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
42 # Get the "effective" field of `field`. If `field` is a variant, return the
43 # currently selected field. If `field` is of any other type, return `field`
47 def _get_leaf_field(field
):
48 if not isinstance(field
, _VariantField
):
51 return _get_leaf_field(field
.selected_option
)
54 class _Field(object._UniqueObject
):
55 def __eq__(self
, other
):
56 other
= _get_leaf_field(other
)
57 return self
._spec
_eq
(other
)
60 def field_class(self
):
61 field_class_ptr
= native_bt
.field_borrow_class_const(self
._ptr
)
62 assert field_class_ptr
is not None
63 return bt2
.field_class
._create
_field
_class
_from
_ptr
_and
_get
_ref
(field_class_ptr
)
66 raise NotImplementedError
72 @functools.total_ordering
73 class _NumericField(_Field
):
75 def _extract_value(other
):
76 if isinstance(other
, bool):
79 if isinstance(other
, numbers
.Integral
):
82 if isinstance(other
, numbers
.Real
):
85 if isinstance(other
, numbers
.Complex
):
89 "'{}' object is not a number object".format(other
.__class
__.__name
__)
93 return int(self
._value
)
96 return float(self
._value
)
99 return repr(self
._value
)
101 def __lt__(self
, other
):
102 if not isinstance(other
, numbers
.Number
):
104 'unorderable types: {}() < {}()'.format(
105 self
.__class
__.__name
__, other
.__class
__.__name
__
109 return self
._value
< self
._extract
_value
(other
)
111 def _spec_eq(self
, other
):
113 return self
._value
== self
._extract
_value
(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
178 class _IntegralField(_NumericField
, numbers
.Integral
):
179 def __lshift__(self
, other
):
180 return self
._value
<< self
._extract
_value
(other
)
182 def __rlshift__(self
, other
):
183 return self
._extract
_value
(other
) << self
._value
185 def __rshift__(self
, other
):
186 return self
._value
>> self
._extract
_value
(other
)
188 def __rrshift__(self
, other
):
189 return self
._extract
_value
(other
) >> self
._value
191 def __and__(self
, other
):
192 return self
._value
& self
._extract
_value
(other
)
194 def __rand__(self
, other
):
195 return self
._extract
_value
(other
) & self
._value
197 def __xor__(self
, other
):
198 return self
._value ^ self
._extract
_value
(other
)
200 def __rxor__(self
, other
):
201 return self
._extract
_value
(other
) ^ self
._value
203 def __or__(self
, other
):
204 return self
._value | self
._extract
_value
(other
)
206 def __ror__(self
, other
):
207 return self
._extract
_value
(other
) | self
._value
209 def __invert__(self
):
213 class _IntegerField(_IntegralField
, _Field
):
217 class _UnsignedIntegerField(_IntegerField
, _Field
):
218 _NAME
= 'Unsigned integer'
220 def _value_to_int(self
, value
):
221 if not isinstance(value
, numbers
.Integral
):
222 raise TypeError('expecting an integral number object')
225 utils
._check
_uint
64(value
)
231 return native_bt
.field_integer_unsigned_get_value(self
._ptr
)
233 def _set_value(self
, value
):
234 value
= self
._value
_to
_int
(value
)
235 native_bt
.field_integer_unsigned_set_value(self
._ptr
, value
)
237 value
= property(fset
=_set_value
)
240 class _SignedIntegerField(_IntegerField
, _Field
):
241 _NAME
= 'Signed integer'
243 def _value_to_int(self
, value
):
244 if not isinstance(value
, numbers
.Integral
):
245 raise TypeError('expecting an integral number object')
248 utils
._check
_int
64(value
)
254 return native_bt
.field_integer_signed_get_value(self
._ptr
)
256 def _set_value(self
, value
):
257 value
= self
._value
_to
_int
(value
)
258 native_bt
.field_integer_signed_set_value(self
._ptr
, value
)
260 value
= property(fset
=_set_value
)
263 class _RealField(_NumericField
, numbers
.Real
):
266 def _value_to_float(self
, value
):
267 if not isinstance(value
, numbers
.Real
):
268 raise TypeError("expecting a real number object")
274 return native_bt
.field_real_get_value(self
._ptr
)
276 def _set_value(self
, value
):
277 value
= self
._value
_to
_float
(value
)
278 native_bt
.field_real_set_value(self
._ptr
, value
)
280 value
= property(fset
=_set_value
)
283 class _EnumerationField(_IntegerField
):
285 return '{} ({})'.format(self
._value
, ', '.join(self
.labels
))
289 status
, labels
= self
._get
_mapping
_labels
(self
._ptr
)
290 utils
._handle
_func
_status
(status
, "cannot get label for enumeration field")
292 assert labels
is not None
296 class _UnsignedEnumerationField(_EnumerationField
, _UnsignedIntegerField
):
297 _NAME
= 'Unsigned Enumeration'
298 _get_mapping_labels
= staticmethod(
299 native_bt
.field_enumeration_unsigned_get_mapping_labels
303 class _SignedEnumerationField(_EnumerationField
, _SignedIntegerField
):
304 _NAME
= 'Signed Enumeration'
305 _get_mapping_labels
= staticmethod(
306 native_bt
.field_enumeration_signed_get_mapping_labels
310 @functools.total_ordering
311 class _StringField(_Field
):
314 def _value_to_str(self
, value
):
315 if isinstance(value
, self
.__class
__):
318 if not isinstance(value
, str):
319 raise TypeError("expecting a 'str' object")
325 return native_bt
.field_string_get_value(self
._ptr
)
327 def _set_value(self
, value
):
328 value
= self
._value
_to
_str
(value
)
329 native_bt
.field_string_set_value(self
._ptr
, value
)
331 value
= property(fset
=_set_value
)
333 def _spec_eq(self
, other
):
335 return self
._value
== self
._value
_to
_str
(other
)
339 def __lt__(self
, other
):
340 return self
._value
< self
._value
_to
_str
(other
)
343 return bool(self
._value
)
346 return repr(self
._value
)
349 return str(self
._value
)
351 def __getitem__(self
, index
):
352 return self
._value
[index
]
355 return native_bt
.field_string_get_length(self
._ptr
)
357 def __iadd__(self
, value
):
358 value
= self
._value
_to
_str
(value
)
359 status
= native_bt
.field_string_append(self
._ptr
, value
)
360 utils
._handle
_func
_status
(
361 status
, "cannot append to string field object's value"
366 class _ContainerField(_Field
):
368 return len(self
) != 0
371 count
= self
._count
()
375 def __delitem__(self
, index
):
376 raise NotImplementedError
379 class _StructureField(_ContainerField
, collections
.abc
.MutableMapping
):
383 return len(self
.field_class
)
385 def __setitem__(self
, key
, value
):
386 # raises if key is somehow invalid
389 # the field's property does the appropriate conversion or raises
390 # the appropriate exception
395 return iter(self
.field_class
)
397 def _spec_eq(self
, other
):
398 if not isinstance(other
, collections
.abc
.Mapping
):
401 if len(self
) != len(other
):
405 for self_key
in self
:
406 if self_key
not in other
:
409 if self
[self_key
] != other
[self_key
]:
414 def _set_value(self
, values
):
416 for key
, value
in values
.items():
417 self
[key
].value
= value
421 value
= property(fset
=_set_value
)
424 items
= ['{}: {}'.format(repr(k
), repr(v
)) for k
, v
in self
.items()]
425 return '{{{}}}'.format(', '.join(items
))
427 def __getitem__(self
, key
):
428 utils
._check
_str
(key
)
429 field_ptr
= native_bt
.field_structure_borrow_member_field_by_name(
433 if field_ptr
is None:
436 return _create_field_from_ptr(
437 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
440 def member_at_index(self
, index
):
441 utils
._check
_uint
64(index
)
443 if index
>= len(self
):
446 field_ptr
= native_bt
.field_structure_borrow_member_field_by_index(
449 assert field_ptr
is not None
450 return _create_field_from_ptr(
451 field_ptr
, self
._owner
_ptr
, self
._owner
_get
_ref
, self
._owner
_put
_ref
455 class _VariantField(_ContainerField
, _Field
):
459 def selected_option_index(self
):
460 return native_bt
.field_variant_get_selected_option_field_index(self
._ptr
)
462 @selected_option_index.setter
463 def selected_option_index(self
, index
):
464 native_bt
.field_variant_select_option_field_by_index(self
._ptr
, index
)
467 def selected_option(self
):
468 field_ptr
= native_bt
.field_variant_borrow_selected_option_field(self
._ptr
)
469 utils
._handle
_ptr
(field_ptr
, "cannot get variant field's selected option")
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
,