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 collections
.abc
32 def _handle_status(status
, obj_name
):
36 raise RuntimeError('unexpected error')
39 def _create_from_ptr(ptr
):
40 if ptr
is None or ptr
== native_bt
.value_null
:
43 typeid
= native_bt
.value_get_type(ptr
)
44 return _TYPE_TO_OBJ
[typeid
]._create
_from
_ptr
(ptr
)
47 def _create_from_ptr_and_get_ref(ptr
):
48 if ptr
is None or ptr
== native_bt
.value_null
:
51 typeid
= native_bt
.value_get_type(ptr
)
52 return _TYPE_TO_OBJ
[typeid
]._create
_from
_ptr
_and
_get
_ref
(ptr
)
55 def create_value(value
):
60 if isinstance(value
, _Value
):
63 if isinstance(value
, bool):
64 return BoolValue(value
)
66 if isinstance(value
, int):
67 return SignedIntegerValue(value
)
69 if isinstance(value
, float):
70 return RealValue(value
)
72 if isinstance(value
, str):
73 return StringValue(value
)
76 return MapValue(value
)
81 return ArrayValue(value
)
85 raise TypeError("cannot create value object from '{}' object".format(value
.__class
__.__name
__))
88 class _Value(object._SharedObject
, metaclass
=abc
.ABCMeta
):
89 _get_ref
= staticmethod(native_bt
.value_get_ref
)
90 _put_ref
= staticmethod(native_bt
.value_put_ref
)
92 def __eq__(self
, other
):
94 # self is never the null value object
97 # try type-specific comparison first
98 spec_eq
= self
._spec
_eq
(other
)
100 if spec_eq
is not None:
103 if not isinstance(other
, _Value
):
104 # not comparing apples to apples
107 # fall back to native comparison function
108 return native_bt
.value_compare(self
._ptr
, other
._ptr
)
110 def __ne__(self
, other
):
111 return not (self
== other
)
114 def _spec_eq(self
, other
):
117 def _handle_status(self
, status
):
118 _handle_status(status
, self
._NAME
)
120 def _check_create_status(self
, ptr
):
122 raise bt2
.CreationError(
123 'cannot create {} value object'.format(self
._NAME
.lower()))
126 @functools.total_ordering
127 class _NumericValue(_Value
):
129 def _extract_value(other
):
130 if isinstance(other
, _NumericValue
):
133 if other
is True or other
is False:
136 if isinstance(other
, numbers
.Integral
):
139 if isinstance(other
, numbers
.Real
):
142 if isinstance(other
, numbers
.Complex
):
143 return complex(other
)
145 raise TypeError("'{}' object is not a number object".format(other
.__class
__.__name
__))
148 return int(self
._value
)
151 return float(self
._value
)
154 return repr(self
._value
)
156 def __lt__(self
, other
):
157 if not isinstance(other
, numbers
.Number
):
158 raise TypeError('unorderable types: {}() < {}()'.format(self
.__class
__.__name
__,
159 other
.__class
__.__name
__))
161 return self
._value
< float(other
)
163 def _spec_eq(self
, other
):
166 def __eq__(self
, other
):
167 if not isinstance(other
, numbers
.Number
):
170 return self
._value
== complex(other
)
172 def __rmod__(self
, other
):
173 return self
._extract
_value
(other
) % self
._value
175 def __mod__(self
, other
):
176 return self
._value
% self
._extract
_value
(other
)
178 def __rfloordiv__(self
, other
):
179 return self
._extract
_value
(other
) // self
._value
181 def __floordiv__(self
, other
):
182 return self
._value
// self
._extract
_value
(other
)
184 def __round__(self
, ndigits
=None):
186 return round(self
._value
)
188 return round(self
._value
, ndigits
)
191 return math
.ceil(self
._value
)
194 return math
.floor(self
._value
)
197 return int(self
._value
)
200 return abs(self
._value
)
202 def __add__(self
, other
):
203 return self
._value
+ self
._extract
_value
(other
)
205 def __radd__(self
, other
):
206 return self
.__add
__(other
)
214 def __mul__(self
, other
):
215 return self
._value
* self
._extract
_value
(other
)
217 def __rmul__(self
, other
):
218 return self
.__mul
__(other
)
220 def __truediv__(self
, other
):
221 return self
._value
/ self
._extract
_value
(other
)
223 def __rtruediv__(self
, other
):
224 return self
._extract
_value
(other
) / self
._value
226 def __pow__(self
, exponent
):
227 return self
._value
** self
._extract
_value
(exponent
)
229 def __rpow__(self
, base
):
230 return self
._extract
_value
(base
) ** self
._value
232 def __iadd__(self
, other
):
233 self
.value
= self
+ other
236 def __isub__(self
, other
):
237 self
.value
= self
- other
240 def __imul__(self
, other
):
241 self
.value
= self
* other
244 def __itruediv__(self
, other
):
245 self
.value
= self
/ other
248 def __ifloordiv__(self
, other
):
249 self
.value
= self
// other
252 def __imod__(self
, other
):
253 self
.value
= self
% other
256 def __ipow__(self
, other
):
257 self
.value
= self
** other
261 class _IntegralValue(_NumericValue
, numbers
.Integral
):
262 def __lshift__(self
, other
):
263 return self
._value
<< self
._extract
_value
(other
)
265 def __rlshift__(self
, other
):
266 return self
._extract
_value
(other
) << self
._value
268 def __rshift__(self
, other
):
269 return self
._value
>> self
._extract
_value
(other
)
271 def __rrshift__(self
, other
):
272 return self
._extract
_value
(other
) >> self
._value
274 def __and__(self
, other
):
275 return self
._value
& self
._extract
_value
(other
)
277 def __rand__(self
, other
):
278 return self
._extract
_value
(other
) & self
._value
280 def __xor__(self
, other
):
281 return self
._value ^ self
._extract
_value
(other
)
283 def __rxor__(self
, other
):
284 return self
._extract
_value
(other
) ^ self
._value
286 def __or__(self
, other
):
287 return self
._value | self
._extract
_value
(other
)
289 def __ror__(self
, other
):
290 return self
._extract
_value
(other
) | self
._value
292 def __invert__(self
):
295 def __ilshift__(self
, other
):
296 self
.value
= self
<< other
299 def __irshift__(self
, other
):
300 self
.value
= self
>> other
303 def __iand__(self
, other
):
304 self
.value
= self
& other
307 def __ixor__(self
, other
):
308 self
.value
= self ^ other
311 def __ior__(self
, other
):
312 self
.value
= self | other
315 def __lt__(self
, other
):
316 if not isinstance(other
, numbers
.Integral
):
317 return super().__lt
__(other
)
319 return self
._value
< int(other
)
321 def __eq__(self
, other
):
322 if not isinstance(other
, numbers
.Integral
):
323 return super().__eq
__(other
)
325 return self
._value
== int(other
)
328 class _RealValue(_NumericValue
, numbers
.Real
):
332 class BoolValue(_Value
):
335 def __init__(self
, value
=None):
337 ptr
= native_bt
.value_bool_create()
339 ptr
= native_bt
.value_bool_create_init(self
._value
_to
_bool
(value
))
341 self
._check
_create
_status
(ptr
)
342 super().__init
__(ptr
)
344 def _spec_eq(self
, other
):
345 if isinstance(other
, numbers
.Number
):
346 return self
._value
== bool(other
)
352 return repr(self
._value
)
354 def _value_to_bool(self
, value
):
355 if isinstance(value
, BoolValue
):
358 if not isinstance(value
, bool):
359 raise TypeError("'{}' object is not a 'bool' or 'BoolValue' object".format(value
.__class
__))
365 value
= native_bt
.value_bool_get(self
._ptr
)
368 def _set_value(self
, value
):
369 native_bt
.value_bool_set(self
._ptr
, self
._value
_to
_bool
(value
))
371 value
= property(fset
=_set_value
)
374 class _IntegerValue(_IntegralValue
):
375 def __init__(self
, value
=None):
377 ptr
= self
._create
_default
_value
()
379 ptr
= self
._create
_value
(self
._value
_to
_int
(value
))
381 self
._check
_create
_status
(ptr
)
382 super().__init
__(ptr
)
384 def _value_to_int(self
, value
):
385 if not isinstance(value
, numbers
.Real
):
386 raise TypeError('expecting a number object')
389 self
._check
_int
_range
(value
)
394 return self
._get
_value
(self
._ptr
)
396 def _prop_set_value(self
, value
):
397 self
._set
_value
(self
._ptr
, self
._value
_to
_int
(value
))
399 value
= property(fset
=_prop_set_value
)
402 class UnsignedIntegerValue(_IntegerValue
):
403 _check_int_range
= staticmethod(utils
._check
_uint
64)
404 _create_default_value
= staticmethod(native_bt
.value_unsigned_integer_create
)
405 _create_value
= staticmethod(native_bt
.value_unsigned_integer_create_init
)
406 _set_value
= staticmethod(native_bt
.value_unsigned_integer_set
)
407 _get_value
= staticmethod(native_bt
.value_unsigned_integer_get
)
410 class SignedIntegerValue(_IntegerValue
):
411 _check_int_range
= staticmethod(utils
._check
_int
64)
412 _create_default_value
= staticmethod(native_bt
.value_signed_integer_create
)
413 _create_value
= staticmethod(native_bt
.value_signed_integer_create_init
)
414 _set_value
= staticmethod(native_bt
.value_signed_integer_set
)
415 _get_value
= staticmethod(native_bt
.value_signed_integer_get
)
418 class RealValue(_RealValue
):
419 _NAME
= 'Real number'
421 def __init__(self
, value
=None):
423 ptr
= native_bt
.value_real_create()
425 value
= self
._value
_to
_float
(value
)
426 ptr
= native_bt
.value_real_create_init(value
)
428 self
._check
_create
_status
(ptr
)
429 super().__init
__(ptr
)
431 def _value_to_float(self
, value
):
432 if not isinstance(value
, numbers
.Real
):
433 raise TypeError("expecting a real number object")
439 return native_bt
.value_real_get(self
._ptr
)
441 def _set_value(self
, value
):
442 native_bt
.value_real_set(self
._ptr
, self
._value
_to
_float
(value
))
444 value
= property(fset
=_set_value
)
447 @functools.total_ordering
448 class StringValue(collections
.abc
.Sequence
, _Value
):
451 def __init__(self
, value
=None):
453 ptr
= native_bt
.value_string_create()
455 ptr
= native_bt
.value_string_create_init(self
._value
_to
_str
(value
))
457 self
._check
_create
_status
(ptr
)
458 super().__init
__(ptr
)
460 def _value_to_str(self
, value
):
461 if isinstance(value
, self
.__class
__):
464 utils
._check
_str
(value
)
469 return native_bt
.value_string_get(self
._ptr
)
471 def _set_value(self
, value
):
472 status
= native_bt
.value_string_set(self
._ptr
, self
._value
_to
_str
(value
))
473 self
._handle
_status
(status
)
475 value
= property(fset
=_set_value
)
477 def _spec_eq(self
, other
):
479 return self
._value
== self
._value
_to
_str
(other
)
483 def __lt__(self
, other
):
484 return self
._value
< self
._value
_to
_str
(other
)
487 return bool(self
._value
)
490 return repr(self
._value
)
495 def __getitem__(self
, index
):
496 return self
._value
[index
]
499 return len(self
._value
)
501 def __iadd__(self
, value
):
502 curvalue
= self
._value
503 curvalue
+= self
._value
_to
_str
(value
)
504 self
.value
= curvalue
510 return len(self
) != 0
512 def __delitem__(self
, index
):
513 raise NotImplementedError
516 class ArrayValue(_Container
, collections
.abc
.MutableSequence
, _Value
):
519 def __init__(self
, value
=None):
520 ptr
= native_bt
.value_array_create()
521 self
._check
_create
_status
(ptr
)
522 super().__init
__(ptr
)
524 # Python will raise a TypeError if there's anything wrong with
525 # the iterable protocol.
526 if value
is not None:
530 def _spec_eq(self
, other
):
532 if len(self
) != len(other
):
536 for self_elem
, other_elem
in zip(self
, other
):
537 if self_elem
!= other_elem
:
545 size
= native_bt
.value_array_get_size(self
._ptr
)
549 def _check_index(self
, index
):
550 # TODO: support slices also
551 if not isinstance(index
, numbers
.Integral
):
552 raise TypeError("'{}' object is not an integral number object: invalid index".format(index
.__class
__.__name
__))
556 if index
< 0 or index
>= len(self
):
557 raise IndexError('array value object index is out of range')
559 def __getitem__(self
, index
):
560 self
._check
_index
(index
)
561 ptr
= native_bt
.value_array_borrow_element_by_index(self
._ptr
, index
)
563 return _create_from_ptr_and_get_ref(ptr
)
565 def __setitem__(self
, index
, value
):
566 self
._check
_index
(index
)
567 value
= create_value(value
)
570 ptr
= native_bt
.value_null
574 status
= native_bt
.value_array_set_element_by_index(
575 self
._ptr
, index
, ptr
)
576 self
._handle
_status
(status
)
578 def append(self
, value
):
579 value
= create_value(value
)
582 ptr
= native_bt
.value_null
586 status
= native_bt
.value_array_append_element(self
._ptr
, ptr
)
587 self
._handle
_status
(status
)
589 def __iadd__(self
, iterable
):
590 # Python will raise a TypeError if there's anything wrong with
591 # the iterable protocol.
592 for elem
in iterable
:
598 return '[{}]'.format(', '.join([repr(v
) for v
in self
]))
600 def insert(self
, value
):
601 raise NotImplementedError
604 class _MapValueKeyIterator(collections
.abc
.Iterator
):
605 def __init__(self
, map_obj
):
606 self
._map
_obj
= map_obj
608 keys_ptr
= native_bt
.value_map_get_keys(map_obj
._ptr
)
611 raise RuntimeError('unexpected error: cannot get map value object keys')
613 self
._keys
= _create_from_ptr(keys_ptr
)
616 if self
._at
== len(self
._map
_obj
):
619 key
= self
._keys
[self
._at
]
624 class MapValue(_Container
, collections
.abc
.MutableMapping
, _Value
):
627 def __init__(self
, value
=None):
628 ptr
= native_bt
.value_map_create()
629 self
._check
_create
_status
(ptr
)
630 super().__init
__(ptr
)
632 # Python will raise a TypeError if there's anything wrong with
633 # the iterable/mapping protocol.
634 if value
is not None:
635 for key
, elem
in value
.items():
638 def __eq__(self
, other
):
639 return _Value
.__eq
__(self
, other
)
641 def __ne__(self
, other
):
642 return _Value
.__ne
__(self
, other
)
644 def _spec_eq(self
, other
):
646 if len(self
) != len(other
):
650 for self_key
in self
:
651 if self_key
not in other
:
654 self_value
= self
[self_key
]
655 other_value
= other
[self_key
]
657 if self_value
!= other_value
:
665 size
= native_bt
.value_map_get_size(self
._ptr
)
669 def __contains__(self
, key
):
670 self
._check
_key
_type
(key
)
671 return native_bt
.value_map_has_entry(self
._ptr
, key
)
673 def _check_key_type(self
, key
):
674 utils
._check
_str
(key
)
676 def _check_key(self
, key
):
680 def __getitem__(self
, key
):
682 ptr
= native_bt
.value_map_borrow_entry_value(self
._ptr
, key
)
684 return _create_from_ptr_and_get_ref(ptr
)
687 return _MapValueKeyIterator(self
)
689 def __setitem__(self
, key
, value
):
690 self
._check
_key
_type
(key
)
691 value
= create_value(value
)
694 ptr
= native_bt
.value_null
698 status
= native_bt
.value_map_insert_entry(self
._ptr
, key
, ptr
)
699 self
._handle
_status
(status
)
702 items
= ['{}: {}'.format(repr(k
), repr(v
)) for k
, v
in self
.items()]
703 return '{{{}}}'.format(', '.join(items
))
707 native_bt
.VALUE_TYPE_BOOL
: BoolValue
,
708 native_bt
.VALUE_TYPE_UNSIGNED_INTEGER
: UnsignedIntegerValue
,
709 native_bt
.VALUE_TYPE_SIGNED_INTEGER
: SignedIntegerValue
,
710 native_bt
.VALUE_TYPE_REAL
: RealValue
,
711 native_bt
.VALUE_TYPE_STRING
: StringValue
,
712 native_bt
.VALUE_TYPE_ARRAY
: ArrayValue
,
713 native_bt
.VALUE_TYPE_MAP
: MapValue
,