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