Add Babeltrace 2 Python bindings
[babeltrace.git] / bindings / python / bt2 / values.py
1 # The MIT License (MIT)
2 #
3 # Copyright (c) 2016 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 _handle_status(status, obj_name):
33 if status >= 0:
34 return
35
36 if status == native_bt.VALUE_STATUS_FROZEN:
37 raise bt2.FrozenError('{} value object is frozen'.format(obj_name))
38 elif status == native_bt.VALUE_STATUS_INVAL:
39 # In practice, this should never happen, because arguments
40 # should always be validated in this Python module before
41 # calling the native functions.
42 raise ValueError('unexpected invalid argument')
43 else:
44 # In practice, this should never happen, because arguments
45 # should always be validated in this Python module before
46 # calling the native functions.
47 raise RuntimeError('unexpected error')
48
49
50 def _create_from_ptr(ptr):
51 if ptr is None or ptr == native_bt.value_null:
52 return
53
54 typeid = native_bt.value_get_type(ptr)
55 return _TYPE_TO_OBJ[typeid]._create_from_ptr(ptr)
56
57
58 def create_value(value):
59 if value is None:
60 # null value object
61 return
62
63 if isinstance(value, _Value):
64 return value
65
66 if isinstance(value, bool):
67 return BoolValue(value)
68
69 if isinstance(value, int):
70 return IntegerValue(value)
71
72 if isinstance(value, float):
73 return FloatValue(value)
74
75 if isinstance(value, str):
76 return StringValue(value)
77
78 try:
79 return MapValue(value)
80 except:
81 pass
82
83 try:
84 return ArrayValue(value)
85 except:
86 pass
87
88 raise TypeError("cannot create value object from '{}' object".format(value.__class__.__name__))
89
90
91 class _Value(object._Object, object._Freezable, metaclass=abc.ABCMeta):
92 def __init__(self, ptr):
93 super().__init__(ptr)
94
95 def __eq__(self, other):
96 if other is None:
97 # self is never the null value object
98 return False
99
100 # try type-specific comparison first
101 spec_eq = self._spec_eq(other)
102
103 if spec_eq is not None:
104 return spec_eq
105
106 if not isinstance(other, _Value):
107 # not comparing apples to apples
108 return False
109
110 # fall back to native comparison function
111 return native_bt.value_compare(self._ptr, other._ptr)
112
113 def __ne__(self, other):
114 return not (self == other)
115
116 @abc.abstractmethod
117 def _spec_eq(self, other):
118 pass
119
120 def _handle_status(self, status):
121 _handle_status(status, self._NAME)
122
123 def _check_create_status(self, ptr):
124 if ptr is None:
125 raise bt2.CreationError('cannot create {} value object'.format(self._NAME.lower()))
126
127 def _is_frozen(self):
128 return native_bt.value_is_frozen(self._ptr)
129
130 def _freeze(self):
131 status = native_bt.value_freeze(self._ptr)
132 self._handle_status(status)
133
134
135 class _BasicCopy:
136 def __copy__(self):
137 return self.__class__(self.value)
138
139 def __deepcopy__(self, memo):
140 copy = self.__copy__()
141 memo[id(self)] = copy
142 return copy
143
144
145 @functools.total_ordering
146 class _NumericValue(_Value, _BasicCopy):
147 @staticmethod
148 def _extract_value(other):
149 if isinstance(other, _NumericValue):
150 return other.value
151
152 if other is True or other is False:
153 return other
154
155 if isinstance(other, numbers.Integral):
156 return int(other)
157
158 if isinstance(other, numbers.Real):
159 return float(other)
160
161 if isinstance(other, numbers.Complex):
162 return complex(other)
163
164 raise TypeError("'{}' object is not a number object".format(other.__class__.__name__))
165
166 def __int__(self):
167 return int(self.value)
168
169 def __float__(self):
170 return float(self.value)
171
172 def __str__(self):
173 return str(self.value)
174
175 def __lt__(self, other):
176 if not isinstance(other, numbers.Number):
177 raise TypeError('unorderable types: {}() < {}()'.format(self.__class__.__name__,
178 other.__class__.__name__))
179
180 return self.value < float(other)
181
182 def __le__(self, other):
183 if not isinstance(other, numbers.Number):
184 raise TypeError('unorderable types: {}() <= {}()'.format(self.__class__.__name__,
185 other.__class__.__name__))
186
187 return self.value <= float(other)
188
189 def _spec_eq(self, other):
190 return
191
192 def __eq__(self, other):
193 if not isinstance(other, numbers.Number):
194 return False
195
196 return self.value == complex(other)
197
198 def __rmod__(self, other):
199 return self._extract_value(other) % self.value
200
201 def __mod__(self, other):
202 return self.value % self._extract_value(other)
203
204 def __rfloordiv__(self, other):
205 return self._extract_value(other) // self.value
206
207 def __floordiv__(self, other):
208 return self.value // self._extract_value(other)
209
210 def __round__(self, ndigits=None):
211 if ndigits is None:
212 return round(self.value)
213 else:
214 return round(self.value, ndigits)
215
216 def __ceil__(self):
217 return math.ceil(self.value)
218
219 def __floor__(self):
220 return math.floor(self.value)
221
222 def __trunc__(self):
223 return int(self.value)
224
225 def __abs__(self):
226 return abs(self.value)
227
228 def __add__(self, other):
229 return self.value + self._extract_value(other)
230
231 def __radd__(self, other):
232 return self.__add__(other)
233
234 def __neg__(self):
235 return -self.value
236
237 def __pos__(self):
238 return +self.value
239
240 def __mul__(self, other):
241 return self.value * self._extract_value(other)
242
243 def __rmul__(self, other):
244 return self.__mul__(other)
245
246 def __truediv__(self, other):
247 return self.value / self._extract_value(other)
248
249 def __rtruediv__(self, other):
250 return self._extract_value(other) / self.value
251
252 def __pow__(self, exponent):
253 return self.value ** self._extract_value(exponent)
254
255 def __rpow__(self, base):
256 return self._extract_value(base) ** self.value
257
258 def __iadd__(self, other):
259 self.value = self + other
260 return self
261
262 def __isub__(self, other):
263 self.value = self - other
264 return self
265
266 def __imul__(self, other):
267 self.value = self * other
268 return self
269
270 def __itruediv__(self, other):
271 self.value = self / other
272 return self
273
274 def __ifloordiv__(self, other):
275 self.value = self // other
276 return self
277
278 def __imod__(self, other):
279 self.value = self % other
280 return self
281
282 def __ipow__(self, other):
283 self.value = self ** other
284 return self
285
286
287 class _IntegralValue(_NumericValue, numbers.Integral):
288 def __lshift__(self, other):
289 return self.value << self._extract_value(other)
290
291 def __rlshift__(self, other):
292 return self._extract_value(other) << self.value
293
294 def __rshift__(self, other):
295 return self.value >> self._extract_value(other)
296
297 def __rrshift__(self, other):
298 return self._extract_value(other) >> self.value
299
300 def __and__(self, other):
301 return self.value & self._extract_value(other)
302
303 def __rand__(self, other):
304 return self._extract_value(other) & self.value
305
306 def __xor__(self, other):
307 return self.value ^ self._extract_value(other)
308
309 def __rxor__(self, other):
310 return self._extract_value(other) ^ self.value
311
312 def __or__(self, other):
313 return self.value | self._extract_value(other)
314
315 def __ror__(self, other):
316 return self._extract_value(other) | self.value
317
318 def __invert__(self):
319 return ~self.value
320
321 def __ilshift__(self, other):
322 self.value = self << other
323 return self
324
325 def __irshift__(self, other):
326 self.value = self >> other
327 return self
328
329 def __iand__(self, other):
330 self.value = self & other
331 return self
332
333 def __ixor__(self, other):
334 self.value = self ^ other
335 return self
336
337 def __ior__(self, other):
338 self.value = self | other
339 return self
340
341
342 class _RealValue(_NumericValue, numbers.Real):
343 pass
344
345
346 class BoolValue(_Value, _BasicCopy):
347 _NAME = 'Boolean'
348
349 def __init__(self, value=None):
350 if value is None:
351 ptr = native_bt.value_bool_create()
352 else:
353 ptr = native_bt.value_bool_create_init(self._value_to_bool(value))
354
355 self._check_create_status(ptr)
356 super().__init__(ptr)
357
358 def _spec_eq(self, other):
359 if isinstance(other, numbers.Number):
360 return self.value == bool(other)
361
362 def __bool__(self):
363 return self.value
364
365 def __str__(self):
366 return str(self.value)
367
368 def _value_to_bool(self, value):
369 if isinstance(value, BoolValue):
370 value = value.value
371
372 if not isinstance(value, bool):
373 raise TypeError("'{}' object is not a 'bool' or 'BoolValue' object".format(value.__class__))
374
375 return value
376
377 @property
378 def value(self):
379 status, value = native_bt.value_bool_get(self._ptr)
380 self._handle_status(status)
381 return value
382
383 @value.setter
384 def value(self, value):
385 status = native_bt.value_bool_set(self._ptr, self._value_to_bool(value))
386 self._handle_status(status)
387
388
389 class IntegerValue(_IntegralValue):
390 _NAME = 'Integer'
391
392 def __init__(self, value=None):
393 if value is None:
394 ptr = native_bt.value_integer_create()
395 else:
396 ptr = native_bt.value_integer_create_init(self._value_to_int(value))
397
398 self._check_create_status(ptr)
399 super().__init__(ptr)
400
401 def _value_to_int(self, value):
402 if not isinstance(value, numbers.Real):
403 raise TypeError('expecting a number object')
404
405 value = int(value)
406 utils._check_int64(value)
407 return value
408
409 @property
410 def value(self):
411 status, value = native_bt.value_integer_get(self._ptr)
412 self._handle_status(status)
413 return value
414
415 @value.setter
416 def value(self, value):
417 status = native_bt.value_integer_set(self._ptr, self._value_to_int(value))
418 self._handle_status(status)
419
420
421 class FloatValue(_RealValue):
422 _NAME = 'Floating point number'
423
424 def __init__(self, value=None):
425 if value is None:
426 ptr = native_bt.value_float_create()
427 else:
428 value = self._value_to_float(value)
429 ptr = native_bt.value_float_create_init(value)
430
431 self._check_create_status(ptr)
432 super().__init__(ptr)
433
434 def _value_to_float(self, value):
435 if not isinstance(value, numbers.Real):
436 raise TypeError("expecting a real number object")
437
438 return float(value)
439
440 @property
441 def value(self):
442 status, value = native_bt.value_float_get(self._ptr)
443 self._handle_status(status)
444 return value
445
446 @value.setter
447 def value(self, value):
448 value = self._value_to_float(value)
449 status = native_bt.value_float_set(self._ptr, value)
450 self._handle_status(status)
451
452
453 @functools.total_ordering
454 class StringValue(_BasicCopy, collections.abc.Sequence, _Value):
455 _NAME = 'String'
456
457 def __init__(self, value=None):
458 if value is None:
459 ptr = native_bt.value_string_create()
460 else:
461 ptr = native_bt.value_string_create_init(self._value_to_str(value))
462
463 self._check_create_status(ptr)
464 super().__init__(ptr)
465
466 def _value_to_str(self, value):
467 if isinstance(value, self.__class__):
468 value = value.value
469
470 utils._check_str(value)
471 return value
472
473 @property
474 def value(self):
475 status, value = native_bt.value_string_get(self._ptr)
476 self._handle_status(status)
477 return value
478
479 @value.setter
480 def value(self, value):
481 status = native_bt.value_string_set(self._ptr, self._value_to_str(value))
482 self._handle_status(status)
483
484 def _spec_eq(self, other):
485 try:
486 return self.value == self._value_to_str(other)
487 except:
488 return
489
490 def __le__(self, other):
491 return self.value <= self._value_to_str(other)
492
493 def __lt__(self, other):
494 return self.value < self._value_to_str(other)
495
496 def __bool__(self):
497 return bool(self.value)
498
499 def __str__(self):
500 return self.value
501
502 def __getitem__(self, index):
503 return self.value[index]
504
505 def __len__(self):
506 return len(self.value)
507
508 def __iadd__(self, value):
509 curvalue = self.value
510 curvalue += self._value_to_str(value)
511 self.value = curvalue
512 return self
513
514
515 class _Container:
516 def __bool__(self):
517 return len(self) != 0
518
519 def __copy__(self):
520 return self.__class__(self)
521
522 def __deepcopy__(self, memo):
523 ptr = native_bt.value_copy(self._ptr)
524
525 if ptr is None:
526 fmt = 'unexpected error: cannot deep-copy {} value object'
527 raise RuntimeError(fmt.format(self._NAME))
528
529 copy = self.__class__._create_from_ptr(ptr)
530 memo[id(self)] = copy
531 return copy
532
533 def __delitem__(self, index):
534 raise NotImplementedError
535
536
537 class ArrayValue(_Container, collections.abc.MutableSequence, _Value):
538 _NAME = 'Array'
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 _spec_eq(self, other):
552 try:
553 if len(self) != len(other):
554 # early mismatch
555 return False
556
557 for self_elem, other_elem in zip(self, other):
558 if self_elem != other_elem:
559 return False
560
561 return True
562 except:
563 return
564
565 def __len__(self):
566 size = native_bt.value_array_size(self._ptr)
567 self._handle_status(size)
568 return size
569
570 def _check_index(self, index):
571 # TODO: support slices also
572 if not isinstance(index, numbers.Integral):
573 raise TypeError("'{}' object is not an integral number object: invalid index".format(index.__class__.__name__))
574
575 index = int(index)
576
577 if index < 0 or index >= len(self):
578 raise IndexError('array value object index is out of range')
579
580 def __getitem__(self, index):
581 self._check_index(index)
582 ptr = native_bt.value_array_get(self._ptr, index)
583
584 if ptr is None:
585 raise RuntimeError('unexpected error: cannot get array value object element')
586
587 return _create_from_ptr(ptr)
588
589 def __setitem__(self, index, value):
590 self._check_index(index)
591 value = create_value(value)
592
593 if value is None:
594 ptr = native_bt.value_null
595 else:
596 ptr = value._ptr
597
598 status = native_bt.value_array_set(self._ptr, index, ptr)
599 self._handle_status(status)
600
601 def append(self, value):
602 value = create_value(value)
603
604 if value is None:
605 ptr = native_bt.value_null
606 else:
607 ptr = value._ptr
608
609 status = native_bt.value_array_append(self._ptr, ptr)
610 self._handle_status(status)
611
612 def __iadd__(self, iterable):
613 # Python will raise a TypeError if there's anything wrong with
614 # the iterable protocol.
615 for elem in iterable:
616 self.append(elem)
617
618 return self
619
620 def __str__(self):
621 strings = []
622
623 for elem in self:
624 if isinstance(elem, StringValue):
625 strings.append(repr(elem.value))
626 else:
627 strings.append(str(elem))
628
629 return '[{}]'.format(', '.join(strings))
630
631 def insert(self, value):
632 raise NotImplementedError
633
634
635 class _MapValueKeyIterator(collections.abc.Iterator):
636 def __init__(self, map_obj):
637 self._map_obj = map_obj
638 self._at = 0
639 keys_ptr = native_bt.value_map_get_keys_private(map_obj._ptr)
640
641 if keys_ptr is None:
642 raise RuntimeError('unexpected error: cannot get map value object keys')
643
644 self._keys = _create_from_ptr(keys_ptr)
645
646 def __next__(self):
647 if self._at == len(self._map_obj):
648 raise StopIteration
649
650 key = self._keys[self._at]
651 self._at += 1
652 return str(key)
653
654
655 class MapValue(_Container, collections.abc.MutableMapping, _Value):
656 _NAME = 'Map'
657
658 def __init__(self, value=None):
659 ptr = native_bt.value_map_create()
660 self._check_create_status(ptr)
661 super().__init__(ptr)
662
663 # Python will raise a TypeError if there's anything wrong with
664 # the iterable/mapping protocol.
665 if value is not None:
666 for key, elem in value.items():
667 self[key] = elem
668
669 def __eq__(self, other):
670 return _Value.__eq__(self, other)
671
672 def __ne__(self, other):
673 return _Value.__ne__(self, other)
674
675 def _spec_eq(self, other):
676 try:
677 if len(self) != len(other):
678 # early mismatch
679 return False
680
681 for self_key in self:
682 if self_key not in other:
683 return False
684
685 self_value = self[self_key]
686 other_value = other[self_key]
687
688 if self_value != other_value:
689 return False
690
691 return True
692 except:
693 return
694
695 def __len__(self):
696 size = native_bt.value_map_size(self._ptr)
697 self._handle_status(size)
698 return size
699
700 def __contains__(self, key):
701 self._check_key_type(key)
702 return native_bt.value_map_has_key(self._ptr, key)
703
704 def _check_key_type(self, key):
705 utils._check_str(key)
706
707 def _check_key(self, key):
708 if key not in self:
709 raise KeyError(key)
710
711 def __getitem__(self, key):
712 self._check_key(key)
713 ptr = native_bt.value_map_get(self._ptr, key)
714
715 if ptr is None:
716 raise RuntimeError('unexpected error: cannot get map value object element')
717
718 return _create_from_ptr(ptr)
719
720 def __iter__(self):
721 return _MapValueKeyIterator(self)
722
723 def __setitem__(self, key, value):
724 self._check_key_type(key)
725 value = create_value(value)
726
727 if value is None:
728 ptr = native_bt.value_null
729 else:
730 ptr = value._ptr
731
732 status = native_bt.value_map_insert(self._ptr, key, ptr)
733 self._handle_status(status)
734
735 def __str__(self):
736 strings = []
737
738 for key, elem in self.items():
739 if isinstance(elem, StringValue):
740 value = repr(elem.value)
741 else:
742 value = str(elem)
743
744 strings.append('{}: {}'.format(repr(key), value))
745
746 return '{{{}}}'.format(', '.join(strings))
747
748
749 _TYPE_TO_OBJ = {
750 native_bt.VALUE_TYPE_BOOL: BoolValue,
751 native_bt.VALUE_TYPE_INTEGER: IntegerValue,
752 native_bt.VALUE_TYPE_FLOAT: FloatValue,
753 native_bt.VALUE_TYPE_STRING: StringValue,
754 native_bt.VALUE_TYPE_ARRAY: ArrayValue,
755 native_bt.VALUE_TYPE_MAP: MapValue,
756 }
This page took 0.045414 seconds and 4 git commands to generate.