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
, numbers
.Integral
):
67 return SignedIntegerValue(value
)
69 if isinstance(value
, numbers
.Real
):
70 return RealValue(value
)
72 if isinstance(value
, str):
73 return StringValue(value
)
75 if isinstance(value
, collections
.abc
.Sequence
):
76 return ArrayValue(value
)
78 if isinstance(value
, collections
.abc
.Mapping
):
79 return MapValue(value
)
81 raise TypeError("cannot create value object from '{}' object".format(value
.__class
__.__name
__))
84 class _Value(object._SharedObject
, metaclass
=abc
.ABCMeta
):
85 _get_ref
= staticmethod(native_bt
.value_get_ref
)
86 _put_ref
= staticmethod(native_bt
.value_put_ref
)
88 def __ne__(self
, other
):
89 return not (self
== other
)
91 def _handle_status(self
, status
):
92 _handle_status(status
, self
._NAME
)
94 def _check_create_status(self
, ptr
):
96 raise bt2
.CreationError(
97 'cannot create {} value object'.format(self
._NAME
.lower()))
100 @functools.total_ordering
101 class _NumericValue(_Value
):
103 def _extract_value(other
):
104 if isinstance(other
, BoolValue
) or isinstance(other
, bool):
107 if isinstance(other
, numbers
.Integral
):
110 if isinstance(other
, numbers
.Real
):
113 if isinstance(other
, numbers
.Complex
):
114 return complex(other
)
116 raise TypeError("'{}' object is not a number object".format(other
.__class
__.__name
__))
119 return int(self
._value
)
122 return float(self
._value
)
125 return repr(self
._value
)
127 def __lt__(self
, other
):
128 return self
._value
< self
._extract
_value
(other
)
130 def __eq__(self
, other
):
132 return self
._value
== self
._extract
_value
(other
)
136 def __rmod__(self
, other
):
137 return self
._extract
_value
(other
) % self
._value
139 def __mod__(self
, other
):
140 return self
._value
% self
._extract
_value
(other
)
142 def __rfloordiv__(self
, other
):
143 return self
._extract
_value
(other
) // self
._value
145 def __floordiv__(self
, other
):
146 return self
._value
// self
._extract
_value
(other
)
148 def __round__(self
, ndigits
=None):
150 return round(self
._value
)
152 return round(self
._value
, ndigits
)
155 return math
.ceil(self
._value
)
158 return math
.floor(self
._value
)
161 return int(self
._value
)
164 return abs(self
._value
)
166 def __add__(self
, other
):
167 return self
._value
+ self
._extract
_value
(other
)
169 def __radd__(self
, other
):
170 return self
.__add
__(other
)
178 def __mul__(self
, other
):
179 return self
._value
* self
._extract
_value
(other
)
181 def __rmul__(self
, other
):
182 return self
.__mul
__(other
)
184 def __truediv__(self
, other
):
185 return self
._value
/ self
._extract
_value
(other
)
187 def __rtruediv__(self
, other
):
188 return self
._extract
_value
(other
) / self
._value
190 def __pow__(self
, exponent
):
191 return self
._value
** self
._extract
_value
(exponent
)
193 def __rpow__(self
, base
):
194 return self
._extract
_value
(base
) ** self
._value
197 class _IntegralValue(_NumericValue
, numbers
.Integral
):
198 def __lshift__(self
, other
):
199 return self
._value
<< self
._extract
_value
(other
)
201 def __rlshift__(self
, other
):
202 return self
._extract
_value
(other
) << self
._value
204 def __rshift__(self
, other
):
205 return self
._value
>> self
._extract
_value
(other
)
207 def __rrshift__(self
, other
):
208 return self
._extract
_value
(other
) >> self
._value
210 def __and__(self
, other
):
211 return self
._value
& self
._extract
_value
(other
)
213 def __rand__(self
, other
):
214 return self
._extract
_value
(other
) & self
._value
216 def __xor__(self
, other
):
217 return self
._value ^ self
._extract
_value
(other
)
219 def __rxor__(self
, other
):
220 return self
._extract
_value
(other
) ^ self
._value
222 def __or__(self
, other
):
223 return self
._value | self
._extract
_value
(other
)
225 def __ror__(self
, other
):
226 return self
._extract
_value
(other
) | self
._value
228 def __invert__(self
):
232 class _RealValue(_NumericValue
, numbers
.Real
):
236 class BoolValue(_IntegralValue
):
239 def __init__(self
, value
=None):
241 ptr
= native_bt
.value_bool_create()
243 ptr
= native_bt
.value_bool_create_init(self
._value
_to
_bool
(value
))
245 self
._check
_create
_status
(ptr
)
246 super().__init
__(ptr
)
252 return repr(self
._value
)
254 def _value_to_bool(self
, value
):
255 if isinstance(value
, BoolValue
):
258 if not isinstance(value
, bool):
259 raise TypeError("'{}' object is not a 'bool' or 'BoolValue' object".format(value
.__class
__))
265 value
= native_bt
.value_bool_get(self
._ptr
)
268 def _set_value(self
, value
):
269 native_bt
.value_bool_set(self
._ptr
, self
._value
_to
_bool
(value
))
271 value
= property(fset
=_set_value
)
274 class _IntegerValue(_IntegralValue
):
275 def __init__(self
, value
=None):
277 ptr
= self
._create
_default
_value
()
279 ptr
= self
._create
_value
(self
._value
_to
_int
(value
))
281 self
._check
_create
_status
(ptr
)
282 super().__init
__(ptr
)
284 def _value_to_int(self
, value
):
285 if not isinstance(value
, numbers
.Integral
):
286 raise TypeError('expecting an integral number object')
289 self
._check
_int
_range
(value
)
294 return self
._get
_value
(self
._ptr
)
296 def _prop_set_value(self
, value
):
297 self
._set
_value
(self
._ptr
, self
._value
_to
_int
(value
))
299 value
= property(fset
=_prop_set_value
)
302 class UnsignedIntegerValue(_IntegerValue
):
303 _check_int_range
= staticmethod(utils
._check
_uint
64)
304 _create_default_value
= staticmethod(native_bt
.value_unsigned_integer_create
)
305 _create_value
= staticmethod(native_bt
.value_unsigned_integer_create_init
)
306 _set_value
= staticmethod(native_bt
.value_unsigned_integer_set
)
307 _get_value
= staticmethod(native_bt
.value_unsigned_integer_get
)
310 class SignedIntegerValue(_IntegerValue
):
311 _check_int_range
= staticmethod(utils
._check
_int
64)
312 _create_default_value
= staticmethod(native_bt
.value_signed_integer_create
)
313 _create_value
= staticmethod(native_bt
.value_signed_integer_create_init
)
314 _set_value
= staticmethod(native_bt
.value_signed_integer_set
)
315 _get_value
= staticmethod(native_bt
.value_signed_integer_get
)
318 class RealValue(_RealValue
):
319 _NAME
= 'Real number'
321 def __init__(self
, value
=None):
323 ptr
= native_bt
.value_real_create()
325 value
= self
._value
_to
_float
(value
)
326 ptr
= native_bt
.value_real_create_init(value
)
328 self
._check
_create
_status
(ptr
)
329 super().__init
__(ptr
)
331 def _value_to_float(self
, value
):
332 if not isinstance(value
, numbers
.Real
):
333 raise TypeError("expecting a real number object")
339 return native_bt
.value_real_get(self
._ptr
)
341 def _set_value(self
, value
):
342 native_bt
.value_real_set(self
._ptr
, self
._value
_to
_float
(value
))
344 value
= property(fset
=_set_value
)
347 @functools.total_ordering
348 class StringValue(collections
.abc
.Sequence
, _Value
):
351 def __init__(self
, value
=None):
353 ptr
= native_bt
.value_string_create()
355 ptr
= native_bt
.value_string_create_init(self
._value
_to
_str
(value
))
357 self
._check
_create
_status
(ptr
)
358 super().__init
__(ptr
)
360 def _value_to_str(self
, value
):
361 if isinstance(value
, self
.__class
__):
364 utils
._check
_str
(value
)
369 return native_bt
.value_string_get(self
._ptr
)
371 def _set_value(self
, value
):
372 status
= native_bt
.value_string_set(self
._ptr
, self
._value
_to
_str
(value
))
373 self
._handle
_status
(status
)
375 value
= property(fset
=_set_value
)
377 def __eq__(self
, other
):
379 return self
._value
== self
._value
_to
_str
(other
)
383 def __lt__(self
, other
):
384 return self
._value
< self
._value
_to
_str
(other
)
387 return bool(self
._value
)
390 return repr(self
._value
)
395 def __getitem__(self
, index
):
396 return self
._value
[index
]
399 return len(self
._value
)
401 def __iadd__(self
, value
):
402 curvalue
= self
._value
403 curvalue
+= self
._value
_to
_str
(value
)
404 self
.value
= curvalue
410 return len(self
) != 0
412 def __delitem__(self
, index
):
413 raise NotImplementedError
416 class ArrayValue(_Container
, collections
.abc
.MutableSequence
, _Value
):
419 def __init__(self
, value
=None):
420 ptr
= native_bt
.value_array_create()
421 self
._check
_create
_status
(ptr
)
422 super().__init
__(ptr
)
424 # Python will raise a TypeError if there's anything wrong with
425 # the iterable protocol.
426 if value
is not None:
430 def __eq__(self
, other
):
431 if not isinstance(other
, collections
.abc
.Sequence
):
434 if len(self
) != len(other
):
438 for self_elem
, other_elem
in zip(self
, other
):
439 if self_elem
!= other_elem
:
445 size
= native_bt
.value_array_get_size(self
._ptr
)
449 def _check_index(self
, index
):
450 # TODO: support slices also
451 if not isinstance(index
, numbers
.Integral
):
452 raise TypeError("'{}' object is not an integral number object: invalid index".format(index
.__class
__.__name
__))
456 if index
< 0 or index
>= len(self
):
457 raise IndexError('array value object index is out of range')
459 def __getitem__(self
, index
):
460 self
._check
_index
(index
)
461 ptr
= native_bt
.value_array_borrow_element_by_index(self
._ptr
, index
)
463 return _create_from_ptr_and_get_ref(ptr
)
465 def __setitem__(self
, index
, value
):
466 self
._check
_index
(index
)
467 value
= create_value(value
)
470 ptr
= native_bt
.value_null
474 status
= native_bt
.value_array_set_element_by_index(
475 self
._ptr
, index
, ptr
)
476 self
._handle
_status
(status
)
478 def append(self
, value
):
479 value
= create_value(value
)
482 ptr
= native_bt
.value_null
486 status
= native_bt
.value_array_append_element(self
._ptr
, ptr
)
487 self
._handle
_status
(status
)
489 def __iadd__(self
, iterable
):
490 # Python will raise a TypeError if there's anything wrong with
491 # the iterable protocol.
492 for elem
in iterable
:
498 return '[{}]'.format(', '.join([repr(v
) for v
in self
]))
500 def insert(self
, value
):
501 raise NotImplementedError
504 class _MapValueKeyIterator(collections
.abc
.Iterator
):
505 def __init__(self
, map_obj
):
506 self
._map
_obj
= map_obj
508 keys_ptr
= native_bt
.value_map_get_keys(map_obj
._ptr
)
511 raise RuntimeError('unexpected error: cannot get map value object keys')
513 self
._keys
= _create_from_ptr(keys_ptr
)
516 if self
._at
== len(self
._map
_obj
):
519 key
= self
._keys
[self
._at
]
524 class MapValue(_Container
, collections
.abc
.MutableMapping
, _Value
):
527 def __init__(self
, value
=None):
528 ptr
= native_bt
.value_map_create()
529 self
._check
_create
_status
(ptr
)
530 super().__init
__(ptr
)
532 # Python will raise a TypeError if there's anything wrong with
533 # the iterable/mapping protocol.
534 if value
is not None:
535 for key
, elem
in value
.items():
538 def __ne__(self
, other
):
539 return _Value
.__ne
__(self
, other
)
541 def __eq__(self
, other
):
542 if not isinstance(other
, collections
.abc
.Mapping
):
545 if len(self
) != len(other
):
549 for self_key
in self
:
550 if self_key
not in other
:
553 if self
[self_key
] != other
[self_key
]:
559 size
= native_bt
.value_map_get_size(self
._ptr
)
563 def __contains__(self
, key
):
564 self
._check
_key
_type
(key
)
565 return native_bt
.value_map_has_entry(self
._ptr
, key
)
567 def _check_key_type(self
, key
):
568 utils
._check
_str
(key
)
570 def _check_key(self
, key
):
574 def __getitem__(self
, key
):
576 ptr
= native_bt
.value_map_borrow_entry_value(self
._ptr
, key
)
578 return _create_from_ptr_and_get_ref(ptr
)
581 return _MapValueKeyIterator(self
)
583 def __setitem__(self
, key
, value
):
584 self
._check
_key
_type
(key
)
585 value
= create_value(value
)
588 ptr
= native_bt
.value_null
592 status
= native_bt
.value_map_insert_entry(self
._ptr
, key
, ptr
)
593 self
._handle
_status
(status
)
596 items
= ['{}: {}'.format(repr(k
), repr(v
)) for k
, v
in self
.items()]
597 return '{{{}}}'.format(', '.join(items
))
601 native_bt
.VALUE_TYPE_BOOL
: BoolValue
,
602 native_bt
.VALUE_TYPE_UNSIGNED_INTEGER
: UnsignedIntegerValue
,
603 native_bt
.VALUE_TYPE_SIGNED_INTEGER
: SignedIntegerValue
,
604 native_bt
.VALUE_TYPE_REAL
: RealValue
,
605 native_bt
.VALUE_TYPE_STRING
: StringValue
,
606 native_bt
.VALUE_TYPE_ARRAY
: ArrayValue
,
607 native_bt
.VALUE_TYPE_MAP
: MapValue
,