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_class
25 import collections
.abc
32 def _create_field_from_ptr(ptr
, owner_ptr
, owner_get_ref
, owner_put_ref
):
33 field_class_ptr
= native_bt
.field_borrow_class_const(ptr
)
34 utils
._handle
_ptr
(field_class_ptr
, "cannot get field object's class")
35 typeid
= native_bt
.field_class_get_type(field_class_ptr
)
36 field
= _TYPE_ID_TO_OBJ
[typeid
]._create
_from
_ptr
_and
_get
_ref
(
37 ptr
, owner_ptr
, owner_get_ref
, owner_put_ref
)
41 # Get the "effective" field of `field`. If `field` is a variant, return the
42 # 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 other
is True or other
is False:
77 if isinstance(other
, numbers
.Integral
):
80 if isinstance(other
, numbers
.Real
):
83 if isinstance(other
, numbers
.Complex
):
86 raise TypeError("'{}' object is not a number object".format(other
.__class
__.__name
__))
89 return int(self
._value
)
92 return float(self
._value
)
95 return repr(self
._value
)
97 def __lt__(self
, other
):
98 if not isinstance(other
, numbers
.Number
):
99 raise TypeError('unorderable types: {}() < {}()'.format(self
.__class
__.__name
__,
100 other
.__class
__.__name
__))
102 return self
._value
< float(other
)
104 def __le__(self
, other
):
105 if not isinstance(other
, numbers
.Number
):
106 raise TypeError('unorderable types: {}() <= {}()'.format(self
.__class
__.__name
__,
107 other
.__class
__.__name
__))
109 return self
._value
<= float(other
)
111 def _spec_eq(self
, other
):
112 if not isinstance(other
, numbers
.Number
):
113 return NotImplemented
115 return self
._value
== complex(other
)
117 def __rmod__(self
, other
):
118 return self
._extract
_value
(other
) % self
._value
120 def __mod__(self
, other
):
121 return self
._value
% self
._extract
_value
(other
)
123 def __rfloordiv__(self
, other
):
124 return self
._extract
_value
(other
) // self
._value
126 def __floordiv__(self
, other
):
127 return self
._value
// self
._extract
_value
(other
)
129 def __round__(self
, ndigits
=None):
131 return round(self
._value
)
133 return round(self
._value
, ndigits
)
136 return math
.ceil(self
._value
)
139 return math
.floor(self
._value
)
142 return int(self
._value
)
145 return abs(self
._value
)
147 def __add__(self
, other
):
148 return self
._value
+ self
._extract
_value
(other
)
150 def __radd__(self
, other
):
151 return self
.__add
__(other
)
159 def __mul__(self
, other
):
160 return self
._value
* self
._extract
_value
(other
)
162 def __rmul__(self
, other
):
163 return self
.__mul
__(other
)
165 def __truediv__(self
, other
):
166 return self
._value
/ self
._extract
_value
(other
)
168 def __rtruediv__(self
, other
):
169 return self
._extract
_value
(other
) / self
._value
171 def __pow__(self
, exponent
):
172 return self
._value
** self
._extract
_value
(exponent
)
174 def __rpow__(self
, base
):
175 return self
._extract
_value
(base
) ** self
._value
177 def __iadd__(self
, other
):
178 self
.value
= self
+ other
181 def __isub__(self
, other
):
182 self
.value
= self
- other
185 def __imul__(self
, other
):
186 self
.value
= self
* other
189 def __itruediv__(self
, other
):
190 self
.value
= self
/ other
193 def __ifloordiv__(self
, other
):
194 self
.value
= self
// other
197 def __imod__(self
, other
):
198 self
.value
= self
% other
201 def __ipow__(self
, other
):
202 self
.value
= self
** other
206 class _IntegralField(_NumericField
, numbers
.Integral
):
207 def __lshift__(self
, other
):
208 return self
._value
<< self
._extract
_value
(other
)
210 def __rlshift__(self
, other
):
211 return self
._extract
_value
(other
) << self
._value
213 def __rshift__(self
, other
):
214 return self
._value
>> self
._extract
_value
(other
)
216 def __rrshift__(self
, other
):
217 return self
._extract
_value
(other
) >> self
._value
219 def __and__(self
, other
):
220 return self
._value
& self
._extract
_value
(other
)
222 def __rand__(self
, other
):
223 return self
._extract
_value
(other
) & self
._value
225 def __xor__(self
, other
):
226 return self
._value ^ self
._extract
_value
(other
)
228 def __rxor__(self
, other
):
229 return self
._extract
_value
(other
) ^ self
._value
231 def __or__(self
, other
):
232 return self
._value | self
._extract
_value
(other
)
234 def __ror__(self
, other
):
235 return self
._extract
_value
(other
) | self
._value
237 def __invert__(self
):
240 def __ilshift__(self
, other
):
241 self
.value
= self
<< other
244 def __irshift__(self
, other
):
245 self
.value
= self
>> other
248 def __iand__(self
, other
):
249 self
.value
= self
& other
252 def __ixor__(self
, other
):
253 self
.value
= self ^ other
256 def __ior__(self
, other
):
257 self
.value
= self | other
261 class _IntegerField(_IntegralField
, _Field
):
265 class _UnsignedIntegerField(_IntegerField
, _Field
):
266 _NAME
= 'Unsigned integer'
268 def _value_to_int(self
, value
):
269 if not isinstance(value
, numbers
.Real
):
270 raise TypeError('expecting a real number object')
273 utils
._check
_uint
64(value
)
279 return native_bt
.field_unsigned_integer_get_value(self
._ptr
)
281 def _set_value(self
, value
):
282 value
= self
._value
_to
_int
(value
)
283 native_bt
.field_unsigned_integer_set_value(self
._ptr
, value
)
285 value
= property(fset
=_set_value
)
288 class _SignedIntegerField(_IntegerField
, _Field
):
289 _NAME
= 'Signed integer'
291 def _value_to_int(self
, value
):
292 if not isinstance(value
, numbers
.Real
):
293 raise TypeError('expecting a real number object')
296 utils
._check
_int
64(value
)
302 return native_bt
.field_signed_integer_get_value(self
._ptr
)
304 def _set_value(self
, value
):
305 value
= self
._value
_to
_int
(value
)
306 native_bt
.field_signed_integer_set_value(self
._ptr
, value
)
308 value
= property(fset
=_set_value
)
311 class _RealField(_NumericField
, numbers
.Real
):
314 def _value_to_float(self
, value
):
315 if not isinstance(value
, numbers
.Real
):
316 raise TypeError("expecting a real number object")
322 return native_bt
.field_real_get_value(self
._ptr
)
324 def _set_value(self
, value
):
325 value
= self
._value
_to
_float
(value
)
326 native_bt
.field_real_set_value(self
._ptr
, value
)
328 value
= property(fset
=_set_value
)
331 class _EnumerationField(_IntegerField
):
333 return '{} ({})'.format(self
._value
, ', '.join(self
.labels
))
337 ret
, labels
= self
._get
_mapping
_labels
(self
._ptr
)
338 utils
._handle
_ret
(ret
, "cannot get label for enumeration field")
340 assert labels
is not None
344 class _UnsignedEnumerationField(_EnumerationField
, _UnsignedIntegerField
):
345 _NAME
= 'Unsigned Enumeration'
346 _get_mapping_labels
= staticmethod(native_bt
.field_unsigned_enumeration_get_mapping_labels
)
349 class _SignedEnumerationField(_EnumerationField
, _SignedIntegerField
):
350 _NAME
= 'Signed Enumeration'
351 _get_mapping_labels
= staticmethod(native_bt
.field_signed_enumeration_get_mapping_labels
)
354 @functools.total_ordering
355 class _StringField(_Field
):
358 def _value_to_str(self
, value
):
359 if isinstance(value
, self
.__class
__):
362 if not isinstance(value
, str):
363 raise TypeError("expecting a 'str' object")
369 return native_bt
.field_string_get_value(self
._ptr
)
371 def _set_value(self
, value
):
372 value
= self
._value
_to
_str
(value
)
373 native_bt
.field_string_set_value(self
._ptr
, value
)
375 value
= property(fset
=_set_value
)
377 def _spec_eq(self
, other
):
379 other
= self
._value
_to
_str
(other
)
383 return self
._value
== other
385 def __le__(self
, other
):
386 return self
._value
<= self
._value
_to
_str
(other
)
388 def __lt__(self
, other
):
389 return self
._value
< self
._value
_to
_str
(other
)
392 return bool(self
._value
)
395 return repr(self
._value
)
398 return str(self
._value
)
400 def __getitem__(self
, index
):
401 return self
._value
[index
]
404 return native_bt
.field_string_get_length(self
._ptr
)
406 def __iadd__(self
, value
):
407 value
= self
._value
_to
_str
(value
)
408 ret
= native_bt
.field_string_append(self
._ptr
, value
)
409 utils
._handle
_ret
(ret
, "cannot append to string field object's value")
413 class _ContainerField(_Field
):
415 return len(self
) != 0
418 count
= self
._count
()
422 def __delitem__(self
, index
):
423 raise NotImplementedError
426 class _StructureField(_ContainerField
, collections
.abc
.MutableMapping
):
430 return len(self
.field_class
)
432 def __setitem__(self
, key
, value
):
433 # raises if key is somehow invalid
436 # the field's property does the appropriate conversion or raises
437 # the appropriate exception
442 return iter(self
.field_class
)
444 def _spec_eq(self
, other
):
446 if len(self
) != len(other
):
449 for self_key
, self_value
in self
.items():
450 if self_key
not in other
:
453 other_value
= other
[self_key
]
455 if self_value
!= other_value
:
462 def _set_value(self
, values
):
464 for key
, value
in values
.items():
465 self
[key
].value
= value
469 value
= property(fset
=_set_value
)
472 items
= ['{}: {}'.format(repr(k
), repr(v
)) for k
, v
in self
.items()]
473 return '{{{}}}'.format(', '.join(items
))
475 def __getitem__(self
, key
):
476 utils
._check
_str
(key
)
477 field_ptr
= native_bt
.field_structure_borrow_member_field_by_name(self
._ptr
, key
)
479 if field_ptr
is None:
482 return _create_field_from_ptr(field_ptr
, self
._owner
_ptr
,
486 def member_at_index(self
, index
):
487 utils
._check
_uint
64(index
)
489 if index
>= len(self
):
492 field_ptr
= native_bt
.field_structure_borrow_member_field_by_index(self
._ptr
, index
)
493 assert field_ptr
is not None
494 return _create_field_from_ptr(field_ptr
, self
._owner
_ptr
,
499 class _VariantField(_ContainerField
, _Field
):
503 def selected_option_index(self
):
504 return native_bt
.field_variant_get_selected_option_field_index(self
._ptr
)
506 @selected_option_index.setter
507 def selected_option_index(self
, index
):
508 native_bt
.field_variant_select_option_field(self
._ptr
, index
)
511 def selected_option(self
):
512 field_ptr
= native_bt
.field_variant_borrow_selected_option_field(self
._ptr
)
513 utils
._handle
_ptr
(field_ptr
, "cannot get variant field's selected option")
515 return _create_field_from_ptr(field_ptr
, self
._owner
_ptr
,
519 def _spec_eq(self
, other
):
520 new_self
= _get_leaf_field(self
)
521 return new_self
== other
524 raise NotImplementedError
527 return str(self
.selected_option
)
530 return repr(self
.selected_option
)
532 def _set_value(self
, value
):
533 self
.selected_option
.value
= value
535 value
= property(fset
=_set_value
)
538 class _ArrayField(_ContainerField
, _Field
):
540 def _get_length(self
):
541 return native_bt
.field_array_get_length(self
._ptr
)
543 length
= property(fget
=_get_length
)
545 def __getitem__(self
, index
):
546 if not isinstance(index
, numbers
.Integral
):
547 raise TypeError("'{}' is not an integral number object: invalid index".format(index
.__class
__.__name
__))
551 if index
< 0 or index
>= len(self
):
552 raise IndexError('{} field object index is out of range'.format(self
._NAME
))
554 field_ptr
= native_bt
.field_array_borrow_element_field_by_index(self
._ptr
, index
)
556 return _create_field_from_ptr(field_ptr
, self
._owner
_ptr
,
560 def __setitem__(self
, index
, value
):
561 # we can only set numbers and strings
562 if not isinstance(value
, (numbers
.Number
, _StringField
, str)):
563 raise TypeError('expecting number or string object')
565 # raises if index is somehow invalid
568 if not isinstance(field
, (_NumericField
, _StringField
)):
569 raise TypeError('can only set the value of a number or string field')
571 # the field's property does the appropriate conversion or raises
572 # the appropriate exception
575 def insert(self
, index
, value
):
576 raise NotImplementedError
578 def _spec_eq(self
, other
):
580 if len(self
) != len(other
):
583 for self_field
, other_field
in zip(self
, other
):
584 if self_field
!= other_field
:
592 return '[{}]'.format(', '.join([repr(v
) for v
in self
]))
595 class _StaticArrayField(_ArrayField
, _Field
):
596 _NAME
= 'Static array'
599 return native_bt
.field_array_get_length(self
._ptr
)
601 def _set_value(self
, values
):
602 if len(self
) != len(values
):
604 'expected length of value and array field to match')
606 for index
, value
in enumerate(values
):
607 if value
is not None:
608 self
[index
].value
= value
610 value
= property(fset
=_set_value
)
613 class _DynamicArrayField(_ArrayField
, _Field
):
614 _NAME
= 'Dynamic array'
619 def _set_length(self
, length
):
620 utils
._check
_uint
64(length
)
621 ret
= native_bt
.field_dynamic_array_set_length(self
._ptr
, length
)
622 utils
._handle
_ret
(ret
, "cannot set dynamic array length")
624 length
= property(fget
=_ArrayField
._get
_length
, fset
=_set_length
)
626 def _set_value(self
, values
):
627 if len(values
) != self
.length
:
628 self
.length
= len(values
)
630 for index
, value
in enumerate(values
):
631 if value
is not None:
632 self
[index
].value
= value
634 value
= property(fset
=_set_value
)
638 native_bt
.FIELD_CLASS_TYPE_UNSIGNED_INTEGER
: _UnsignedIntegerField
,
639 native_bt
.FIELD_CLASS_TYPE_SIGNED_INTEGER
: _SignedIntegerField
,
640 native_bt
.FIELD_CLASS_TYPE_REAL
: _RealField
,
641 native_bt
.FIELD_CLASS_TYPE_UNSIGNED_ENUMERATION
: _UnsignedEnumerationField
,
642 native_bt
.FIELD_CLASS_TYPE_SIGNED_ENUMERATION
: _SignedEnumerationField
,
643 native_bt
.FIELD_CLASS_TYPE_STRING
: _StringField
,
644 native_bt
.FIELD_CLASS_TYPE_STRUCTURE
: _StructureField
,
645 native_bt
.FIELD_CLASS_TYPE_STATIC_ARRAY
: _StaticArrayField
,
646 native_bt
.FIELD_CLASS_TYPE_DYNAMIC_ARRAY
: _DynamicArrayField
,
647 native_bt
.FIELD_CLASS_TYPE_VARIANT
: _VariantField
,