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 _create_from_ptr(ptr
):
36 # bt_value_null is translated to None. However, we are given a reference
37 # to it that we are not going to manage anymore, since we don't create a
38 # Python wrapper for it. Therefore put that reference immediately.
39 if ptr
== native_bt
.value_null
:
40 bt2
.value
._Value
._put
_ref
(ptr
)
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 _check_create_status(self
, ptr
):
93 raise bt2
.CreationError(
94 'cannot create {} value object'.format(self
._NAME
.lower()))
97 @functools.total_ordering
98 class _NumericValue(_Value
):
100 def _extract_value(other
):
101 if isinstance(other
, BoolValue
) or isinstance(other
, bool):
104 if isinstance(other
, numbers
.Integral
):
107 if isinstance(other
, numbers
.Real
):
110 if isinstance(other
, numbers
.Complex
):
111 return complex(other
)
113 raise TypeError("'{}' object is not a number object".format(other
.__class
__.__name
__))
116 return int(self
._value
)
119 return float(self
._value
)
122 return repr(self
._value
)
124 def __lt__(self
, other
):
125 return self
._value
< self
._extract
_value
(other
)
127 def __eq__(self
, other
):
129 return self
._value
== self
._extract
_value
(other
)
133 def __rmod__(self
, other
):
134 return self
._extract
_value
(other
) % self
._value
136 def __mod__(self
, other
):
137 return self
._value
% self
._extract
_value
(other
)
139 def __rfloordiv__(self
, other
):
140 return self
._extract
_value
(other
) // self
._value
142 def __floordiv__(self
, other
):
143 return self
._value
// self
._extract
_value
(other
)
145 def __round__(self
, ndigits
=None):
147 return round(self
._value
)
149 return round(self
._value
, ndigits
)
152 return math
.ceil(self
._value
)
155 return math
.floor(self
._value
)
158 return int(self
._value
)
161 return abs(self
._value
)
163 def __add__(self
, other
):
164 return self
._value
+ self
._extract
_value
(other
)
166 def __radd__(self
, other
):
167 return self
.__add
__(other
)
175 def __mul__(self
, other
):
176 return self
._value
* self
._extract
_value
(other
)
178 def __rmul__(self
, other
):
179 return self
.__mul
__(other
)
181 def __truediv__(self
, other
):
182 return self
._value
/ self
._extract
_value
(other
)
184 def __rtruediv__(self
, other
):
185 return self
._extract
_value
(other
) / self
._value
187 def __pow__(self
, exponent
):
188 return self
._value
** self
._extract
_value
(exponent
)
190 def __rpow__(self
, base
):
191 return self
._extract
_value
(base
) ** self
._value
194 class _IntegralValue(_NumericValue
, numbers
.Integral
):
195 def __lshift__(self
, other
):
196 return self
._value
<< self
._extract
_value
(other
)
198 def __rlshift__(self
, other
):
199 return self
._extract
_value
(other
) << self
._value
201 def __rshift__(self
, other
):
202 return self
._value
>> self
._extract
_value
(other
)
204 def __rrshift__(self
, other
):
205 return self
._extract
_value
(other
) >> self
._value
207 def __and__(self
, other
):
208 return self
._value
& self
._extract
_value
(other
)
210 def __rand__(self
, other
):
211 return self
._extract
_value
(other
) & self
._value
213 def __xor__(self
, other
):
214 return self
._value ^ self
._extract
_value
(other
)
216 def __rxor__(self
, other
):
217 return self
._extract
_value
(other
) ^ self
._value
219 def __or__(self
, other
):
220 return self
._value | self
._extract
_value
(other
)
222 def __ror__(self
, other
):
223 return self
._extract
_value
(other
) | self
._value
225 def __invert__(self
):
229 class _RealValue(_NumericValue
, numbers
.Real
):
233 class BoolValue(_IntegralValue
):
236 def __init__(self
, value
=None):
238 ptr
= native_bt
.value_bool_create()
240 ptr
= native_bt
.value_bool_create_init(self
._value
_to
_bool
(value
))
242 self
._check
_create
_status
(ptr
)
243 super().__init
__(ptr
)
249 return repr(self
._value
)
251 def _value_to_bool(self
, value
):
252 if isinstance(value
, BoolValue
):
255 if not isinstance(value
, bool):
256 raise TypeError("'{}' object is not a 'bool' or 'BoolValue' object".format(value
.__class
__))
262 value
= native_bt
.value_bool_get(self
._ptr
)
265 def _set_value(self
, value
):
266 native_bt
.value_bool_set(self
._ptr
, self
._value
_to
_bool
(value
))
268 value
= property(fset
=_set_value
)
271 class _IntegerValue(_IntegralValue
):
272 def __init__(self
, value
=None):
274 ptr
= self
._create
_default
_value
()
276 ptr
= self
._create
_value
(self
._value
_to
_int
(value
))
278 self
._check
_create
_status
(ptr
)
279 super().__init
__(ptr
)
281 def _value_to_int(self
, value
):
282 if not isinstance(value
, numbers
.Integral
):
283 raise TypeError('expecting an integral number object')
286 self
._check
_int
_range
(value
)
291 return self
._get
_value
(self
._ptr
)
293 def _prop_set_value(self
, value
):
294 self
._set
_value
(self
._ptr
, self
._value
_to
_int
(value
))
296 value
= property(fset
=_prop_set_value
)
299 class UnsignedIntegerValue(_IntegerValue
):
300 _check_int_range
= staticmethod(utils
._check
_uint
64)
301 _create_default_value
= staticmethod(native_bt
.value_unsigned_integer_create
)
302 _create_value
= staticmethod(native_bt
.value_unsigned_integer_create_init
)
303 _set_value
= staticmethod(native_bt
.value_unsigned_integer_set
)
304 _get_value
= staticmethod(native_bt
.value_unsigned_integer_get
)
307 class SignedIntegerValue(_IntegerValue
):
308 _check_int_range
= staticmethod(utils
._check
_int
64)
309 _create_default_value
= staticmethod(native_bt
.value_signed_integer_create
)
310 _create_value
= staticmethod(native_bt
.value_signed_integer_create_init
)
311 _set_value
= staticmethod(native_bt
.value_signed_integer_set
)
312 _get_value
= staticmethod(native_bt
.value_signed_integer_get
)
315 class RealValue(_RealValue
):
316 _NAME
= 'Real number'
318 def __init__(self
, value
=None):
320 ptr
= native_bt
.value_real_create()
322 value
= self
._value
_to
_float
(value
)
323 ptr
= native_bt
.value_real_create_init(value
)
325 self
._check
_create
_status
(ptr
)
326 super().__init
__(ptr
)
328 def _value_to_float(self
, value
):
329 if not isinstance(value
, numbers
.Real
):
330 raise TypeError("expecting a real number object")
336 return native_bt
.value_real_get(self
._ptr
)
338 def _set_value(self
, value
):
339 native_bt
.value_real_set(self
._ptr
, self
._value
_to
_float
(value
))
341 value
= property(fset
=_set_value
)
344 @functools.total_ordering
345 class StringValue(collections
.abc
.Sequence
, _Value
):
348 def __init__(self
, value
=None):
350 ptr
= native_bt
.value_string_create()
352 ptr
= native_bt
.value_string_create_init(self
._value
_to
_str
(value
))
354 self
._check
_create
_status
(ptr
)
355 super().__init
__(ptr
)
357 def _value_to_str(self
, value
):
358 if isinstance(value
, self
.__class
__):
361 utils
._check
_str
(value
)
366 return native_bt
.value_string_get(self
._ptr
)
368 def _set_value(self
, value
):
369 status
= native_bt
.value_string_set(self
._ptr
, self
._value
_to
_str
(value
))
370 utils
._handle
_func
_status
(status
)
372 value
= property(fset
=_set_value
)
374 def __eq__(self
, other
):
376 return self
._value
== self
._value
_to
_str
(other
)
380 def __lt__(self
, other
):
381 return self
._value
< self
._value
_to
_str
(other
)
384 return bool(self
._value
)
387 return repr(self
._value
)
392 def __getitem__(self
, index
):
393 return self
._value
[index
]
396 return len(self
._value
)
398 def __iadd__(self
, value
):
399 curvalue
= self
._value
400 curvalue
+= self
._value
_to
_str
(value
)
401 self
.value
= curvalue
407 return len(self
) != 0
409 def __delitem__(self
, index
):
410 raise NotImplementedError
413 class ArrayValue(_Container
, collections
.abc
.MutableSequence
, _Value
):
416 def __init__(self
, value
=None):
417 ptr
= native_bt
.value_array_create()
418 self
._check
_create
_status
(ptr
)
419 super().__init
__(ptr
)
421 # Python will raise a TypeError if there's anything wrong with
422 # the iterable protocol.
423 if value
is not None:
427 def __eq__(self
, other
):
428 if not isinstance(other
, collections
.abc
.Sequence
):
431 if len(self
) != len(other
):
435 for self_elem
, other_elem
in zip(self
, other
):
436 if self_elem
!= other_elem
:
442 size
= native_bt
.value_array_get_size(self
._ptr
)
446 def _check_index(self
, index
):
447 # TODO: support slices also
448 if not isinstance(index
, numbers
.Integral
):
449 raise TypeError("'{}' object is not an integral number object: invalid index".format(index
.__class
__.__name
__))
453 if index
< 0 or index
>= len(self
):
454 raise IndexError('array value object index is out of range')
456 def __getitem__(self
, index
):
457 self
._check
_index
(index
)
458 ptr
= native_bt
.value_array_borrow_element_by_index(self
._ptr
, index
)
460 return _create_from_ptr_and_get_ref(ptr
)
462 def __setitem__(self
, index
, value
):
463 self
._check
_index
(index
)
464 value
= create_value(value
)
467 ptr
= native_bt
.value_null
471 status
= native_bt
.value_array_set_element_by_index(
472 self
._ptr
, index
, ptr
)
473 utils
._handle
_func
_status
(status
)
475 def append(self
, value
):
476 value
= create_value(value
)
479 ptr
= native_bt
.value_null
483 status
= native_bt
.value_array_append_element(self
._ptr
, ptr
)
484 utils
._handle
_func
_status
(status
)
486 def __iadd__(self
, iterable
):
487 # Python will raise a TypeError if there's anything wrong with
488 # the iterable protocol.
489 for elem
in iterable
:
495 return '[{}]'.format(', '.join([repr(v
) for v
in self
]))
497 def insert(self
, value
):
498 raise NotImplementedError
501 class _MapValueKeyIterator(collections
.abc
.Iterator
):
502 def __init__(self
, map_obj
):
503 self
._map
_obj
= map_obj
505 keys_ptr
= native_bt
.value_map_get_keys(map_obj
._ptr
)
508 raise RuntimeError('unexpected error: cannot get map value object keys')
510 self
._keys
= _create_from_ptr(keys_ptr
)
513 if self
._at
== len(self
._map
_obj
):
516 key
= self
._keys
[self
._at
]
521 class MapValue(_Container
, collections
.abc
.MutableMapping
, _Value
):
524 def __init__(self
, value
=None):
525 ptr
= native_bt
.value_map_create()
526 self
._check
_create
_status
(ptr
)
527 super().__init
__(ptr
)
529 # Python will raise a TypeError if there's anything wrong with
530 # the iterable/mapping protocol.
531 if value
is not None:
532 for key
, elem
in value
.items():
535 def __ne__(self
, other
):
536 return _Value
.__ne
__(self
, other
)
538 def __eq__(self
, other
):
539 if not isinstance(other
, collections
.abc
.Mapping
):
542 if len(self
) != len(other
):
546 for self_key
in self
:
547 if self_key
not in other
:
550 if self
[self_key
] != other
[self_key
]:
556 size
= native_bt
.value_map_get_size(self
._ptr
)
560 def __contains__(self
, key
):
561 self
._check
_key
_type
(key
)
562 return native_bt
.value_map_has_entry(self
._ptr
, key
)
564 def _check_key_type(self
, key
):
565 utils
._check
_str
(key
)
567 def _check_key(self
, key
):
571 def __getitem__(self
, key
):
573 ptr
= native_bt
.value_map_borrow_entry_value(self
._ptr
, key
)
575 return _create_from_ptr_and_get_ref(ptr
)
578 return _MapValueKeyIterator(self
)
580 def __setitem__(self
, key
, value
):
581 self
._check
_key
_type
(key
)
582 value
= create_value(value
)
585 ptr
= native_bt
.value_null
589 status
= native_bt
.value_map_insert_entry(self
._ptr
, key
, ptr
)
590 utils
._handle
_func
_status
(status
)
593 items
= ['{}: {}'.format(repr(k
), repr(v
)) for k
, v
in self
.items()]
594 return '{{{}}}'.format(', '.join(items
))
598 native_bt
.VALUE_TYPE_BOOL
: BoolValue
,
599 native_bt
.VALUE_TYPE_UNSIGNED_INTEGER
: UnsignedIntegerValue
,
600 native_bt
.VALUE_TYPE_SIGNED_INTEGER
: SignedIntegerValue
,
601 native_bt
.VALUE_TYPE_REAL
: RealValue
,
602 native_bt
.VALUE_TYPE_STRING
: StringValue
,
603 native_bt
.VALUE_TYPE_ARRAY
: ArrayValue
,
604 native_bt
.VALUE_TYPE_MAP
: MapValue
,