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