1 # The MIT License (MIT)
3 # Copyright (c) 2017 Philippe Proulx <pproulx@efficios.com>
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 from bt2
import native_bt
, object, utils
24 import bt2
.field_types
25 import collections
.abc
33 def _get_leaf_field(obj
):
34 if type(obj
) is not _VariantField
:
37 return _get_leaf_field(obj
.selected_field
)
40 def _create_from_ptr(ptr
):
41 # recreate the field type wrapper of this field's type (the identity
42 # could be different, but the underlying address should be the
44 field_type_ptr
= native_bt
.field_get_type(ptr
)
45 utils
._handle
_ptr
(field_type_ptr
, "cannot get field object's type")
46 field_type
= bt2
.field_types
._create
_from
_ptr
(field_type_ptr
)
47 typeid
= native_bt
.field_type_get_type_id(field_type
._ptr
)
48 field
= _TYPE_ID_TO_OBJ
[typeid
]._create
_from
_ptr
(ptr
)
49 field
._field
_type
= field_type
53 class _Field(object._Object
, metaclass
=abc
.ABCMeta
):
55 ptr
= native_bt
.field_copy(self
._ptr
)
56 utils
._handle
_ptr
(ptr
, 'cannot copy {} field object'.format(self
._NAME
.lower()))
57 return _create_from_ptr(ptr
)
59 def __deepcopy__(self
, memo
):
64 def __eq__(self
, other
):
65 # special case: two unset fields with the same field type are equal
66 if isinstance(other
, _Field
):
67 if not self
.is_set
or not other
.is_set
:
68 if not self
.is_set
and not other
.is_set
and self
.field_type
== other
.field_type
:
72 other
= _get_leaf_field(other
)
73 return self
._spec
_eq
(other
)
77 return self
._field
_type
81 is_set
= native_bt
.field_is_set(self
._ptr
)
85 ret
= native_bt
.field_reset(self
._ptr
)
86 utils
._handle
_ret
(ret
, "cannot reset field object's value")
89 @functools.total_ordering
90 class _NumericField(_Field
):
92 def _extract_value(other
):
93 if other
is True or other
is False:
96 if isinstance(other
, numbers
.Integral
):
99 if isinstance(other
, numbers
.Real
):
102 if isinstance(other
, numbers
.Complex
):
103 return complex(other
)
105 raise TypeError("'{}' object is not a number object".format(other
.__class
__.__name
__))
108 return int(self
._value
)
111 return float(self
._value
)
114 return str(self
._value
)
116 def __lt__(self
, other
):
117 if not isinstance(other
, numbers
.Number
):
118 raise TypeError('unorderable types: {}() < {}()'.format(self
.__class
__.__name
__,
119 other
.__class
__.__name
__))
121 return self
._value
< float(other
)
123 def __le__(self
, other
):
124 if not isinstance(other
, numbers
.Number
):
125 raise TypeError('unorderable types: {}() <= {}()'.format(self
.__class
__.__name
__,
126 other
.__class
__.__name
__))
128 return self
._value
<= float(other
)
130 def _spec_eq(self
, other
):
131 if not isinstance(other
, numbers
.Number
):
134 return self
._value
== complex(other
)
136 def __rmod__(self
, other
):
137 return self
._extract
_value
(other
) % self
._value
139 def __mod__(self
, other
):
140 return self
._value
% self
._extract
_value
(other
)
142 def __rfloordiv__(self
, other
):
143 return self
._extract
_value
(other
) // self
._value
145 def __floordiv__(self
, other
):
146 return self
._value
// self
._extract
_value
(other
)
148 def __round__(self
, ndigits
=None):
150 return round(self
._value
)
152 return round(self
._value
, ndigits
)
155 return math
.ceil(self
._value
)
158 return math
.floor(self
._value
)
161 return int(self
._value
)
164 return abs(self
._value
)
166 def __add__(self
, other
):
167 return self
._value
+ self
._extract
_value
(other
)
169 def __radd__(self
, other
):
170 return self
.__add
__(other
)
178 def __mul__(self
, other
):
179 return self
._value
* self
._extract
_value
(other
)
181 def __rmul__(self
, other
):
182 return self
.__mul
__(other
)
184 def __truediv__(self
, other
):
185 return self
._value
/ self
._extract
_value
(other
)
187 def __rtruediv__(self
, other
):
188 return self
._extract
_value
(other
) / self
._value
190 def __pow__(self
, exponent
):
191 return self
._value
** self
._extract
_value
(exponent
)
193 def __rpow__(self
, base
):
194 return self
._extract
_value
(base
) ** self
._value
196 def __iadd__(self
, other
):
197 self
.value
= self
+ other
200 def __isub__(self
, other
):
201 self
.value
= self
- other
204 def __imul__(self
, other
):
205 self
.value
= self
* other
208 def __itruediv__(self
, other
):
209 self
.value
= self
/ other
212 def __ifloordiv__(self
, other
):
213 self
.value
= self
// other
216 def __imod__(self
, other
):
217 self
.value
= self
% other
220 def __ipow__(self
, other
):
221 self
.value
= self
** other
225 class _IntegralField(_NumericField
, numbers
.Integral
):
226 def __lshift__(self
, other
):
227 return self
._value
<< self
._extract
_value
(other
)
229 def __rlshift__(self
, other
):
230 return self
._extract
_value
(other
) << self
._value
232 def __rshift__(self
, other
):
233 return self
._value
>> self
._extract
_value
(other
)
235 def __rrshift__(self
, other
):
236 return self
._extract
_value
(other
) >> self
._value
238 def __and__(self
, other
):
239 return self
._value
& self
._extract
_value
(other
)
241 def __rand__(self
, other
):
242 return self
._extract
_value
(other
) & self
._value
244 def __xor__(self
, other
):
245 return self
._value ^ self
._extract
_value
(other
)
247 def __rxor__(self
, other
):
248 return self
._extract
_value
(other
) ^ self
._value
250 def __or__(self
, other
):
251 return self
._value | self
._extract
_value
(other
)
253 def __ror__(self
, other
):
254 return self
._extract
_value
(other
) | self
._value
256 def __invert__(self
):
259 def __ilshift__(self
, other
):
260 self
.value
= self
<< other
263 def __irshift__(self
, other
):
264 self
.value
= self
>> other
267 def __iand__(self
, other
):
268 self
.value
= self
& other
271 def __ixor__(self
, other
):
272 self
.value
= self ^ other
275 def __ior__(self
, other
):
276 self
.value
= self | other
280 class _RealField(_NumericField
, numbers
.Real
):
284 class _IntegerField(_IntegralField
):
287 def _value_to_int(self
, value
):
288 if not isinstance(value
, numbers
.Real
):
289 raise TypeError('expecting a real number object')
293 if self
.field_type
.is_signed
:
294 utils
._check
_int
64(value
)
296 utils
._check
_uint
64(value
)
302 if self
.field_type
.is_signed
:
303 ret
, value
= native_bt
.field_signed_integer_get_value(self
._ptr
)
305 ret
, value
= native_bt
.field_unsigned_integer_get_value(self
._ptr
)
311 utils
._handle
_ret
(ret
, "cannot get integer field's value")
315 def _set_value(self
, value
):
316 value
= self
._value
_to
_int
(value
)
318 if self
.field_type
.is_signed
:
319 ret
= native_bt
.field_signed_integer_set_value(self
._ptr
, value
)
321 ret
= native_bt
.field_unsigned_integer_set_value(self
._ptr
, value
)
323 utils
._handle
_ret
(ret
, "cannot set integer field object's value")
325 value
= property(fset
=_set_value
)
328 class _FloatingPointNumberField(_RealField
):
329 _NAME
= 'Floating point number'
331 def _value_to_float(self
, value
):
332 if not isinstance(value
, numbers
.Real
):
333 raise TypeError("expecting a real number object")
339 ret
, value
= native_bt
.field_floating_point_get_value(self
._ptr
)
345 utils
._handle
_ret
(ret
, "cannot get floating point number field's value")
349 def _set_value(self
, value
):
350 value
= self
._value
_to
_float
(value
)
351 ret
= native_bt
.field_floating_point_set_value(self
._ptr
, value
)
352 utils
._handle
_ret
(ret
, "cannot set floating point number field object's value")
354 value
= property(fset
=_set_value
)
357 class _EnumerationField(_IntegerField
):
358 _NAME
= 'Enumeration'
361 def integer_field(self
):
362 int_field_ptr
= native_bt
.field_enumeration_get_container(self
._ptr
)
363 assert(int_field_ptr
)
364 return _create_from_ptr(int_field_ptr
)
366 def _set_value(self
, value
):
367 self
.integer_field
.value
= value
370 labels
= [repr(v
.name
) for v
in self
.mappings
]
371 return '{} ({})'.format(self
._value
, ', '.join(labels
))
373 value
= property(fset
=_set_value
)
377 return self
.integer_field
._value
381 iter_ptr
= native_bt
.field_enumeration_get_mappings(self
._ptr
)
383 return bt2
.field_types
._EnumerationFieldTypeMappingIterator
(iter_ptr
,
384 self
.field_type
.is_signed
)
387 @functools.total_ordering
388 class _StringField(_Field
, collections
.abc
.Sequence
):
391 def _value_to_str(self
, value
):
392 if isinstance(value
, self
.__class
__):
395 if not isinstance(value
, str):
396 raise TypeError("expecting a 'str' object")
402 value
= native_bt
.field_string_get_value(self
._ptr
)
405 def _set_value(self
, value
):
406 value
= self
._value
_to
_str
(value
)
407 ret
= native_bt
.field_string_set_value(self
._ptr
, value
)
408 utils
._handle
_ret
(ret
, "cannot set string field object's value")
410 value
= property(fset
=_set_value
)
412 def _spec_eq(self
, other
):
414 other
= self
._value
_to
_str
(other
)
418 return self
._value
== other
420 def __le__(self
, other
):
421 return self
._value
<= self
._value
_to
_str
(other
)
423 def __lt__(self
, other
):
424 return self
._value
< self
._value
_to
_str
(other
)
427 return bool(self
._value
)
432 def __getitem__(self
, index
):
433 return self
._value
[index
]
436 return len(self
._value
)
438 def __iadd__(self
, value
):
439 value
= self
._value
_to
_str
(value
)
440 ret
= native_bt
.field_string_append(self
._ptr
, value
)
441 utils
._handle
_ret
(ret
, "cannot append to string field object's value")
445 class _ContainerField(_Field
):
447 return len(self
) != 0
450 count
= self
._count
()
454 def __delitem__(self
, index
):
455 raise NotImplementedError
458 class _StructureField(_ContainerField
, collections
.abc
.MutableMapping
):
462 return len(self
.field_type
)
464 def __getitem__(self
, key
):
465 utils
._check
_str
(key
)
466 ptr
= native_bt
.field_structure_get_field_by_name(self
._ptr
, key
)
471 return _create_from_ptr(ptr
)
473 def __setitem__(self
, key
, value
):
474 # raises if key is somehow invalid
477 # the field's property does the appropriate conversion or raises
478 # the appropriate exception
481 def at_index(self
, index
):
482 utils
._check
_uint
64(index
)
484 if index
>= len(self
):
487 field_ptr
= native_bt
.field_structure_get_field_by_index(self
._ptr
, index
)
489 return _create_from_ptr(field_ptr
)
493 return iter(self
.field_type
)
495 def _spec_eq(self
, other
):
497 if len(self
) != len(other
):
500 for self_key
, self_value
in self
.items():
501 if self_key
not in other
:
504 other_value
= other
[self_key
]
506 if self_value
!= other_value
:
515 return {key
: value
._value
for key
, value
in self
.items()}
517 def _set_value(self
, values
):
518 original_values
= self
._value
521 for key
, value
in values
.items():
522 self
[key
].value
= value
524 self
.value
= original_values
527 value
= property(fset
=_set_value
)
530 items
= ['{}: {}'.format(repr(k
), repr(v
)) for k
, v
in self
.items()]
531 return '{{{}}}'.format(', '.join(items
))
534 class _VariantField(_Field
):
539 field_ptr
= native_bt
.field_variant_get_tag(self
._ptr
)
541 if field_ptr
is None:
544 return _create_from_ptr(field_ptr
)
547 def selected_field(self
):
550 def field(self
, tag_field
=None):
551 if tag_field
is None:
552 field_ptr
= native_bt
.field_variant_get_current_field(self
._ptr
)
554 if field_ptr
is None:
557 utils
._check
_type
(tag_field
, _EnumerationField
)
558 field_ptr
= native_bt
.field_variant_get_field(self
._ptr
, tag_field
._ptr
)
559 utils
._handle
_ptr
(field_ptr
, "cannot select variant field object's field")
561 return _create_from_ptr(field_ptr
)
563 def _spec_eq(self
, other
):
564 return _get_leaf_field(self
) == other
567 return bool(self
.selected_field
)
570 return repr(self
._value
)
574 if self
.selected_field
is not None:
575 return self
.selected_field
._value
577 def _set_value(self
, value
):
578 self
.selected_field
.value
= value
580 value
= property(fset
=_set_value
)
583 class _ArraySequenceField(_ContainerField
, collections
.abc
.MutableSequence
):
584 def __getitem__(self
, index
):
585 if not isinstance(index
, numbers
.Integral
):
586 raise TypeError("'{}' is not an integral number object: invalid index".format(index
.__class
__.__name
__))
590 if index
< 0 or index
>= len(self
):
591 raise IndexError('{} field object index is out of range'.format(self
._NAME
))
593 field_ptr
= self
._get
_field
_ptr
_at
_index
(index
)
595 return _create_from_ptr(field_ptr
)
597 def __setitem__(self
, index
, value
):
598 # we can only set numbers and strings
599 if not isinstance(value
, (numbers
.Number
, _StringField
, str)):
600 raise TypeError('expecting number or string object')
602 # raises if index is somehow invalid
605 if not isinstance(field
, (_NumericField
, _StringField
)):
606 raise TypeError('can only set the value of a number or string field')
608 # the field's property does the appropriate conversion or raises
609 # the appropriate exception
612 def insert(self
, index
, value
):
613 raise NotImplementedError
615 def _spec_eq(self
, other
):
617 if len(self
) != len(other
):
620 for self_field
, other_field
in zip(self
, other
):
621 if self_field
!= other_field
:
630 return [field
._value
for field
in self
]
633 return '[{}]'.format(', '.join([repr(v
) for v
in self
]))
636 class _ArrayField(_ArraySequenceField
):
640 return self
.field_type
.length
642 def _get_field_ptr_at_index(self
, index
):
643 return native_bt
.field_array_get_field(self
._ptr
, index
)
645 def _set_value(self
, values
):
646 if len(self
) != len(values
):
648 'expected length of value and array field to match')
650 original_values
= self
._value
652 for index
, value
in enumerate(values
):
653 if value
is not None:
654 self
[index
].value
= value
658 self
.value
= original_values
661 value
= property(fset
=_set_value
)
664 class _SequenceField(_ArraySequenceField
):
668 return int(self
.length_field
)
671 def length_field(self
):
672 field_ptr
= native_bt
.field_sequence_get_length(self
._ptr
)
673 if field_ptr
is None:
675 return _create_from_ptr(field_ptr
)
678 def length_field(self
, length_field
):
679 utils
._check
_type
(length_field
, _IntegerField
)
680 ret
= native_bt
.field_sequence_set_length(self
._ptr
, length_field
._ptr
)
681 utils
._handle
_ret
(ret
, "cannot set sequence field object's length field")
683 def _get_field_ptr_at_index(self
, index
):
684 return native_bt
.field_sequence_get_field(self
._ptr
, index
)
686 def _set_value(self
, values
):
687 original_length_field
= self
.length_field
688 if original_length_field
is not None:
689 original_values
= self
._value
691 if len(values
) != self
.length_field
:
692 if self
.length_field
is not None:
693 length_ft
= self
.length_field
.field_type
695 length_ft
= bt2
.IntegerFieldType(size
=64, is_signed
=False)
696 self
.length_field
= length_ft(len(values
))
699 for index
, value
in enumerate(values
):
700 if value
is not None:
701 self
[index
].value
= value
705 if original_length_field
is not None:
706 self
.length_field
= original_length_field
707 self
.value
= original_values
712 value
= property(fset
=_set_value
)
716 native_bt
.FIELD_TYPE_ID_INTEGER
: _IntegerField
,
717 native_bt
.FIELD_TYPE_ID_FLOAT
: _FloatingPointNumberField
,
718 native_bt
.FIELD_TYPE_ID_ENUM
: _EnumerationField
,
719 native_bt
.FIELD_TYPE_ID_STRING
: _StringField
,
720 native_bt
.FIELD_TYPE_ID_STRUCT
: _StructureField
,
721 native_bt
.FIELD_TYPE_ID_ARRAY
: _ArrayField
,
722 native_bt
.FIELD_TYPE_ID_SEQUENCE
: _SequenceField
,
723 native_bt
.FIELD_TYPE_ID_VARIANT
: _VariantField
,