bt2: update value.py, make test_value pass
[babeltrace.git] / bindings / python / bt2 / bt2 / value.py
CommitLineData
81447b5b
PP
1# The MIT License (MIT)
2#
f6a5e476 3# Copyright (c) 2017 Philippe Proulx <pproulx@efficios.com>
81447b5b
PP
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
23from bt2 import native_bt, object, utils
24import collections.abc
25import functools
26import numbers
27import math
28import abc
29import bt2
30
31
32def _handle_status(status, obj_name):
33 if status >= 0:
34 return
81447b5b 35 else:
81447b5b
PP
36 raise RuntimeError('unexpected error')
37
38
39def _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
77b70d39
SM
47def _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
81447b5b
PP
55def 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 IntegerValue(value)
68
69 if isinstance(value, float):
77b70d39 70 return RealValue(value)
81447b5b
PP
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
c3044a97 88class _Value(object._SharedObject, metaclass=abc.ABCMeta):
77b70d39
SM
89 _get_ref = native_bt.value_get_ref
90 _put_ref = native_bt.value_put_ref
91
81447b5b
PP
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:
77b70d39
SM
122 raise bt2.CreationError(
123 'cannot create {} value object'.format(self._NAME.lower()))
81447b5b
PP
124
125
126@functools.total_ordering
77b70d39 127class _NumericValue(_Value):
81447b5b
PP
128 @staticmethod
129 def _extract_value(other):
130 if isinstance(other, _NumericValue):
72bd7054 131 return other._value
81447b5b
PP
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):
72bd7054 148 return int(self._value)
81447b5b
PP
149
150 def __float__(self):
72bd7054 151 return float(self._value)
81447b5b 152
2ef5b04b
JG
153 def __repr__(self):
154 return repr(self._value)
81447b5b
PP
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
72bd7054 161 return self._value < float(other)
81447b5b
PP
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
72bd7054 168 return self._value <= float(other)
81447b5b
PP
169
170 def _spec_eq(self, other):
f6a5e476 171 pass
81447b5b
PP
172
173 def __eq__(self, other):
174 if not isinstance(other, numbers.Number):
175 return False
176
72bd7054 177 return self._value == complex(other)
81447b5b
PP
178
179 def __rmod__(self, other):
72bd7054 180 return self._extract_value(other) % self._value
81447b5b
PP
181
182 def __mod__(self, other):
72bd7054 183 return self._value % self._extract_value(other)
81447b5b
PP
184
185 def __rfloordiv__(self, other):
72bd7054 186 return self._extract_value(other) // self._value
81447b5b
PP
187
188 def __floordiv__(self, other):
72bd7054 189 return self._value // self._extract_value(other)
81447b5b
PP
190
191 def __round__(self, ndigits=None):
192 if ndigits is None:
72bd7054 193 return round(self._value)
81447b5b 194 else:
72bd7054 195 return round(self._value, ndigits)
81447b5b
PP
196
197 def __ceil__(self):
72bd7054 198 return math.ceil(self._value)
81447b5b
PP
199
200 def __floor__(self):
72bd7054 201 return math.floor(self._value)
81447b5b
PP
202
203 def __trunc__(self):
72bd7054 204 return int(self._value)
81447b5b
PP
205
206 def __abs__(self):
72bd7054 207 return abs(self._value)
81447b5b
PP
208
209 def __add__(self, other):
72bd7054 210 return self._value + self._extract_value(other)
81447b5b
PP
211
212 def __radd__(self, other):
213 return self.__add__(other)
214
215 def __neg__(self):
72bd7054 216 return -self._value
81447b5b
PP
217
218 def __pos__(self):
72bd7054 219 return +self._value
81447b5b
PP
220
221 def __mul__(self, other):
72bd7054 222 return self._value * self._extract_value(other)
81447b5b
PP
223
224 def __rmul__(self, other):
225 return self.__mul__(other)
226
227 def __truediv__(self, other):
72bd7054 228 return self._value / self._extract_value(other)
81447b5b
PP
229
230 def __rtruediv__(self, other):
72bd7054 231 return self._extract_value(other) / self._value
81447b5b
PP
232
233 def __pow__(self, exponent):
72bd7054 234 return self._value ** self._extract_value(exponent)
81447b5b
PP
235
236 def __rpow__(self, base):
72bd7054 237 return self._extract_value(base) ** self._value
81447b5b
PP
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
268class _IntegralValue(_NumericValue, numbers.Integral):
269 def __lshift__(self, other):
72bd7054 270 return self._value << self._extract_value(other)
81447b5b
PP
271
272 def __rlshift__(self, other):
72bd7054 273 return self._extract_value(other) << self._value
81447b5b
PP
274
275 def __rshift__(self, other):
72bd7054 276 return self._value >> self._extract_value(other)
81447b5b
PP
277
278 def __rrshift__(self, other):
72bd7054 279 return self._extract_value(other) >> self._value
81447b5b
PP
280
281 def __and__(self, other):
72bd7054 282 return self._value & self._extract_value(other)
81447b5b
PP
283
284 def __rand__(self, other):
72bd7054 285 return self._extract_value(other) & self._value
81447b5b
PP
286
287 def __xor__(self, other):
72bd7054 288 return self._value ^ self._extract_value(other)
81447b5b
PP
289
290 def __rxor__(self, other):
72bd7054 291 return self._extract_value(other) ^ self._value
81447b5b
PP
292
293 def __or__(self, other):
72bd7054 294 return self._value | self._extract_value(other)
81447b5b
PP
295
296 def __ror__(self, other):
72bd7054 297 return self._extract_value(other) | self._value
81447b5b
PP
298
299 def __invert__(self):
72bd7054 300 return ~self._value
81447b5b
PP
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
323class _RealValue(_NumericValue, numbers.Real):
324 pass
325
326
77b70d39 327class BoolValue(_Value):
81447b5b
PP
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):
72bd7054 341 return self._value == bool(other)
81447b5b
PP
342
343 def __bool__(self):
72bd7054 344 return self._value
81447b5b 345
2ef5b04b
JG
346 def __repr__(self):
347 return repr(self._value)
81447b5b
PP
348
349 def _value_to_bool(self, value):
350 if isinstance(value, BoolValue):
72bd7054 351 value = value._value
81447b5b
PP
352
353 if not isinstance(value, bool):
354 raise TypeError("'{}' object is not a 'bool' or 'BoolValue' object".format(value.__class__))
355
f6a5e476 356 return int(value)
81447b5b
PP
357
358 @property
72bd7054 359 def _value(self):
77b70d39
SM
360 value = native_bt.value_bool_get(self._ptr)
361 return value != 0
81447b5b 362
72bd7054 363 def _set_value(self, value):
77b70d39 364 native_bt.value_bool_set(self._ptr, self._value_to_bool(value))
81447b5b 365
72bd7054
PP
366 value = property(fset=_set_value)
367
81447b5b
PP
368
369class IntegerValue(_IntegralValue):
370 _NAME = 'Integer'
371
372 def __init__(self, value=None):
373 if value is None:
374 ptr = native_bt.value_integer_create()
375 else:
376 ptr = native_bt.value_integer_create_init(self._value_to_int(value))
377
378 self._check_create_status(ptr)
379 super().__init__(ptr)
380
381 def _value_to_int(self, value):
382 if not isinstance(value, numbers.Real):
383 raise TypeError('expecting a number object')
384
385 value = int(value)
386 utils._check_int64(value)
387 return value
388
389 @property
72bd7054 390 def _value(self):
77b70d39 391 return native_bt.value_integer_get(self._ptr)
81447b5b 392
72bd7054 393 def _set_value(self, value):
77b70d39 394 native_bt.value_integer_set(self._ptr, self._value_to_int(value))
81447b5b 395
72bd7054
PP
396 value = property(fset=_set_value)
397
81447b5b 398
77b70d39
SM
399class RealValue(_RealValue):
400 _NAME = 'Real number'
81447b5b
PP
401
402 def __init__(self, value=None):
403 if value is None:
77b70d39 404 ptr = native_bt.value_real_create()
81447b5b
PP
405 else:
406 value = self._value_to_float(value)
77b70d39 407 ptr = native_bt.value_real_create_init(value)
81447b5b
PP
408
409 self._check_create_status(ptr)
410 super().__init__(ptr)
411
412 def _value_to_float(self, value):
413 if not isinstance(value, numbers.Real):
414 raise TypeError("expecting a real number object")
415
416 return float(value)
417
418 @property
72bd7054 419 def _value(self):
77b70d39 420 return native_bt.value_real_get(self._ptr)
81447b5b 421
72bd7054 422 def _set_value(self, value):
77b70d39 423 native_bt.value_real_set(self._ptr, self._value_to_float(value))
81447b5b 424
72bd7054
PP
425 value = property(fset=_set_value)
426
81447b5b
PP
427
428@functools.total_ordering
77b70d39 429class StringValue(collections.abc.Sequence, _Value):
81447b5b
PP
430 _NAME = 'String'
431
432 def __init__(self, value=None):
433 if value is None:
434 ptr = native_bt.value_string_create()
435 else:
436 ptr = native_bt.value_string_create_init(self._value_to_str(value))
437
438 self._check_create_status(ptr)
439 super().__init__(ptr)
440
441 def _value_to_str(self, value):
442 if isinstance(value, self.__class__):
72bd7054 443 value = value._value
81447b5b
PP
444
445 utils._check_str(value)
446 return value
447
448 @property
72bd7054 449 def _value(self):
77b70d39 450 return native_bt.value_string_get(self._ptr)
81447b5b 451
72bd7054 452 def _set_value(self, value):
81447b5b
PP
453 status = native_bt.value_string_set(self._ptr, self._value_to_str(value))
454 self._handle_status(status)
455
72bd7054
PP
456 value = property(fset=_set_value)
457
81447b5b
PP
458 def _spec_eq(self, other):
459 try:
72bd7054 460 return self._value == self._value_to_str(other)
81447b5b
PP
461 except:
462 return
463
464 def __le__(self, other):
72bd7054 465 return self._value <= self._value_to_str(other)
81447b5b
PP
466
467 def __lt__(self, other):
72bd7054 468 return self._value < self._value_to_str(other)
81447b5b
PP
469
470 def __bool__(self):
72bd7054 471 return bool(self._value)
81447b5b 472
2ef5b04b 473 def __repr__(self):
77b70d39 474 return repr(self._value)
2ef5b04b 475
81447b5b 476 def __str__(self):
72bd7054 477 return self._value
81447b5b
PP
478
479 def __getitem__(self, index):
72bd7054 480 return self._value[index]
81447b5b
PP
481
482 def __len__(self):
72bd7054 483 return len(self._value)
81447b5b
PP
484
485 def __iadd__(self, value):
72bd7054 486 curvalue = self._value
81447b5b
PP
487 curvalue += self._value_to_str(value)
488 self.value = curvalue
489 return self
490
491
492class _Container:
493 def __bool__(self):
494 return len(self) != 0
495
81447b5b
PP
496 def __delitem__(self, index):
497 raise NotImplementedError
498
499
500class ArrayValue(_Container, collections.abc.MutableSequence, _Value):
501 _NAME = 'Array'
502
503 def __init__(self, value=None):
504 ptr = native_bt.value_array_create()
505 self._check_create_status(ptr)
506 super().__init__(ptr)
507
508 # Python will raise a TypeError if there's anything wrong with
509 # the iterable protocol.
510 if value is not None:
511 for elem in value:
512 self.append(elem)
513
514 def _spec_eq(self, other):
515 try:
516 if len(self) != len(other):
517 # early mismatch
518 return False
519
520 for self_elem, other_elem in zip(self, other):
521 if self_elem != other_elem:
522 return False
523
524 return True
525 except:
526 return
527
528 def __len__(self):
77b70d39 529 size = native_bt.value_array_get_size(self._ptr)
f6a5e476 530 assert(size >= 0)
81447b5b
PP
531 return size
532
533 def _check_index(self, index):
534 # TODO: support slices also
535 if not isinstance(index, numbers.Integral):
536 raise TypeError("'{}' object is not an integral number object: invalid index".format(index.__class__.__name__))
537
538 index = int(index)
539
540 if index < 0 or index >= len(self):
541 raise IndexError('array value object index is out of range')
542
543 def __getitem__(self, index):
544 self._check_index(index)
77b70d39 545 ptr = native_bt.value_array_borrow_element_by_index(self._ptr, index)
f6a5e476 546 assert(ptr)
77b70d39 547 return _create_from_ptr_and_get_ref(ptr)
81447b5b
PP
548
549 def __setitem__(self, index, value):
550 self._check_index(index)
551 value = create_value(value)
552
553 if value is None:
554 ptr = native_bt.value_null
555 else:
556 ptr = value._ptr
557
77b70d39
SM
558 status = native_bt.value_array_set_element_by_index(
559 self._ptr, index, ptr)
81447b5b
PP
560 self._handle_status(status)
561
562 def append(self, value):
563 value = create_value(value)
564
565 if value is None:
566 ptr = native_bt.value_null
567 else:
568 ptr = value._ptr
569
77b70d39 570 status = native_bt.value_array_append_element(self._ptr, ptr)
81447b5b
PP
571 self._handle_status(status)
572
573 def __iadd__(self, iterable):
574 # Python will raise a TypeError if there's anything wrong with
575 # the iterable protocol.
576 for elem in iterable:
577 self.append(elem)
578
579 return self
580
2ef5b04b
JG
581 def __repr__(self):
582 return '[{}]'.format(', '.join([repr(v) for v in self]))
81447b5b
PP
583
584 def insert(self, value):
585 raise NotImplementedError
586
587
588class _MapValueKeyIterator(collections.abc.Iterator):
589 def __init__(self, map_obj):
590 self._map_obj = map_obj
591 self._at = 0
77b70d39 592 keys_ptr = native_bt.value_map_get_keys(map_obj._ptr)
81447b5b
PP
593
594 if keys_ptr is None:
595 raise RuntimeError('unexpected error: cannot get map value object keys')
596
597 self._keys = _create_from_ptr(keys_ptr)
598
599 def __next__(self):
600 if self._at == len(self._map_obj):
601 raise StopIteration
602
603 key = self._keys[self._at]
604 self._at += 1
605 return str(key)
606
607
608class MapValue(_Container, collections.abc.MutableMapping, _Value):
609 _NAME = 'Map'
610
611 def __init__(self, value=None):
612 ptr = native_bt.value_map_create()
613 self._check_create_status(ptr)
614 super().__init__(ptr)
615
616 # Python will raise a TypeError if there's anything wrong with
617 # the iterable/mapping protocol.
618 if value is not None:
619 for key, elem in value.items():
620 self[key] = elem
621
622 def __eq__(self, other):
623 return _Value.__eq__(self, other)
624
625 def __ne__(self, other):
626 return _Value.__ne__(self, other)
627
628 def _spec_eq(self, other):
629 try:
630 if len(self) != len(other):
631 # early mismatch
632 return False
633
634 for self_key in self:
635 if self_key not in other:
636 return False
637
638 self_value = self[self_key]
639 other_value = other[self_key]
640
641 if self_value != other_value:
642 return False
643
644 return True
645 except:
646 return
647
648 def __len__(self):
77b70d39 649 size = native_bt.value_map_get_size(self._ptr)
f6a5e476 650 assert(size >= 0)
81447b5b
PP
651 return size
652
653 def __contains__(self, key):
654 self._check_key_type(key)
77b70d39 655 return native_bt.value_map_has_entry(self._ptr, key)
81447b5b
PP
656
657 def _check_key_type(self, key):
658 utils._check_str(key)
659
660 def _check_key(self, key):
661 if key not in self:
662 raise KeyError(key)
663
664 def __getitem__(self, key):
665 self._check_key(key)
77b70d39 666 ptr = native_bt.value_map_borrow_entry_value(self._ptr, key)
f6a5e476 667 assert(ptr)
77b70d39 668 return _create_from_ptr_and_get_ref(ptr)
81447b5b
PP
669
670 def __iter__(self):
671 return _MapValueKeyIterator(self)
672
673 def __setitem__(self, key, value):
674 self._check_key_type(key)
675 value = create_value(value)
676
677 if value is None:
678 ptr = native_bt.value_null
679 else:
680 ptr = value._ptr
681
77b70d39 682 status = native_bt.value_map_insert_entry(self._ptr, key, ptr)
81447b5b
PP
683 self._handle_status(status)
684
2ef5b04b
JG
685 def __repr__(self):
686 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
687 return '{{{}}}'.format(', '.join(items))
81447b5b
PP
688
689
690_TYPE_TO_OBJ = {
691 native_bt.VALUE_TYPE_BOOL: BoolValue,
692 native_bt.VALUE_TYPE_INTEGER: IntegerValue,
77b70d39 693 native_bt.VALUE_TYPE_REAL: RealValue,
81447b5b
PP
694 native_bt.VALUE_TYPE_STRING: StringValue,
695 native_bt.VALUE_TYPE_ARRAY: ArrayValue,
696 native_bt.VALUE_TYPE_MAP: MapValue,
697}
This page took 0.064967 seconds and 4 git commands to generate.