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
41 # the currently selected field. If `field` is an option, return the
42 # content field. If `field` is of any other type, return `field`
46 def _get_leaf_field(field
):
47 if isinstance(field
, _VariantField
):
48 return _get_leaf_field(field
.selected_option
)
50 if isinstance(field
, _OptionField
):
51 return _get_leaf_field(field
.field
)
56 class _Field(object._UniqueObject
):
57 def __eq__(self
, other
):
58 other
= _get_leaf_field(other
)
59 return self
._spec
_eq
(other
)
62 def field_class(self
):
63 field_class_ptr
= native_bt
.field_borrow_class_const(self
._ptr
)
64 assert field_class_ptr
is not None
65 return bt2_field_class
._create
_field
_class
_from
_ptr
_and
_get
_ref
(field_class_ptr
)
68 raise NotImplementedError
74 @functools.total_ordering
75 class _NumericField(_Field
):
77 def _extract_value(other
):
78 if isinstance(other
, _BoolField
) or isinstance(other
, bool):
81 if isinstance(other
, numbers
.Integral
):
84 if isinstance(other
, numbers
.Real
):
87 if isinstance(other
, numbers
.Complex
):
91 "'{}' object is not a number object".format(other
.__class
__.__name
__)
95 return int(self
._value
)
98 return float(self
._value
)
101 return repr(self
._value
)
103 def __lt__(self
, other
):
104 if not isinstance(other
, numbers
.Number
):
106 'unorderable types: {}() < {}()'.format(
107 self
.__class
__.__name
__, other
.__class
__.__name
__
111 return self
._value
< self
._extract
_value
(other
)
113 def _spec_eq(self
, other
):
115 return self
._value
== self
._extract
_value
(other
)
119 def __rmod__(self
, other
):
120 return self
._extract
_value
(other
) % self
._value
122 def __mod__(self
, other
):
123 return self
._value
% self
._extract
_value
(other
)
125 def __rfloordiv__(self
, other
):
126 return self
._extract
_value
(other
) // self
._value
128 def __floordiv__(self
, other
):
129 return self
._value
// self
._extract
_value
(other
)
131 def __round__(self
, ndigits
=None):
133 return round(self
._value
)
135 return round(self
._value
, ndigits
)
138 return math
.ceil(self
._value
)
141 return math
.floor(self
._value
)
144 return int(self
._value
)
147 return abs(self
._value
)
149 def __add__(self
, other
):
150 return self
._value
+ self
._extract
_value
(other
)
152 def __radd__(self
, other
):
153 return self
.__add
__(other
)
161 def __mul__(self
, other
):
162 return self
._value
* self
._extract
_value
(other
)
164 def __rmul__(self
, other
):
165 return self
.__mul
__(other
)
167 def __truediv__(self
, other
):
168 return self
._value
/ self
._extract
_value
(other
)
170 def __rtruediv__(self
, other
):
171 return self
._extract
_value
(other
) / self
._value
173 def __pow__(self
, exponent
):
174 return self
._value
** self
._extract
_value
(exponent
)
176 def __rpow__(self
, base
):
177 return self
._extract
_value
(base
) ** self
._value
180 class _IntegralField(_NumericField
, numbers
.Integral
):
181 def __lshift__(self
, other
):
182 return self
._value
<< self
._extract
_value
(other
)
184 def __rlshift__(self
, other
):
185 return self
._extract
_value
(other
) << self
._value
187 def __rshift__(self
, other
):
188 return self
._value
>> self
._extract
_value
(other
)
190 def __rrshift__(self
, other
):
191 return self
._extract
_value
(other
) >> self
._value
193 def __and__(self
, other
):
194 return self
._value
& self
._extract
_value
(other
)
196 def __rand__(self
, other
):
197 return self
._extract
_value
(other
) & self
._value
199 def __xor__(self
, other
):
200 return self
._value ^ self
._extract
_value
(other
)
202 def __rxor__(self
, other
):
203 return self
._extract
_value
(other
) ^ self
._value
205 def __or__(self
, other
):
206 return self
._value | self
._extract
_value
(other
)
208 def __ror__(self
, other
):
209 return self
._extract
_value
(other
) | self
._value
211 def __invert__(self
):
215 class _BoolField(_IntegralField
, _Field
):
221 def _value_to_bool(self
, value
):
222 if isinstance(value
, _BoolField
):
225 if not isinstance(value
, bool):
227 "'{}' object is not a 'bool' or '_BoolField' object".format(
236 return bool(native_bt
.field_bool_get_value(self
._ptr
))
238 def _set_value(self
, value
):
239 value
= self
._value
_to
_bool
(value
)
240 native_bt
.field_bool_set_value(self
._ptr
, value
)
242 value
= property(fset
=_set_value
)
245 class _IntegerField(_IntegralField
, _Field
):
249 class _UnsignedIntegerField(_IntegerField
, _Field
):
250 _NAME
= 'Unsigned integer'
252 def _value_to_int(self
, value
):
253 if not isinstance(value
, numbers
.Integral
):
254 raise TypeError('expecting an integral number object')
257 utils
._check
_uint
64(value
)
263 return native_bt
.field_integer_unsigned_get_value(self
._ptr
)
265 def _set_value(self
, value
):
266 value
= self
._value
_to
_int
(value
)
267 native_bt
.field_integer_unsigned_set_value(self
._ptr
, value
)
269 value
= property(fset
=_set_value
)
272 class _SignedIntegerField(_IntegerField
, _Field
):
273 _NAME
= 'Signed integer'
275 def _value_to_int(self
, value
):
276 if not isinstance(value
, numbers
.Integral
):
277 raise TypeError('expecting an integral number object')
280 utils
._check
_int
64(value
)
286 return native_bt
.field_integer_signed_get_value(self
._ptr
)
288 def _set_value(self
, value
):
289 value
= self
._value
_to
_int
(value
)
290 native_bt
.field_integer_signed_set_value(self
._ptr
, value
)
292 value
= property(fset
=_set_value
)
295 class _RealField(_NumericField
, numbers
.Real
):
298 def _value_to_float(self
, value
):
299 if not isinstance(value
, numbers
.Real
):
300 raise TypeError("expecting a real number object")
306 return native_bt
.field_real_get_value(self
._ptr
)
308 def _set_value(self
, value
):
309 value
= self
._value
_to
_float
(value
)
310 native_bt
.field_real_set_value(self
._ptr
, value
)
312 value
= property(fset
=_set_value
)
315 class _EnumerationField(_IntegerField
):
317 return '{} ({})'.format(self
._value
, ', '.join(self
.labels
))
321 status
, labels
= self
._get
_mapping
_labels
(self
._ptr
)
322 utils
._handle
_func
_status
(status
, "cannot get label for enumeration field")
324 assert labels
is not None
328 class _UnsignedEnumerationField(_EnumerationField
, _UnsignedIntegerField
):
329 _NAME
= 'Unsigned Enumeration'
330 _get_mapping_labels
= staticmethod(
331 native_bt
.field_enumeration_unsigned_get_mapping_labels
335 class _SignedEnumerationField(_EnumerationField
, _SignedIntegerField
):
336 _NAME
= 'Signed Enumeration'
337 _get_mapping_labels
= staticmethod(
338 native_bt
.field_enumeration_signed_get_mapping_labels
342 @functools.total_ordering
343 class _StringField(_Field
):
346 def _value_to_str(self
, value
):
347 if isinstance(value
, self
.__class
__):
350 if not isinstance(value
, str):
351 raise TypeError("expecting a 'str' object")
357 return native_bt
.field_string_get_value(self
._ptr
)
359 def _set_value(self
, value
):
360 value
= self
._value
_to
_str
(value
)
361 native_bt
.field_string_set_value(self
._ptr
, value
)
363 value
= property(fset
=_set_value
)
365 def _spec_eq(self
, other
):
367 return self
._value
== self
._value
_to
_str
(other
)
371 def __lt__(self
, other
):
372 return self
._value
< self
._value
_to
_str
(other
)
375 return bool(self
._value
)
378 return repr(self
._value
)
381 return str(self
._value
)
383 def __getitem__(self
, index
):
384 return self
._value
[index
]
387 return native_bt
.field_string_get_length(self
._ptr
)
389 def __iadd__(self
, value
):
390 value
= self
._value
_to
_str
(value
)
391 status
= native_bt
.field_string_append(self
._ptr
, value
)
392 utils
._handle
_func
_status
(
393 status
, "cannot append to string field object's value"
398 class _ContainerField(_Field
):
400 return len(self
) != 0
403 count
= self
._count
()
407 def __delitem__(self
, index
):
408 raise NotImplementedError
411 class _StructureField(_ContainerField
, collections
.abc
.MutableMapping
):
415 return len(self
.field_class
)
417 def __setitem__(self
, key
, value
):
418 # raises if key is somehow invalid
421 # the field's property does the appropriate conversion or raises
422 # the appropriate exception
427 return iter(self
.field_class
)
429 def _spec_eq(self
, other
):
430 if not isinstance(other
, collections
.abc
.Mapping
):
433 if len(self
) != len(other
):
437 for self_key
in self
:
438 if self_key
not in other
:
441 if self
[self_key
] != other
[self_key
]:
446 def _set_value(self
, values
):
448 for key
, value
in values
.items():
449 self
[key
].value
= value
453 value
= property(fset
=_set_value
)
456 items
= ['{}: {}'.format(repr(k
), repr(v
)) for k
, v
in self
.items()]
457 return '{{{}}}'.format(', '.join(items
))
459 def __getitem__(self
, key
):
460 utils
._check
_str
(key
)
461 field_ptr
= native_bt
.field_structure_borrow_member_field_by_name(
465 if field_ptr
is None:
468 return _create_field_from_ptr(
469 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
472 def member_at_index(self
, index
):
473 utils
._check
_uint
64(index
)
475 if index
>= len(self
):
478 field_ptr
= native_bt
.field_structure_borrow_member_field_by_index(
481 assert field_ptr
is not None
482 return _create_field_from_ptr(
483 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
487 class _OptionField(_Field
):
492 field_ptr
= native_bt
.field_option_borrow_field_const(self
._ptr
)
494 if field_ptr
is None:
497 return _create_field_from_ptr(
498 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
503 return self
.field
is not None
506 def has_field(self
, value
):
507 utils
._check
_bool
(value
)
508 native_bt
.field_option_set_has_field(self
._ptr
, value
)
510 def _spec_eq(self
, other
):
511 return _get_leaf_field(self
) == other
514 return self
.has_field
517 return str(self
.field
)
520 return repr(self
.field
)
522 def _set_value(self
, value
):
523 self
.has_field
= True
525 assert field
is not None
528 value
= property(fset
=_set_value
)
531 class _VariantField(_ContainerField
, _Field
):
535 def selected_option_index(self
):
536 return native_bt
.field_variant_get_selected_option_field_index(self
._ptr
)
538 @selected_option_index.setter
539 def selected_option_index(self
, index
):
540 native_bt
.field_variant_select_option_field_by_index(self
._ptr
, index
)
543 def selected_option(self
):
544 # TODO: Is there a way to check if the variant field has a selected_option,
545 # so we can raise an exception instead of hitting a pre-condition check?
546 # If there is something, that check should be added to selected_option_index too.
547 field_ptr
= native_bt
.field_variant_borrow_selected_option_field(self
._ptr
)
549 return _create_field_from_ptr(
550 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
553 def _spec_eq(self
, other
):
554 return _get_leaf_field(self
) == other
557 raise NotImplementedError
560 return str(self
.selected_option
)
563 return repr(self
.selected_option
)
565 def _set_value(self
, value
):
566 self
.selected_option
.value
= value
568 value
= property(fset
=_set_value
)
571 class _ArrayField(_ContainerField
, _Field
, collections
.abc
.MutableSequence
):
572 def _get_length(self
):
573 return native_bt
.field_array_get_length(self
._ptr
)
575 length
= property(fget
=_get_length
)
577 def __getitem__(self
, index
):
578 if not isinstance(index
, numbers
.Integral
):
580 "'{}' is not an integral number object: invalid index".format(
581 index
.__class
__.__name
__
587 if index
< 0 or index
>= len(self
):
588 raise IndexError('{} field object index is out of range'.format(self
._NAME
))
590 field_ptr
= native_bt
.field_array_borrow_element_field_by_index(
594 return _create_field_from_ptr(
595 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
598 def __setitem__(self
, index
, value
):
599 # raises if index is somehow invalid
602 if not isinstance(field
, (_NumericField
, _StringField
)):
603 raise TypeError('can only set the value of a number or string field')
605 # the field's property does the appropriate conversion or raises
606 # the appropriate exception
609 def insert(self
, index
, value
):
610 raise NotImplementedError
612 def _spec_eq(self
, other
):
613 if not isinstance(other
, collections
.abc
.Sequence
):
616 if len(self
) != len(other
):
620 for self_elem
, other_elem
in zip(self
, other
):
621 if self_elem
!= other_elem
:
627 return '[{}]'.format(', '.join([repr(v
) for v
in self
]))
630 class _StaticArrayField(_ArrayField
, _Field
):
631 _NAME
= 'Static array'
634 return native_bt
.field_array_get_length(self
._ptr
)
636 def _set_value(self
, values
):
637 if len(self
) != len(values
):
638 raise ValueError('expected length of value and array field to match')
640 for index
, value
in enumerate(values
):
641 if value
is not None:
642 self
[index
].value
= value
644 value
= property(fset
=_set_value
)
647 class _DynamicArrayField(_ArrayField
, _Field
):
648 _NAME
= 'Dynamic array'
653 def _set_length(self
, length
):
654 utils
._check
_uint
64(length
)
655 status
= native_bt
.field_array_dynamic_set_length(self
._ptr
, length
)
656 utils
._handle
_func
_status
(status
, "cannot set dynamic array length")
658 length
= property(fget
=_ArrayField
._get
_length
, fset
=_set_length
)
660 def _set_value(self
, values
):
661 if len(values
) != self
.length
:
662 self
.length
= len(values
)
664 for index
, value
in enumerate(values
):
665 if value
is not None:
666 self
[index
].value
= value
668 value
= property(fset
=_set_value
)
672 native_bt
.FIELD_CLASS_TYPE_BOOL
: _BoolField
,
673 native_bt
.FIELD_CLASS_TYPE_UNSIGNED_INTEGER
: _UnsignedIntegerField
,
674 native_bt
.FIELD_CLASS_TYPE_SIGNED_INTEGER
: _SignedIntegerField
,
675 native_bt
.FIELD_CLASS_TYPE_REAL
: _RealField
,
676 native_bt
.FIELD_CLASS_TYPE_UNSIGNED_ENUMERATION
: _UnsignedEnumerationField
,
677 native_bt
.FIELD_CLASS_TYPE_SIGNED_ENUMERATION
: _SignedEnumerationField
,
678 native_bt
.FIELD_CLASS_TYPE_STRING
: _StringField
,
679 native_bt
.FIELD_CLASS_TYPE_STRUCTURE
: _StructureField
,
680 native_bt
.FIELD_CLASS_TYPE_STATIC_ARRAY
: _StaticArrayField
,
681 native_bt
.FIELD_CLASS_TYPE_DYNAMIC_ARRAY
: _DynamicArrayField
,
682 native_bt
.FIELD_CLASS_TYPE_OPTION
: _OptionField
,
683 native_bt
.FIELD_CLASS_TYPE_VARIANT_WITHOUT_SELECTOR
: _VariantField
,
684 native_bt
.FIELD_CLASS_TYPE_VARIANT_WITH_UNSIGNED_SELECTOR
: _VariantField
,
685 native_bt
.FIELD_CLASS_TYPE_VARIANT_WITH_SIGNED_SELECTOR
: _VariantField
,