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