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