d2cb4e076a11adc4f86eafecb9a9de3910a535c0
[babeltrace.git] / src / bindings / python / bt2 / bt2 / value.py
1 # SPDX-License-Identifier: MIT
2 #
3 # Copyright (c) 2017 Philippe Proulx <pproulx@efficios.com>
4
5 from bt2 import native_bt
6 from bt2 import object as bt2_object
7 from bt2 import utils as bt2_utils
8 from bt2 import error as bt2_error
9 import collections.abc
10 import functools
11 import numbers
12 import math
13 import abc
14
15
16 def _create_from_ptr_template(ptr, object_map):
17 if ptr is None:
18 return
19
20 # bt_value_null is translated to None. However, we are given a reference
21 # to it that we are not going to manage anymore, since we don't create a
22 # Python wrapper for it. Therefore put that reference immediately.
23 if ptr == native_bt.value_null:
24 _Value._put_ref(ptr)
25 return
26
27 typeid = native_bt.value_get_type(ptr)
28 return object_map[typeid]._create_from_ptr(ptr)
29
30
31 def _create_from_ptr(ptr):
32 return _create_from_ptr_template(ptr, _TYPE_TO_OBJ)
33
34
35 def _create_from_const_ptr(ptr):
36 return _create_from_ptr_template(ptr, _TYPE_TO_CONST_OBJ)
37
38
39 def _create_from_ptr_and_get_ref_template(ptr, object_map):
40 if ptr is None or ptr == native_bt.value_null:
41 return
42
43 typeid = native_bt.value_get_type(ptr)
44 return object_map[typeid]._create_from_ptr_and_get_ref(ptr)
45
46
47 def _create_from_ptr_and_get_ref(ptr):
48 return _create_from_ptr_and_get_ref_template(ptr, _TYPE_TO_OBJ)
49
50
51 def _create_from_const_ptr_and_get_ref(ptr):
52 return _create_from_ptr_and_get_ref_template(ptr, _TYPE_TO_CONST_OBJ)
53
54
55 def create_value(value):
56 if value is None:
57 # null value object
58 return
59
60 if isinstance(value, _Value):
61 return value
62
63 if isinstance(value, bool):
64 return BoolValue(value)
65
66 if isinstance(value, numbers.Integral):
67 return SignedIntegerValue(value)
68
69 if isinstance(value, numbers.Real):
70 return RealValue(value)
71
72 if isinstance(value, str):
73 return StringValue(value)
74
75 if isinstance(value, collections.abc.Sequence):
76 return ArrayValue(value)
77
78 if isinstance(value, collections.abc.Mapping):
79 return MapValue(value)
80
81 raise TypeError(
82 "cannot create value object from '{}' object".format(value.__class__.__name__)
83 )
84
85
86 class _ValueConst(bt2_object._SharedObject, metaclass=abc.ABCMeta):
87 @staticmethod
88 def _get_ref(ptr):
89 native_bt.value_get_ref(ptr)
90
91 @staticmethod
92 def _put_ref(ptr):
93 native_bt.value_put_ref(ptr)
94
95 _create_value_from_ptr = staticmethod(_create_from_const_ptr)
96 _create_value_from_ptr_and_get_ref = staticmethod(
97 _create_from_const_ptr_and_get_ref
98 )
99
100 def __ne__(self, other):
101 return not (self == other)
102
103 def _check_create_status(self, ptr):
104 if ptr is None:
105 raise bt2_error._MemoryError(
106 "cannot create {} value object".format(self._NAME.lower())
107 )
108
109
110 class _Value(_ValueConst):
111 _create_value_from_ptr = staticmethod(_create_from_ptr)
112 _create_value_from_ptr_and_get_ref = staticmethod(_create_from_ptr_and_get_ref)
113
114
115 @functools.total_ordering
116 class _NumericValueConst(_ValueConst):
117 @staticmethod
118 def _extract_value(other):
119 if isinstance(other, _BoolValueConst) or isinstance(other, bool):
120 return bool(other)
121
122 if isinstance(other, numbers.Integral):
123 return int(other)
124
125 if isinstance(other, numbers.Real):
126 return float(other)
127
128 if isinstance(other, numbers.Complex):
129 return complex(other)
130
131 raise TypeError(
132 "'{}' object is not a number object".format(other.__class__.__name__)
133 )
134
135 def __int__(self):
136 return int(self._value)
137
138 def __float__(self):
139 return float(self._value)
140
141 def __repr__(self):
142 return repr(self._value)
143
144 def __lt__(self, other):
145 return self._value < self._extract_value(other)
146
147 def __eq__(self, other):
148 try:
149 return self._value == self._extract_value(other)
150 except Exception:
151 return False
152
153 def __rmod__(self, other):
154 return self._extract_value(other) % self._value
155
156 def __mod__(self, other):
157 return self._value % self._extract_value(other)
158
159 def __rfloordiv__(self, other):
160 return self._extract_value(other) // self._value
161
162 def __floordiv__(self, other):
163 return self._value // self._extract_value(other)
164
165 def __round__(self, ndigits=None):
166 if ndigits is None:
167 return round(self._value)
168 else:
169 return round(self._value, ndigits)
170
171 def __ceil__(self):
172 return math.ceil(self._value)
173
174 def __floor__(self):
175 return math.floor(self._value)
176
177 def __trunc__(self):
178 return int(self._value)
179
180 def __abs__(self):
181 return abs(self._value)
182
183 def __add__(self, other):
184 return self._value + self._extract_value(other)
185
186 def __radd__(self, other):
187 return self.__add__(other)
188
189 def __neg__(self):
190 return -self._value
191
192 def __pos__(self):
193 return +self._value
194
195 def __mul__(self, other):
196 return self._value * self._extract_value(other)
197
198 def __rmul__(self, other):
199 return self.__mul__(other)
200
201 def __truediv__(self, other):
202 return self._value / self._extract_value(other)
203
204 def __rtruediv__(self, other):
205 return self._extract_value(other) / self._value
206
207 def __pow__(self, exponent):
208 return self._value ** self._extract_value(exponent)
209
210 def __rpow__(self, base):
211 return self._extract_value(base) ** self._value
212
213
214 class _NumericValue(_NumericValueConst, _Value):
215 pass
216
217
218 class _IntegralValueConst(_NumericValueConst, numbers.Integral):
219 def __lshift__(self, other):
220 return self._value << self._extract_value(other)
221
222 def __rlshift__(self, other):
223 return self._extract_value(other) << self._value
224
225 def __rshift__(self, other):
226 return self._value >> self._extract_value(other)
227
228 def __rrshift__(self, other):
229 return self._extract_value(other) >> self._value
230
231 def __and__(self, other):
232 return self._value & self._extract_value(other)
233
234 def __rand__(self, other):
235 return self._extract_value(other) & self._value
236
237 def __xor__(self, other):
238 return self._value ^ self._extract_value(other)
239
240 def __rxor__(self, other):
241 return self._extract_value(other) ^ self._value
242
243 def __or__(self, other):
244 return self._value | self._extract_value(other)
245
246 def __ror__(self, other):
247 return self._extract_value(other) | self._value
248
249 def __invert__(self):
250 return ~self._value
251
252
253 class _IntegralValue(_IntegralValueConst, _NumericValue):
254 pass
255
256
257 class _BoolValueConst(_IntegralValueConst):
258 _NAME = "Const boolean"
259
260 def __bool__(self):
261 return self._value
262
263 def __repr__(self):
264 return repr(self._value)
265
266 @property
267 def _value(self):
268 value = native_bt.value_bool_get(self._ptr)
269 return value != 0
270
271
272 class BoolValue(_BoolValueConst, _IntegralValue):
273 _NAME = "Boolean"
274
275 def __init__(self, value=None):
276 if value is None:
277 ptr = native_bt.value_bool_create()
278 else:
279 ptr = native_bt.value_bool_create_init(self._value_to_bool(value))
280
281 self._check_create_status(ptr)
282 super().__init__(ptr)
283
284 @classmethod
285 def _value_to_bool(cls, value):
286 if isinstance(value, _BoolValueConst):
287 value = value._value
288
289 if not isinstance(value, bool):
290 raise TypeError(
291 "'{}' object is not a 'bool', 'BoolValue', or '_BoolValueConst' object".format(
292 value.__class__
293 )
294 )
295
296 return value
297
298 def _set_value(self, value):
299 native_bt.value_bool_set(self._ptr, self._value_to_bool(value))
300
301 value = property(fset=_set_value)
302
303
304 class _IntegerValueConst(_IntegralValueConst):
305 @property
306 def _value(self):
307 return self._get_value(self._ptr)
308
309
310 class _IntegerValue(_IntegerValueConst, _IntegralValue):
311 def __init__(self, value=None):
312 if value is None:
313 ptr = self._create_default_value()
314 else:
315 ptr = self._create_value(self._value_to_int(value))
316
317 self._check_create_status(ptr)
318 super().__init__(ptr)
319
320 @classmethod
321 def _value_to_int(cls, value):
322 if not isinstance(value, numbers.Integral):
323 raise TypeError("expecting an integral number object")
324
325 value = int(value)
326 cls._check_int_range(value)
327 return value
328
329 def _prop_set_value(self, value):
330 self._set_value(self._ptr, self._value_to_int(value))
331
332 value = property(fset=_prop_set_value)
333
334
335 class _UnsignedIntegerValueConst(_IntegerValueConst):
336 _NAME = "Const unsigned integer"
337 _get_value = staticmethod(native_bt.value_integer_unsigned_get)
338
339
340 class UnsignedIntegerValue(_UnsignedIntegerValueConst, _IntegerValue):
341 _NAME = "Unsigned integer"
342 _check_int_range = staticmethod(bt2_utils._check_uint64)
343 _create_default_value = staticmethod(native_bt.value_integer_unsigned_create)
344 _create_value = staticmethod(native_bt.value_integer_unsigned_create_init)
345 _set_value = staticmethod(native_bt.value_integer_unsigned_set)
346
347
348 class _SignedIntegerValueConst(_IntegerValueConst):
349 _NAME = "Const signed integer"
350 _get_value = staticmethod(native_bt.value_integer_signed_get)
351
352
353 class SignedIntegerValue(_SignedIntegerValueConst, _IntegerValue):
354 _NAME = "Signed integer"
355 _check_int_range = staticmethod(bt2_utils._check_int64)
356 _create_default_value = staticmethod(native_bt.value_integer_signed_create)
357 _create_value = staticmethod(native_bt.value_integer_signed_create_init)
358 _set_value = staticmethod(native_bt.value_integer_signed_set)
359
360
361 class _RealValueConst(_NumericValueConst, numbers.Real):
362 _NAME = "Const real number"
363
364 @property
365 def _value(self):
366 return native_bt.value_real_get(self._ptr)
367
368
369 class RealValue(_RealValueConst, _NumericValue):
370 _NAME = "Real number"
371
372 def __init__(self, value=None):
373 if value is None:
374 ptr = native_bt.value_real_create()
375 else:
376 value = self._value_to_float(value)
377 ptr = native_bt.value_real_create_init(value)
378
379 self._check_create_status(ptr)
380 super().__init__(ptr)
381
382 @classmethod
383 def _value_to_float(cls, value):
384 if not isinstance(value, numbers.Real):
385 raise TypeError("expecting a real number object")
386
387 return float(value)
388
389 def _set_value(self, value):
390 native_bt.value_real_set(self._ptr, self._value_to_float(value))
391
392 value = property(fset=_set_value)
393
394
395 @functools.total_ordering
396 class _StringValueConst(collections.abc.Sequence, _Value):
397 _NAME = "Const string"
398
399 @classmethod
400 def _value_to_str(cls, value):
401 if isinstance(value, _StringValueConst):
402 value = value._value
403
404 bt2_utils._check_str(value)
405 return value
406
407 @property
408 def _value(self):
409 return native_bt.value_string_get(self._ptr)
410
411 def __eq__(self, other):
412 try:
413 return self._value == self._value_to_str(other)
414 except Exception:
415 return False
416
417 def __lt__(self, other):
418 return self._value < self._value_to_str(other)
419
420 def __bool__(self):
421 return bool(self._value)
422
423 def __repr__(self):
424 return repr(self._value)
425
426 def __str__(self):
427 return self._value
428
429 def __getitem__(self, index):
430 return self._value[index]
431
432 def __len__(self):
433 return len(self._value)
434
435 def __contains__(self, item):
436 return self._value_to_str(item) in self._value
437
438
439 class StringValue(_StringValueConst, _Value):
440 _NAME = "String"
441
442 def __init__(self, value=None):
443 if value is None:
444 ptr = native_bt.value_string_create()
445 else:
446 ptr = native_bt.value_string_create_init(self._value_to_str(value))
447
448 self._check_create_status(ptr)
449 super().__init__(ptr)
450
451 def _set_value(self, value):
452 status = native_bt.value_string_set(self._ptr, self._value_to_str(value))
453 bt2_utils._handle_func_status(status)
454
455 value = property(fset=_set_value)
456
457 def __iadd__(self, value):
458 curvalue = self._value
459 curvalue += self._value_to_str(value)
460 self.value = curvalue
461 return self
462
463
464 class _ContainerConst:
465 def __bool__(self):
466 return len(self) != 0
467
468
469 class _Container(_ContainerConst):
470 def __delitem__(self, index):
471 raise NotImplementedError
472
473
474 class _ArrayValueConst(_ContainerConst, collections.abc.Sequence, _ValueConst):
475 _NAME = "Const array"
476 _borrow_element_by_index = staticmethod(
477 native_bt.value_array_borrow_element_by_index_const
478 )
479 _is_const = True
480
481 def __eq__(self, other):
482 if not isinstance(other, collections.abc.Sequence):
483 return False
484
485 if len(self) != len(other):
486 # early mismatch
487 return False
488
489 for self_elem, other_elem in zip(self, other):
490 if self_elem != other_elem:
491 return False
492
493 return True
494
495 def __len__(self):
496 size = native_bt.value_array_get_length(self._ptr)
497 assert size >= 0
498 return size
499
500 def _check_index(self, index):
501 # TODO: support slices also
502 if not isinstance(index, numbers.Integral):
503 raise TypeError(
504 "'{}' object is not an integral number object: invalid index".format(
505 index.__class__.__name__
506 )
507 )
508
509 index = int(index)
510
511 if index < 0 or index >= len(self):
512 raise IndexError("array value object index is out of range")
513
514 def __getitem__(self, index):
515 self._check_index(index)
516 ptr = self._borrow_element_by_index(self._ptr, index)
517 assert ptr
518 return self._create_value_from_ptr_and_get_ref(ptr)
519
520 def __repr__(self):
521 return "[{}]".format(", ".join([repr(v) for v in self]))
522
523
524 class ArrayValue(_ArrayValueConst, _Container, collections.abc.MutableSequence, _Value):
525 _NAME = "Array"
526 _borrow_element_by_index = staticmethod(
527 native_bt.value_array_borrow_element_by_index
528 )
529
530 def __init__(self, value=None):
531 ptr = native_bt.value_array_create()
532 self._check_create_status(ptr)
533 super().__init__(ptr)
534
535 # Python will raise a TypeError if there's anything wrong with
536 # the iterable protocol.
537 if value is not None:
538 for elem in value:
539 self.append(elem)
540
541 def __setitem__(self, index, value):
542 self._check_index(index)
543 value = create_value(value)
544
545 if value is None:
546 ptr = native_bt.value_null
547 else:
548 ptr = value._ptr
549
550 status = native_bt.value_array_set_element_by_index(self._ptr, index, ptr)
551 bt2_utils._handle_func_status(status)
552
553 def append(self, value):
554 value = create_value(value)
555
556 if value is None:
557 ptr = native_bt.value_null
558 else:
559 ptr = value._ptr
560
561 status = native_bt.value_array_append_element(self._ptr, ptr)
562 bt2_utils._handle_func_status(status)
563
564 def __iadd__(self, iterable):
565 # Python will raise a TypeError if there's anything wrong with
566 # the iterable protocol.
567 for elem in iterable:
568 self.append(elem)
569
570 return self
571
572 def insert(self, value):
573 raise NotImplementedError
574
575
576 class _MapValueKeyIterator(collections.abc.Iterator):
577 def __init__(self, map_obj):
578 self._map_obj = map_obj
579 self._at = 0
580 keys_ptr = native_bt.value_map_get_keys(map_obj._ptr)
581
582 if keys_ptr is None:
583 raise RuntimeError("unexpected error: cannot get map value object keys")
584
585 self._keys = _create_from_ptr(keys_ptr)
586
587 def __next__(self):
588 if self._at == len(self._map_obj):
589 raise StopIteration
590
591 key = self._keys[self._at]
592 self._at += 1
593 return str(key)
594
595
596 class _MapValueConst(_ContainerConst, collections.abc.Mapping, _ValueConst):
597 _NAME = "Const map"
598 _borrow_entry_value_ptr = staticmethod(native_bt.value_map_borrow_entry_value_const)
599
600 def __ne__(self, other):
601 return _Value.__ne__(self, other)
602
603 def __eq__(self, other):
604 if not isinstance(other, collections.abc.Mapping):
605 return False
606
607 if len(self) != len(other):
608 # early mismatch
609 return False
610
611 for self_key in self:
612 if self_key not in other:
613 return False
614
615 if self[self_key] != other[self_key]:
616 return False
617
618 return True
619
620 def __len__(self):
621 size = native_bt.value_map_get_size(self._ptr)
622 assert size >= 0
623 return size
624
625 def __contains__(self, key):
626 self._check_key_type(key)
627 return native_bt.value_map_has_entry(self._ptr, key)
628
629 def _check_key_type(self, key):
630 bt2_utils._check_str(key)
631
632 def _check_key(self, key):
633 if key not in self:
634 raise KeyError(key)
635
636 def __getitem__(self, key):
637 self._check_key(key)
638 ptr = self._borrow_entry_value_ptr(self._ptr, key)
639 assert ptr
640 return self._create_value_from_ptr_and_get_ref(ptr)
641
642 def __iter__(self):
643 return _MapValueKeyIterator(self)
644
645 def __repr__(self):
646 items = ["{}: {}".format(repr(k), repr(v)) for k, v in self.items()]
647 return "{{{}}}".format(", ".join(items))
648
649
650 class MapValue(_MapValueConst, _Container, collections.abc.MutableMapping, _Value):
651 _NAME = "Map"
652 _borrow_entry_value_ptr = staticmethod(native_bt.value_map_borrow_entry_value)
653
654 def __init__(self, value=None):
655 ptr = native_bt.value_map_create()
656 self._check_create_status(ptr)
657 super().__init__(ptr)
658
659 # Python will raise a TypeError if there's anything wrong with
660 # the iterable/mapping protocol.
661 if value is not None:
662 for key, elem in value.items():
663 self[key] = elem
664
665 def __setitem__(self, key, value):
666 self._check_key_type(key)
667 value = create_value(value)
668
669 if value is None:
670 ptr = native_bt.value_null
671 else:
672 ptr = value._ptr
673
674 status = native_bt.value_map_insert_entry(self._ptr, key, ptr)
675 bt2_utils._handle_func_status(status)
676
677
678 _TYPE_TO_OBJ = {
679 native_bt.VALUE_TYPE_BOOL: BoolValue,
680 native_bt.VALUE_TYPE_UNSIGNED_INTEGER: UnsignedIntegerValue,
681 native_bt.VALUE_TYPE_SIGNED_INTEGER: SignedIntegerValue,
682 native_bt.VALUE_TYPE_REAL: RealValue,
683 native_bt.VALUE_TYPE_STRING: StringValue,
684 native_bt.VALUE_TYPE_ARRAY: ArrayValue,
685 native_bt.VALUE_TYPE_MAP: MapValue,
686 }
687
688 _TYPE_TO_CONST_OBJ = {
689 native_bt.VALUE_TYPE_BOOL: _BoolValueConst,
690 native_bt.VALUE_TYPE_UNSIGNED_INTEGER: _UnsignedIntegerValueConst,
691 native_bt.VALUE_TYPE_SIGNED_INTEGER: _SignedIntegerValueConst,
692 native_bt.VALUE_TYPE_REAL: _RealValueConst,
693 native_bt.VALUE_TYPE_STRING: _StringValueConst,
694 native_bt.VALUE_TYPE_ARRAY: _ArrayValueConst,
695 native_bt.VALUE_TYPE_MAP: _MapValueConst,
696 }
This page took 0.04558 seconds and 3 git commands to generate.