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