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
, 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 _IntegerField(_IntegralField
, _Field
):
215 class _UnsignedIntegerField(_IntegerField
, _Field
):
216 _NAME
= 'Unsigned integer'
218 def _value_to_int(self
, value
):
219 if not isinstance(value
, numbers
.Integral
):
220 raise TypeError('expecting an integral number object')
223 utils
._check
_uint
64(value
)
229 return native_bt
.field_integer_unsigned_get_value(self
._ptr
)
231 def _set_value(self
, value
):
232 value
= self
._value
_to
_int
(value
)
233 native_bt
.field_integer_unsigned_set_value(self
._ptr
, value
)
235 value
= property(fset
=_set_value
)
238 class _SignedIntegerField(_IntegerField
, _Field
):
239 _NAME
= 'Signed integer'
241 def _value_to_int(self
, value
):
242 if not isinstance(value
, numbers
.Integral
):
243 raise TypeError('expecting an integral number object')
246 utils
._check
_int
64(value
)
252 return native_bt
.field_integer_signed_get_value(self
._ptr
)
254 def _set_value(self
, value
):
255 value
= self
._value
_to
_int
(value
)
256 native_bt
.field_integer_signed_set_value(self
._ptr
, value
)
258 value
= property(fset
=_set_value
)
261 class _RealField(_NumericField
, numbers
.Real
):
264 def _value_to_float(self
, value
):
265 if not isinstance(value
, numbers
.Real
):
266 raise TypeError("expecting a real number object")
272 return native_bt
.field_real_get_value(self
._ptr
)
274 def _set_value(self
, value
):
275 value
= self
._value
_to
_float
(value
)
276 native_bt
.field_real_set_value(self
._ptr
, value
)
278 value
= property(fset
=_set_value
)
281 class _EnumerationField(_IntegerField
):
283 return '{} ({})'.format(self
._value
, ', '.join(self
.labels
))
287 status
, labels
= self
._get
_mapping
_labels
(self
._ptr
)
288 utils
._handle
_func
_status
(status
, "cannot get label for enumeration field")
290 assert labels
is not None
294 class _UnsignedEnumerationField(_EnumerationField
, _UnsignedIntegerField
):
295 _NAME
= 'Unsigned Enumeration'
296 _get_mapping_labels
= staticmethod(
297 native_bt
.field_enumeration_unsigned_get_mapping_labels
301 class _SignedEnumerationField(_EnumerationField
, _SignedIntegerField
):
302 _NAME
= 'Signed Enumeration'
303 _get_mapping_labels
= staticmethod(
304 native_bt
.field_enumeration_signed_get_mapping_labels
308 @functools.total_ordering
309 class _StringField(_Field
):
312 def _value_to_str(self
, value
):
313 if isinstance(value
, self
.__class
__):
316 if not isinstance(value
, str):
317 raise TypeError("expecting a 'str' object")
323 return native_bt
.field_string_get_value(self
._ptr
)
325 def _set_value(self
, value
):
326 value
= self
._value
_to
_str
(value
)
327 native_bt
.field_string_set_value(self
._ptr
, value
)
329 value
= property(fset
=_set_value
)
331 def _spec_eq(self
, other
):
333 return self
._value
== self
._value
_to
_str
(other
)
337 def __lt__(self
, other
):
338 return self
._value
< self
._value
_to
_str
(other
)
341 return bool(self
._value
)
344 return repr(self
._value
)
347 return str(self
._value
)
349 def __getitem__(self
, index
):
350 return self
._value
[index
]
353 return native_bt
.field_string_get_length(self
._ptr
)
355 def __iadd__(self
, value
):
356 value
= self
._value
_to
_str
(value
)
357 status
= native_bt
.field_string_append(self
._ptr
, value
)
358 utils
._handle
_func
_status
(
359 status
, "cannot append to string field object's value"
364 class _ContainerField(_Field
):
366 return len(self
) != 0
369 count
= self
._count
()
373 def __delitem__(self
, index
):
374 raise NotImplementedError
377 class _StructureField(_ContainerField
, collections
.abc
.MutableMapping
):
381 return len(self
.field_class
)
383 def __setitem__(self
, key
, value
):
384 # raises if key is somehow invalid
387 # the field's property does the appropriate conversion or raises
388 # the appropriate exception
393 return iter(self
.field_class
)
395 def _spec_eq(self
, other
):
396 if not isinstance(other
, collections
.abc
.Mapping
):
399 if len(self
) != len(other
):
403 for self_key
in self
:
404 if self_key
not in other
:
407 if self
[self_key
] != other
[self_key
]:
412 def _set_value(self
, values
):
414 for key
, value
in values
.items():
415 self
[key
].value
= value
419 value
= property(fset
=_set_value
)
422 items
= ['{}: {}'.format(repr(k
), repr(v
)) for k
, v
in self
.items()]
423 return '{{{}}}'.format(', '.join(items
))
425 def __getitem__(self
, key
):
426 utils
._check
_str
(key
)
427 field_ptr
= native_bt
.field_structure_borrow_member_field_by_name(
431 if field_ptr
is None:
434 return _create_field_from_ptr(
435 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
438 def member_at_index(self
, index
):
439 utils
._check
_uint
64(index
)
441 if index
>= len(self
):
444 field_ptr
= native_bt
.field_structure_borrow_member_field_by_index(
447 assert field_ptr
is not None
448 return _create_field_from_ptr(
449 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
453 class _VariantField(_ContainerField
, _Field
):
457 def selected_option_index(self
):
458 return native_bt
.field_variant_get_selected_option_field_index(self
._ptr
)
460 @selected_option_index.setter
461 def selected_option_index(self
, index
):
462 native_bt
.field_variant_select_option_field_by_index(self
._ptr
, index
)
465 def selected_option(self
):
466 # TODO: Is there a way to check if the variant field has a selected_option,
467 # so we can raise an exception instead of hitting a pre-condition check?
468 # If there is something, that check should be added to selected_option_index too.
469 field_ptr
= native_bt
.field_variant_borrow_selected_option_field(self
._ptr
)
471 return _create_field_from_ptr(
472 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
475 def _spec_eq(self
, other
):
476 return _get_leaf_field(self
) == other
479 raise NotImplementedError
482 return str(self
.selected_option
)
485 return repr(self
.selected_option
)
487 def _set_value(self
, value
):
488 self
.selected_option
.value
= value
490 value
= property(fset
=_set_value
)
493 class _ArrayField(_ContainerField
, _Field
, collections
.abc
.MutableSequence
):
494 def _get_length(self
):
495 return native_bt
.field_array_get_length(self
._ptr
)
497 length
= property(fget
=_get_length
)
499 def __getitem__(self
, index
):
500 if not isinstance(index
, numbers
.Integral
):
502 "'{}' is not an integral number object: invalid index".format(
503 index
.__class
__.__name
__
509 if index
< 0 or index
>= len(self
):
510 raise IndexError('{} field object index is out of range'.format(self
._NAME
))
512 field_ptr
= native_bt
.field_array_borrow_element_field_by_index(
516 return _create_field_from_ptr(
517 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
520 def __setitem__(self
, index
, value
):
521 # raises if index is somehow invalid
524 if not isinstance(field
, (_NumericField
, _StringField
)):
525 raise TypeError('can only set the value of a number or string field')
527 # the field's property does the appropriate conversion or raises
528 # the appropriate exception
531 def insert(self
, index
, value
):
532 raise NotImplementedError
534 def _spec_eq(self
, other
):
535 if not isinstance(other
, collections
.abc
.Sequence
):
538 if len(self
) != len(other
):
542 for self_elem
, other_elem
in zip(self
, other
):
543 if self_elem
!= other_elem
:
549 return '[{}]'.format(', '.join([repr(v
) for v
in self
]))
552 class _StaticArrayField(_ArrayField
, _Field
):
553 _NAME
= 'Static array'
556 return native_bt
.field_array_get_length(self
._ptr
)
558 def _set_value(self
, values
):
559 if len(self
) != len(values
):
560 raise ValueError('expected length of value and array field to match')
562 for index
, value
in enumerate(values
):
563 if value
is not None:
564 self
[index
].value
= value
566 value
= property(fset
=_set_value
)
569 class _DynamicArrayField(_ArrayField
, _Field
):
570 _NAME
= 'Dynamic array'
575 def _set_length(self
, length
):
576 utils
._check
_uint
64(length
)
577 status
= native_bt
.field_array_dynamic_set_length(self
._ptr
, length
)
578 utils
._handle
_func
_status
(status
, "cannot set dynamic array length")
580 length
= property(fget
=_ArrayField
._get
_length
, fset
=_set_length
)
582 def _set_value(self
, values
):
583 if len(values
) != self
.length
:
584 self
.length
= len(values
)
586 for index
, value
in enumerate(values
):
587 if value
is not None:
588 self
[index
].value
= value
590 value
= property(fset
=_set_value
)
594 native_bt
.FIELD_CLASS_TYPE_UNSIGNED_INTEGER
: _UnsignedIntegerField
,
595 native_bt
.FIELD_CLASS_TYPE_SIGNED_INTEGER
: _SignedIntegerField
,
596 native_bt
.FIELD_CLASS_TYPE_REAL
: _RealField
,
597 native_bt
.FIELD_CLASS_TYPE_UNSIGNED_ENUMERATION
: _UnsignedEnumerationField
,
598 native_bt
.FIELD_CLASS_TYPE_SIGNED_ENUMERATION
: _SignedEnumerationField
,
599 native_bt
.FIELD_CLASS_TYPE_STRING
: _StringField
,
600 native_bt
.FIELD_CLASS_TYPE_STRUCTURE
: _StructureField
,
601 native_bt
.FIELD_CLASS_TYPE_STATIC_ARRAY
: _StaticArrayField
,
602 native_bt
.FIELD_CLASS_TYPE_DYNAMIC_ARRAY
: _DynamicArrayField
,
603 native_bt
.FIELD_CLASS_TYPE_VARIANT_WITHOUT_SELECTOR
: _VariantField
,
604 native_bt
.FIELD_CLASS_TYPE_VARIANT_WITH_UNSIGNED_SELECTOR
: _VariantField
,
605 native_bt
.FIELD_CLASS_TYPE_VARIANT_WITH_SIGNED_SELECTOR
: _VariantField
,