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 from bt2
import field_class
as bt2_field_class
25 import collections
.abc
31 def _create_field_from_ptr(ptr
, owner_ptr
, owner_get_ref
, owner_put_ref
):
32 field_class_ptr
= native_bt
.field_borrow_class_const(ptr
)
33 typeid
= native_bt
.field_class_get_type(field_class_ptr
)
34 field
= _TYPE_ID_TO_OBJ
[typeid
]._create
_from
_ptr
_and
_get
_ref
(
35 ptr
, owner_ptr
, owner_get_ref
, owner_put_ref
40 # Get the "effective" field of `field`. If `field` is a variant, return the
41 # currently selected field. If `field` is of any other type, return `field`
45 def _get_leaf_field(field
):
46 if not isinstance(field
, _VariantField
):
49 return _get_leaf_field(field
.selected_option
)
52 class _Field(object._UniqueObject
):
53 def __eq__(self
, other
):
54 other
= _get_leaf_field(other
)
55 return self
._spec
_eq
(other
)
58 def field_class(self
):
59 field_class_ptr
= native_bt
.field_borrow_class_const(self
._ptr
)
60 assert field_class_ptr
is not None
61 return bt2_field_class
._create
_field
_class
_from
_ptr
_and
_get
_ref
(field_class_ptr
)
64 raise NotImplementedError
70 @functools.total_ordering
71 class _NumericField(_Field
):
73 def _extract_value(other
):
74 if isinstance(other
, _BoolField
) or isinstance(other
, bool):
77 if isinstance(other
, numbers
.Integral
):
80 if isinstance(other
, numbers
.Real
):
83 if isinstance(other
, numbers
.Complex
):
87 "'{}' object is not a number object".format(other
.__class
__.__name
__)
91 return int(self
._value
)
94 return float(self
._value
)
97 return repr(self
._value
)
99 def __lt__(self
, other
):
100 if not isinstance(other
, numbers
.Number
):
102 'unorderable types: {}() < {}()'.format(
103 self
.__class
__.__name
__, other
.__class
__.__name
__
107 return self
._value
< self
._extract
_value
(other
)
109 def _spec_eq(self
, other
):
111 return self
._value
== self
._extract
_value
(other
)
115 def __rmod__(self
, other
):
116 return self
._extract
_value
(other
) % self
._value
118 def __mod__(self
, other
):
119 return self
._value
% self
._extract
_value
(other
)
121 def __rfloordiv__(self
, other
):
122 return self
._extract
_value
(other
) // self
._value
124 def __floordiv__(self
, other
):
125 return self
._value
// self
._extract
_value
(other
)
127 def __round__(self
, ndigits
=None):
129 return round(self
._value
)
131 return round(self
._value
, ndigits
)
134 return math
.ceil(self
._value
)
137 return math
.floor(self
._value
)
140 return int(self
._value
)
143 return abs(self
._value
)
145 def __add__(self
, other
):
146 return self
._value
+ self
._extract
_value
(other
)
148 def __radd__(self
, other
):
149 return self
.__add
__(other
)
157 def __mul__(self
, other
):
158 return self
._value
* self
._extract
_value
(other
)
160 def __rmul__(self
, other
):
161 return self
.__mul
__(other
)
163 def __truediv__(self
, other
):
164 return self
._value
/ self
._extract
_value
(other
)
166 def __rtruediv__(self
, other
):
167 return self
._extract
_value
(other
) / self
._value
169 def __pow__(self
, exponent
):
170 return self
._value
** self
._extract
_value
(exponent
)
172 def __rpow__(self
, base
):
173 return self
._extract
_value
(base
) ** self
._value
176 class _IntegralField(_NumericField
, numbers
.Integral
):
177 def __lshift__(self
, other
):
178 return self
._value
<< self
._extract
_value
(other
)
180 def __rlshift__(self
, other
):
181 return self
._extract
_value
(other
) << self
._value
183 def __rshift__(self
, other
):
184 return self
._value
>> self
._extract
_value
(other
)
186 def __rrshift__(self
, other
):
187 return self
._extract
_value
(other
) >> self
._value
189 def __and__(self
, other
):
190 return self
._value
& self
._extract
_value
(other
)
192 def __rand__(self
, other
):
193 return self
._extract
_value
(other
) & self
._value
195 def __xor__(self
, other
):
196 return self
._value ^ self
._extract
_value
(other
)
198 def __rxor__(self
, other
):
199 return self
._extract
_value
(other
) ^ self
._value
201 def __or__(self
, other
):
202 return self
._value | self
._extract
_value
(other
)
204 def __ror__(self
, other
):
205 return self
._extract
_value
(other
) | self
._value
207 def __invert__(self
):
211 class _BoolField(_IntegralField
, _Field
):
217 def _value_to_bool(self
, value
):
218 if isinstance(value
, _BoolField
):
221 if not isinstance(value
, bool):
223 "'{}' object is not a 'bool' or '_BoolField' object".format(
232 return bool(native_bt
.field_bool_get_value(self
._ptr
))
234 def _set_value(self
, value
):
235 value
= self
._value
_to
_bool
(value
)
236 native_bt
.field_bool_set_value(self
._ptr
, value
)
238 value
= property(fset
=_set_value
)
241 class _IntegerField(_IntegralField
, _Field
):
245 class _UnsignedIntegerField(_IntegerField
, _Field
):
246 _NAME
= 'Unsigned integer'
248 def _value_to_int(self
, value
):
249 if not isinstance(value
, numbers
.Integral
):
250 raise TypeError('expecting an integral number object')
253 utils
._check
_uint
64(value
)
259 return native_bt
.field_integer_unsigned_get_value(self
._ptr
)
261 def _set_value(self
, value
):
262 value
= self
._value
_to
_int
(value
)
263 native_bt
.field_integer_unsigned_set_value(self
._ptr
, value
)
265 value
= property(fset
=_set_value
)
268 class _SignedIntegerField(_IntegerField
, _Field
):
269 _NAME
= 'Signed integer'
271 def _value_to_int(self
, value
):
272 if not isinstance(value
, numbers
.Integral
):
273 raise TypeError('expecting an integral number object')
276 utils
._check
_int
64(value
)
282 return native_bt
.field_integer_signed_get_value(self
._ptr
)
284 def _set_value(self
, value
):
285 value
= self
._value
_to
_int
(value
)
286 native_bt
.field_integer_signed_set_value(self
._ptr
, value
)
288 value
= property(fset
=_set_value
)
291 class _RealField(_NumericField
, numbers
.Real
):
294 def _value_to_float(self
, value
):
295 if not isinstance(value
, numbers
.Real
):
296 raise TypeError("expecting a real number object")
302 return native_bt
.field_real_get_value(self
._ptr
)
304 def _set_value(self
, value
):
305 value
= self
._value
_to
_float
(value
)
306 native_bt
.field_real_set_value(self
._ptr
, value
)
308 value
= property(fset
=_set_value
)
311 class _EnumerationField(_IntegerField
):
313 return '{} ({})'.format(self
._value
, ', '.join(self
.labels
))
317 status
, labels
= self
._get
_mapping
_labels
(self
._ptr
)
318 utils
._handle
_func
_status
(status
, "cannot get label for enumeration field")
320 assert labels
is not None
324 class _UnsignedEnumerationField(_EnumerationField
, _UnsignedIntegerField
):
325 _NAME
= 'Unsigned Enumeration'
326 _get_mapping_labels
= staticmethod(
327 native_bt
.field_enumeration_unsigned_get_mapping_labels
331 class _SignedEnumerationField(_EnumerationField
, _SignedIntegerField
):
332 _NAME
= 'Signed Enumeration'
333 _get_mapping_labels
= staticmethod(
334 native_bt
.field_enumeration_signed_get_mapping_labels
338 @functools.total_ordering
339 class _StringField(_Field
):
342 def _value_to_str(self
, value
):
343 if isinstance(value
, self
.__class
__):
346 if not isinstance(value
, str):
347 raise TypeError("expecting a 'str' object")
353 return native_bt
.field_string_get_value(self
._ptr
)
355 def _set_value(self
, value
):
356 value
= self
._value
_to
_str
(value
)
357 native_bt
.field_string_set_value(self
._ptr
, value
)
359 value
= property(fset
=_set_value
)
361 def _spec_eq(self
, other
):
363 return self
._value
== self
._value
_to
_str
(other
)
367 def __lt__(self
, other
):
368 return self
._value
< self
._value
_to
_str
(other
)
371 return bool(self
._value
)
374 return repr(self
._value
)
377 return str(self
._value
)
379 def __getitem__(self
, index
):
380 return self
._value
[index
]
383 return native_bt
.field_string_get_length(self
._ptr
)
385 def __iadd__(self
, value
):
386 value
= self
._value
_to
_str
(value
)
387 status
= native_bt
.field_string_append(self
._ptr
, value
)
388 utils
._handle
_func
_status
(
389 status
, "cannot append to string field object's value"
394 class _ContainerField(_Field
):
396 return len(self
) != 0
399 count
= self
._count
()
403 def __delitem__(self
, index
):
404 raise NotImplementedError
407 class _StructureField(_ContainerField
, collections
.abc
.MutableMapping
):
411 return len(self
.field_class
)
413 def __setitem__(self
, key
, value
):
414 # raises if key is somehow invalid
417 # the field's property does the appropriate conversion or raises
418 # the appropriate exception
423 return iter(self
.field_class
)
425 def _spec_eq(self
, other
):
426 if not isinstance(other
, collections
.abc
.Mapping
):
429 if len(self
) != len(other
):
433 for self_key
in self
:
434 if self_key
not in other
:
437 if self
[self_key
] != other
[self_key
]:
442 def _set_value(self
, values
):
444 for key
, value
in values
.items():
445 self
[key
].value
= value
449 value
= property(fset
=_set_value
)
452 items
= ['{}: {}'.format(repr(k
), repr(v
)) for k
, v
in self
.items()]
453 return '{{{}}}'.format(', '.join(items
))
455 def __getitem__(self
, key
):
456 utils
._check
_str
(key
)
457 field_ptr
= native_bt
.field_structure_borrow_member_field_by_name(
461 if field_ptr
is None:
464 return _create_field_from_ptr(
465 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
468 def member_at_index(self
, index
):
469 utils
._check
_uint
64(index
)
471 if index
>= len(self
):
474 field_ptr
= native_bt
.field_structure_borrow_member_field_by_index(
477 assert field_ptr
is not None
478 return _create_field_from_ptr(
479 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
483 class _VariantField(_ContainerField
, _Field
):
487 def selected_option_index(self
):
488 return native_bt
.field_variant_get_selected_option_field_index(self
._ptr
)
490 @selected_option_index.setter
491 def selected_option_index(self
, index
):
492 native_bt
.field_variant_select_option_field_by_index(self
._ptr
, index
)
495 def selected_option(self
):
496 # TODO: Is there a way to check if the variant field has a selected_option,
497 # so we can raise an exception instead of hitting a pre-condition check?
498 # If there is something, that check should be added to selected_option_index too.
499 field_ptr
= native_bt
.field_variant_borrow_selected_option_field(self
._ptr
)
501 return _create_field_from_ptr(
502 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
505 def _spec_eq(self
, other
):
506 return _get_leaf_field(self
) == other
509 raise NotImplementedError
512 return str(self
.selected_option
)
515 return repr(self
.selected_option
)
517 def _set_value(self
, value
):
518 self
.selected_option
.value
= value
520 value
= property(fset
=_set_value
)
523 class _ArrayField(_ContainerField
, _Field
, collections
.abc
.MutableSequence
):
524 def _get_length(self
):
525 return native_bt
.field_array_get_length(self
._ptr
)
527 length
= property(fget
=_get_length
)
529 def __getitem__(self
, index
):
530 if not isinstance(index
, numbers
.Integral
):
532 "'{}' is not an integral number object: invalid index".format(
533 index
.__class
__.__name
__
539 if index
< 0 or index
>= len(self
):
540 raise IndexError('{} field object index is out of range'.format(self
._NAME
))
542 field_ptr
= native_bt
.field_array_borrow_element_field_by_index(
546 return _create_field_from_ptr(
547 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
550 def __setitem__(self
, index
, value
):
551 # raises if index is somehow invalid
554 if not isinstance(field
, (_NumericField
, _StringField
)):
555 raise TypeError('can only set the value of a number or string field')
557 # the field's property does the appropriate conversion or raises
558 # the appropriate exception
561 def insert(self
, index
, value
):
562 raise NotImplementedError
564 def _spec_eq(self
, other
):
565 if not isinstance(other
, collections
.abc
.Sequence
):
568 if len(self
) != len(other
):
572 for self_elem
, other_elem
in zip(self
, other
):
573 if self_elem
!= other_elem
:
579 return '[{}]'.format(', '.join([repr(v
) for v
in self
]))
582 class _StaticArrayField(_ArrayField
, _Field
):
583 _NAME
= 'Static array'
586 return native_bt
.field_array_get_length(self
._ptr
)
588 def _set_value(self
, values
):
589 if len(self
) != len(values
):
590 raise ValueError('expected length of value and array field to match')
592 for index
, value
in enumerate(values
):
593 if value
is not None:
594 self
[index
].value
= value
596 value
= property(fset
=_set_value
)
599 class _DynamicArrayField(_ArrayField
, _Field
):
600 _NAME
= 'Dynamic array'
605 def _set_length(self
, length
):
606 utils
._check
_uint
64(length
)
607 status
= native_bt
.field_array_dynamic_set_length(self
._ptr
, length
)
608 utils
._handle
_func
_status
(status
, "cannot set dynamic array length")
610 length
= property(fget
=_ArrayField
._get
_length
, fset
=_set_length
)
612 def _set_value(self
, values
):
613 if len(values
) != self
.length
:
614 self
.length
= len(values
)
616 for index
, value
in enumerate(values
):
617 if value
is not None:
618 self
[index
].value
= value
620 value
= property(fset
=_set_value
)
624 native_bt
.FIELD_CLASS_TYPE_BOOL
: _BoolField
,
625 native_bt
.FIELD_CLASS_TYPE_UNSIGNED_INTEGER
: _UnsignedIntegerField
,
626 native_bt
.FIELD_CLASS_TYPE_SIGNED_INTEGER
: _SignedIntegerField
,
627 native_bt
.FIELD_CLASS_TYPE_REAL
: _RealField
,
628 native_bt
.FIELD_CLASS_TYPE_UNSIGNED_ENUMERATION
: _UnsignedEnumerationField
,
629 native_bt
.FIELD_CLASS_TYPE_SIGNED_ENUMERATION
: _SignedEnumerationField
,
630 native_bt
.FIELD_CLASS_TYPE_STRING
: _StringField
,
631 native_bt
.FIELD_CLASS_TYPE_STRUCTURE
: _StructureField
,
632 native_bt
.FIELD_CLASS_TYPE_STATIC_ARRAY
: _StaticArrayField
,
633 native_bt
.FIELD_CLASS_TYPE_DYNAMIC_ARRAY
: _DynamicArrayField
,
634 native_bt
.FIELD_CLASS_TYPE_VARIANT_WITHOUT_SELECTOR
: _VariantField
,
635 native_bt
.FIELD_CLASS_TYPE_VARIANT_WITH_UNSIGNED_SELECTOR
: _VariantField
,
636 native_bt
.FIELD_CLASS_TYPE_VARIANT_WITH_SIGNED_SELECTOR
: _VariantField
,