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 __ne__(self
, other
):
93 return not (self
== other
)
95 def _handle_status(self
, status
):
96 _handle_status(status
, self
._NAME
)
98 def _check_create_status(self
, ptr
):
100 raise bt2
.CreationError(
101 'cannot create {} value object'.format(self
._NAME
.lower()))
104 @functools.total_ordering
105 class _NumericValue(_Value
):
107 def _extract_value(other
):
108 if isinstance(other
, BoolValue
) or isinstance(other
, bool):
111 if isinstance(other
, numbers
.Integral
):
114 if isinstance(other
, numbers
.Real
):
117 if isinstance(other
, numbers
.Complex
):
118 return complex(other
)
120 raise TypeError("'{}' object is not a number object".format(other
.__class
__.__name
__))
123 return int(self
._value
)
126 return float(self
._value
)
129 return repr(self
._value
)
131 def __lt__(self
, other
):
132 return self
._value
< self
._extract
_value
(other
)
134 def __eq__(self
, other
):
136 return self
._value
== self
._extract
_value
(other
)
140 def __rmod__(self
, other
):
141 return self
._extract
_value
(other
) % self
._value
143 def __mod__(self
, other
):
144 return self
._value
% self
._extract
_value
(other
)
146 def __rfloordiv__(self
, other
):
147 return self
._extract
_value
(other
) // self
._value
149 def __floordiv__(self
, other
):
150 return self
._value
// self
._extract
_value
(other
)
152 def __round__(self
, ndigits
=None):
154 return round(self
._value
)
156 return round(self
._value
, ndigits
)
159 return math
.ceil(self
._value
)
162 return math
.floor(self
._value
)
165 return int(self
._value
)
168 return abs(self
._value
)
170 def __add__(self
, other
):
171 return self
._value
+ self
._extract
_value
(other
)
173 def __radd__(self
, other
):
174 return self
.__add
__(other
)
182 def __mul__(self
, other
):
183 return self
._value
* self
._extract
_value
(other
)
185 def __rmul__(self
, other
):
186 return self
.__mul
__(other
)
188 def __truediv__(self
, other
):
189 return self
._value
/ self
._extract
_value
(other
)
191 def __rtruediv__(self
, other
):
192 return self
._extract
_value
(other
) / self
._value
194 def __pow__(self
, exponent
):
195 return self
._value
** self
._extract
_value
(exponent
)
197 def __rpow__(self
, base
):
198 return self
._extract
_value
(base
) ** self
._value
201 class _IntegralValue(_NumericValue
, numbers
.Integral
):
202 def __lshift__(self
, other
):
203 return self
._value
<< self
._extract
_value
(other
)
205 def __rlshift__(self
, other
):
206 return self
._extract
_value
(other
) << self
._value
208 def __rshift__(self
, other
):
209 return self
._value
>> self
._extract
_value
(other
)
211 def __rrshift__(self
, other
):
212 return self
._extract
_value
(other
) >> self
._value
214 def __and__(self
, other
):
215 return self
._value
& self
._extract
_value
(other
)
217 def __rand__(self
, other
):
218 return self
._extract
_value
(other
) & self
._value
220 def __xor__(self
, other
):
221 return self
._value ^ self
._extract
_value
(other
)
223 def __rxor__(self
, other
):
224 return self
._extract
_value
(other
) ^ self
._value
226 def __or__(self
, other
):
227 return self
._value | self
._extract
_value
(other
)
229 def __ror__(self
, other
):
230 return self
._extract
_value
(other
) | self
._value
232 def __invert__(self
):
236 class _RealValue(_NumericValue
, numbers
.Real
):
240 class BoolValue(_IntegralValue
):
243 def __init__(self
, value
=None):
245 ptr
= native_bt
.value_bool_create()
247 ptr
= native_bt
.value_bool_create_init(self
._value
_to
_bool
(value
))
249 self
._check
_create
_status
(ptr
)
250 super().__init
__(ptr
)
256 return repr(self
._value
)
258 def _value_to_bool(self
, value
):
259 if isinstance(value
, BoolValue
):
262 if not isinstance(value
, bool):
263 raise TypeError("'{}' object is not a 'bool' or 'BoolValue' object".format(value
.__class
__))
269 value
= native_bt
.value_bool_get(self
._ptr
)
272 def _set_value(self
, value
):
273 native_bt
.value_bool_set(self
._ptr
, self
._value
_to
_bool
(value
))
275 value
= property(fset
=_set_value
)
278 class _IntegerValue(_IntegralValue
):
279 def __init__(self
, value
=None):
281 ptr
= self
._create
_default
_value
()
283 ptr
= self
._create
_value
(self
._value
_to
_int
(value
))
285 self
._check
_create
_status
(ptr
)
286 super().__init
__(ptr
)
288 def _value_to_int(self
, value
):
289 if not isinstance(value
, numbers
.Real
):
290 raise TypeError('expecting a number object')
293 self
._check
_int
_range
(value
)
298 return self
._get
_value
(self
._ptr
)
300 def _prop_set_value(self
, value
):
301 self
._set
_value
(self
._ptr
, self
._value
_to
_int
(value
))
303 value
= property(fset
=_prop_set_value
)
306 class UnsignedIntegerValue(_IntegerValue
):
307 _check_int_range
= staticmethod(utils
._check
_uint
64)
308 _create_default_value
= staticmethod(native_bt
.value_unsigned_integer_create
)
309 _create_value
= staticmethod(native_bt
.value_unsigned_integer_create_init
)
310 _set_value
= staticmethod(native_bt
.value_unsigned_integer_set
)
311 _get_value
= staticmethod(native_bt
.value_unsigned_integer_get
)
314 class SignedIntegerValue(_IntegerValue
):
315 _check_int_range
= staticmethod(utils
._check
_int
64)
316 _create_default_value
= staticmethod(native_bt
.value_signed_integer_create
)
317 _create_value
= staticmethod(native_bt
.value_signed_integer_create_init
)
318 _set_value
= staticmethod(native_bt
.value_signed_integer_set
)
319 _get_value
= staticmethod(native_bt
.value_signed_integer_get
)
322 class RealValue(_RealValue
):
323 _NAME
= 'Real number'
325 def __init__(self
, value
=None):
327 ptr
= native_bt
.value_real_create()
329 value
= self
._value
_to
_float
(value
)
330 ptr
= native_bt
.value_real_create_init(value
)
332 self
._check
_create
_status
(ptr
)
333 super().__init
__(ptr
)
335 def _value_to_float(self
, value
):
336 if not isinstance(value
, numbers
.Real
):
337 raise TypeError("expecting a real number object")
343 return native_bt
.value_real_get(self
._ptr
)
345 def _set_value(self
, value
):
346 native_bt
.value_real_set(self
._ptr
, self
._value
_to
_float
(value
))
348 value
= property(fset
=_set_value
)
351 @functools.total_ordering
352 class StringValue(collections
.abc
.Sequence
, _Value
):
355 def __init__(self
, value
=None):
357 ptr
= native_bt
.value_string_create()
359 ptr
= native_bt
.value_string_create_init(self
._value
_to
_str
(value
))
361 self
._check
_create
_status
(ptr
)
362 super().__init
__(ptr
)
364 def _value_to_str(self
, value
):
365 if isinstance(value
, self
.__class
__):
368 utils
._check
_str
(value
)
373 return native_bt
.value_string_get(self
._ptr
)
375 def _set_value(self
, value
):
376 status
= native_bt
.value_string_set(self
._ptr
, self
._value
_to
_str
(value
))
377 self
._handle
_status
(status
)
379 value
= property(fset
=_set_value
)
381 def __eq__(self
, other
):
383 return self
._value
== self
._value
_to
_str
(other
)
387 def __lt__(self
, other
):
388 return self
._value
< self
._value
_to
_str
(other
)
391 return bool(self
._value
)
394 return repr(self
._value
)
399 def __getitem__(self
, index
):
400 return self
._value
[index
]
403 return len(self
._value
)
405 def __iadd__(self
, value
):
406 curvalue
= self
._value
407 curvalue
+= self
._value
_to
_str
(value
)
408 self
.value
= curvalue
414 return len(self
) != 0
416 def __delitem__(self
, index
):
417 raise NotImplementedError
420 class ArrayValue(_Container
, collections
.abc
.MutableSequence
, _Value
):
423 def __init__(self
, value
=None):
424 ptr
= native_bt
.value_array_create()
425 self
._check
_create
_status
(ptr
)
426 super().__init
__(ptr
)
428 # Python will raise a TypeError if there's anything wrong with
429 # the iterable protocol.
430 if value
is not None:
434 def __eq__(self
, other
):
435 if not isinstance(other
, collections
.abc
.Sequence
):
438 if len(self
) != len(other
):
442 for self_elem
, other_elem
in zip(self
, other
):
443 if self_elem
!= other_elem
:
449 size
= native_bt
.value_array_get_size(self
._ptr
)
453 def _check_index(self
, index
):
454 # TODO: support slices also
455 if not isinstance(index
, numbers
.Integral
):
456 raise TypeError("'{}' object is not an integral number object: invalid index".format(index
.__class
__.__name
__))
460 if index
< 0 or index
>= len(self
):
461 raise IndexError('array value object index is out of range')
463 def __getitem__(self
, index
):
464 self
._check
_index
(index
)
465 ptr
= native_bt
.value_array_borrow_element_by_index(self
._ptr
, index
)
467 return _create_from_ptr_and_get_ref(ptr
)
469 def __setitem__(self
, index
, value
):
470 self
._check
_index
(index
)
471 value
= create_value(value
)
474 ptr
= native_bt
.value_null
478 status
= native_bt
.value_array_set_element_by_index(
479 self
._ptr
, index
, ptr
)
480 self
._handle
_status
(status
)
482 def append(self
, value
):
483 value
= create_value(value
)
486 ptr
= native_bt
.value_null
490 status
= native_bt
.value_array_append_element(self
._ptr
, ptr
)
491 self
._handle
_status
(status
)
493 def __iadd__(self
, iterable
):
494 # Python will raise a TypeError if there's anything wrong with
495 # the iterable protocol.
496 for elem
in iterable
:
502 return '[{}]'.format(', '.join([repr(v
) for v
in self
]))
504 def insert(self
, value
):
505 raise NotImplementedError
508 class _MapValueKeyIterator(collections
.abc
.Iterator
):
509 def __init__(self
, map_obj
):
510 self
._map
_obj
= map_obj
512 keys_ptr
= native_bt
.value_map_get_keys(map_obj
._ptr
)
515 raise RuntimeError('unexpected error: cannot get map value object keys')
517 self
._keys
= _create_from_ptr(keys_ptr
)
520 if self
._at
== len(self
._map
_obj
):
523 key
= self
._keys
[self
._at
]
528 class MapValue(_Container
, collections
.abc
.MutableMapping
, _Value
):
531 def __init__(self
, value
=None):
532 ptr
= native_bt
.value_map_create()
533 self
._check
_create
_status
(ptr
)
534 super().__init
__(ptr
)
536 # Python will raise a TypeError if there's anything wrong with
537 # the iterable/mapping protocol.
538 if value
is not None:
539 for key
, elem
in value
.items():
542 def __ne__(self
, other
):
543 return _Value
.__ne
__(self
, other
)
545 def __eq__(self
, other
):
546 if not isinstance(other
, collections
.abc
.Mapping
):
549 if len(self
) != len(other
):
553 for self_key
in self
:
554 if self_key
not in other
:
557 if self
[self_key
] != other
[self_key
]:
563 size
= native_bt
.value_map_get_size(self
._ptr
)
567 def __contains__(self
, key
):
568 self
._check
_key
_type
(key
)
569 return native_bt
.value_map_has_entry(self
._ptr
, key
)
571 def _check_key_type(self
, key
):
572 utils
._check
_str
(key
)
574 def _check_key(self
, key
):
578 def __getitem__(self
, key
):
580 ptr
= native_bt
.value_map_borrow_entry_value(self
._ptr
, key
)
582 return _create_from_ptr_and_get_ref(ptr
)
585 return _MapValueKeyIterator(self
)
587 def __setitem__(self
, key
, value
):
588 self
._check
_key
_type
(key
)
589 value
= create_value(value
)
592 ptr
= native_bt
.value_null
596 status
= native_bt
.value_map_insert_entry(self
._ptr
, key
, ptr
)
597 self
._handle
_status
(status
)
600 items
= ['{}: {}'.format(repr(k
), repr(v
)) for k
, v
in self
.items()]
601 return '{{{}}}'.format(', '.join(items
))
605 native_bt
.VALUE_TYPE_BOOL
: BoolValue
,
606 native_bt
.VALUE_TYPE_UNSIGNED_INTEGER
: UnsignedIntegerValue
,
607 native_bt
.VALUE_TYPE_SIGNED_INTEGER
: SignedIntegerValue
,
608 native_bt
.VALUE_TYPE_REAL
: RealValue
,
609 native_bt
.VALUE_TYPE_STRING
: StringValue
,
610 native_bt
.VALUE_TYPE_ARRAY
: ArrayValue
,
611 native_bt
.VALUE_TYPE_MAP
: MapValue
,