bt2: value.py: refactor value comparison
[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(_Value):
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 __eq__(self, other):
301 try:
302 return self._value == self._value_to_bool(other)
303 except:
304 return False
305
306 def __bool__(self):
307 return self._value
308
309 def __repr__(self):
310 return repr(self._value)
311
312 def _value_to_bool(self, value):
313 if isinstance(value, BoolValue):
314 value = value._value
315
316 if not isinstance(value, bool):
317 raise TypeError("'{}' object is not a 'bool' or 'BoolValue' object".format(value.__class__))
318
319 return value
320
321 @property
322 def _value(self):
323 value = native_bt.value_bool_get(self._ptr)
324 return value != 0
325
326 def _set_value(self, value):
327 native_bt.value_bool_set(self._ptr, self._value_to_bool(value))
328
329 value = property(fset=_set_value)
330
331
332 class _IntegerValue(_IntegralValue):
333 def __init__(self, value=None):
334 if value is None:
335 ptr = self._create_default_value()
336 else:
337 ptr = self._create_value(self._value_to_int(value))
338
339 self._check_create_status(ptr)
340 super().__init__(ptr)
341
342 def _value_to_int(self, value):
343 if not isinstance(value, numbers.Real):
344 raise TypeError('expecting a number object')
345
346 value = int(value)
347 self._check_int_range(value)
348 return value
349
350 @property
351 def _value(self):
352 return self._get_value(self._ptr)
353
354 def _prop_set_value(self, value):
355 self._set_value(self._ptr, self._value_to_int(value))
356
357 value = property(fset=_prop_set_value)
358
359
360 class UnsignedIntegerValue(_IntegerValue):
361 _check_int_range = staticmethod(utils._check_uint64)
362 _create_default_value = staticmethod(native_bt.value_unsigned_integer_create)
363 _create_value = staticmethod(native_bt.value_unsigned_integer_create_init)
364 _set_value = staticmethod(native_bt.value_unsigned_integer_set)
365 _get_value = staticmethod(native_bt.value_unsigned_integer_get)
366
367
368 class SignedIntegerValue(_IntegerValue):
369 _check_int_range = staticmethod(utils._check_int64)
370 _create_default_value = staticmethod(native_bt.value_signed_integer_create)
371 _create_value = staticmethod(native_bt.value_signed_integer_create_init)
372 _set_value = staticmethod(native_bt.value_signed_integer_set)
373 _get_value = staticmethod(native_bt.value_signed_integer_get)
374
375
376 class RealValue(_RealValue):
377 _NAME = 'Real number'
378
379 def __init__(self, value=None):
380 if value is None:
381 ptr = native_bt.value_real_create()
382 else:
383 value = self._value_to_float(value)
384 ptr = native_bt.value_real_create_init(value)
385
386 self._check_create_status(ptr)
387 super().__init__(ptr)
388
389 def _value_to_float(self, value):
390 if not isinstance(value, numbers.Real):
391 raise TypeError("expecting a real number object")
392
393 return float(value)
394
395 @property
396 def _value(self):
397 return native_bt.value_real_get(self._ptr)
398
399 def _set_value(self, value):
400 native_bt.value_real_set(self._ptr, self._value_to_float(value))
401
402 value = property(fset=_set_value)
403
404
405 @functools.total_ordering
406 class StringValue(collections.abc.Sequence, _Value):
407 _NAME = 'String'
408
409 def __init__(self, value=None):
410 if value is None:
411 ptr = native_bt.value_string_create()
412 else:
413 ptr = native_bt.value_string_create_init(self._value_to_str(value))
414
415 self._check_create_status(ptr)
416 super().__init__(ptr)
417
418 def _value_to_str(self, value):
419 if isinstance(value, self.__class__):
420 value = value._value
421
422 utils._check_str(value)
423 return value
424
425 @property
426 def _value(self):
427 return native_bt.value_string_get(self._ptr)
428
429 def _set_value(self, value):
430 status = native_bt.value_string_set(self._ptr, self._value_to_str(value))
431 self._handle_status(status)
432
433 value = property(fset=_set_value)
434
435 def __eq__(self, other):
436 try:
437 return self._value == self._value_to_str(other)
438 except:
439 return False
440
441 def __lt__(self, other):
442 return self._value < self._value_to_str(other)
443
444 def __bool__(self):
445 return bool(self._value)
446
447 def __repr__(self):
448 return repr(self._value)
449
450 def __str__(self):
451 return self._value
452
453 def __getitem__(self, index):
454 return self._value[index]
455
456 def __len__(self):
457 return len(self._value)
458
459 def __iadd__(self, value):
460 curvalue = self._value
461 curvalue += self._value_to_str(value)
462 self.value = curvalue
463 return self
464
465
466 class _Container:
467 def __bool__(self):
468 return len(self) != 0
469
470 def __delitem__(self, index):
471 raise NotImplementedError
472
473
474 class ArrayValue(_Container, collections.abc.MutableSequence, _Value):
475 _NAME = 'Array'
476
477 def __init__(self, value=None):
478 ptr = native_bt.value_array_create()
479 self._check_create_status(ptr)
480 super().__init__(ptr)
481
482 # Python will raise a TypeError if there's anything wrong with
483 # the iterable protocol.
484 if value is not None:
485 for elem in value:
486 self.append(elem)
487
488 def __eq__(self, other):
489 if not isinstance(other, collections.abc.Sequence):
490 return False
491
492 if len(self) != len(other):
493 # early mismatch
494 return False
495
496 for self_elem, other_elem in zip(self, other):
497 if self_elem != other_elem:
498 return False
499
500 return True
501
502 def __len__(self):
503 size = native_bt.value_array_get_size(self._ptr)
504 assert(size >= 0)
505 return size
506
507 def _check_index(self, index):
508 # TODO: support slices also
509 if not isinstance(index, numbers.Integral):
510 raise TypeError("'{}' object is not an integral number object: invalid index".format(index.__class__.__name__))
511
512 index = int(index)
513
514 if index < 0 or index >= len(self):
515 raise IndexError('array value object index is out of range')
516
517 def __getitem__(self, index):
518 self._check_index(index)
519 ptr = native_bt.value_array_borrow_element_by_index(self._ptr, index)
520 assert(ptr)
521 return _create_from_ptr_and_get_ref(ptr)
522
523 def __setitem__(self, index, value):
524 self._check_index(index)
525 value = create_value(value)
526
527 if value is None:
528 ptr = native_bt.value_null
529 else:
530 ptr = value._ptr
531
532 status = native_bt.value_array_set_element_by_index(
533 self._ptr, index, ptr)
534 self._handle_status(status)
535
536 def append(self, value):
537 value = create_value(value)
538
539 if value is None:
540 ptr = native_bt.value_null
541 else:
542 ptr = value._ptr
543
544 status = native_bt.value_array_append_element(self._ptr, ptr)
545 self._handle_status(status)
546
547 def __iadd__(self, iterable):
548 # Python will raise a TypeError if there's anything wrong with
549 # the iterable protocol.
550 for elem in iterable:
551 self.append(elem)
552
553 return self
554
555 def __repr__(self):
556 return '[{}]'.format(', '.join([repr(v) for v in self]))
557
558 def insert(self, value):
559 raise NotImplementedError
560
561
562 class _MapValueKeyIterator(collections.abc.Iterator):
563 def __init__(self, map_obj):
564 self._map_obj = map_obj
565 self._at = 0
566 keys_ptr = native_bt.value_map_get_keys(map_obj._ptr)
567
568 if keys_ptr is None:
569 raise RuntimeError('unexpected error: cannot get map value object keys')
570
571 self._keys = _create_from_ptr(keys_ptr)
572
573 def __next__(self):
574 if self._at == len(self._map_obj):
575 raise StopIteration
576
577 key = self._keys[self._at]
578 self._at += 1
579 return str(key)
580
581
582 class MapValue(_Container, collections.abc.MutableMapping, _Value):
583 _NAME = 'Map'
584
585 def __init__(self, value=None):
586 ptr = native_bt.value_map_create()
587 self._check_create_status(ptr)
588 super().__init__(ptr)
589
590 # Python will raise a TypeError if there's anything wrong with
591 # the iterable/mapping protocol.
592 if value is not None:
593 for key, elem in value.items():
594 self[key] = elem
595
596 def __ne__(self, other):
597 return _Value.__ne__(self, other)
598
599 def __eq__(self, other):
600 if not isinstance(other, collections.abc.Mapping):
601 return False
602
603 if len(self) != len(other):
604 # early mismatch
605 return False
606
607 for self_key in self:
608 if self_key not in other:
609 return False
610
611 if self[self_key] != other[self_key]:
612 return False
613
614 return True
615
616 def __len__(self):
617 size = native_bt.value_map_get_size(self._ptr)
618 assert(size >= 0)
619 return size
620
621 def __contains__(self, key):
622 self._check_key_type(key)
623 return native_bt.value_map_has_entry(self._ptr, key)
624
625 def _check_key_type(self, key):
626 utils._check_str(key)
627
628 def _check_key(self, key):
629 if key not in self:
630 raise KeyError(key)
631
632 def __getitem__(self, key):
633 self._check_key(key)
634 ptr = native_bt.value_map_borrow_entry_value(self._ptr, key)
635 assert(ptr)
636 return _create_from_ptr_and_get_ref(ptr)
637
638 def __iter__(self):
639 return _MapValueKeyIterator(self)
640
641 def __setitem__(self, key, value):
642 self._check_key_type(key)
643 value = create_value(value)
644
645 if value is None:
646 ptr = native_bt.value_null
647 else:
648 ptr = value._ptr
649
650 status = native_bt.value_map_insert_entry(self._ptr, key, ptr)
651 self._handle_status(status)
652
653 def __repr__(self):
654 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
655 return '{{{}}}'.format(', '.join(items))
656
657
658 _TYPE_TO_OBJ = {
659 native_bt.VALUE_TYPE_BOOL: BoolValue,
660 native_bt.VALUE_TYPE_UNSIGNED_INTEGER: UnsignedIntegerValue,
661 native_bt.VALUE_TYPE_SIGNED_INTEGER: SignedIntegerValue,
662 native_bt.VALUE_TYPE_REAL: RealValue,
663 native_bt.VALUE_TYPE_STRING: StringValue,
664 native_bt.VALUE_TYPE_ARRAY: ArrayValue,
665 native_bt.VALUE_TYPE_MAP: MapValue,
666 }
This page took 0.043016 seconds and 5 git commands to generate.