bt2: field.py: refactor field comparison
[babeltrace.git] / src / bindings / python / bt2 / bt2 / value.py
CommitLineData
81447b5b
PP
1# The MIT License (MIT)
2#
811644b8 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
10a19b49
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):
fdd3a2da 67 return SignedIntegerValue(value)
81447b5b
PP
68
69 if isinstance(value, float):
10a19b49 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
78288f58 88class _Value(object._SharedObject, metaclass=abc.ABCMeta):
2f16a6a2
PP
89 _get_ref = staticmethod(native_bt.value_get_ref)
90 _put_ref = staticmethod(native_bt.value_put_ref)
10a19b49 91
81447b5b
PP
92 def __ne__(self, other):
93 return not (self == other)
94
81447b5b
PP
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:
10a19b49
SM
100 raise bt2.CreationError(
101 'cannot create {} value object'.format(self._NAME.lower()))
81447b5b
PP
102
103
104@functools.total_ordering
10a19b49 105class _NumericValue(_Value):
81447b5b
PP
106 @staticmethod
107 def _extract_value(other):
b00a769c
PP
108 if isinstance(other, BoolValue) or isinstance(other, bool):
109 return bool(other)
81447b5b
PP
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):
9b6cd4a7 123 return int(self._value)
81447b5b
PP
124
125 def __float__(self):
9b6cd4a7 126 return float(self._value)
81447b5b 127
83656269
JG
128 def __repr__(self):
129 return repr(self._value)
81447b5b
PP
130
131 def __lt__(self, other):
09a926c1 132 return self._value < self._extract_value(other)
81447b5b 133
81447b5b 134 def __eq__(self, other):
b00a769c
PP
135 try:
136 return self._value == self._extract_value(other)
137 except:
81447b5b
PP
138 return False
139
81447b5b 140 def __rmod__(self, other):
9b6cd4a7 141 return self._extract_value(other) % self._value
81447b5b
PP
142
143 def __mod__(self, other):
9b6cd4a7 144 return self._value % self._extract_value(other)
81447b5b
PP
145
146 def __rfloordiv__(self, other):
9b6cd4a7 147 return self._extract_value(other) // self._value
81447b5b
PP
148
149 def __floordiv__(self, other):
9b6cd4a7 150 return self._value // self._extract_value(other)
81447b5b
PP
151
152 def __round__(self, ndigits=None):
153 if ndigits is None:
9b6cd4a7 154 return round(self._value)
81447b5b 155 else:
9b6cd4a7 156 return round(self._value, ndigits)
81447b5b
PP
157
158 def __ceil__(self):
9b6cd4a7 159 return math.ceil(self._value)
81447b5b
PP
160
161 def __floor__(self):
9b6cd4a7 162 return math.floor(self._value)
81447b5b
PP
163
164 def __trunc__(self):
9b6cd4a7 165 return int(self._value)
81447b5b
PP
166
167 def __abs__(self):
9b6cd4a7 168 return abs(self._value)
81447b5b
PP
169
170 def __add__(self, other):
9b6cd4a7 171 return self._value + self._extract_value(other)
81447b5b
PP
172
173 def __radd__(self, other):
174 return self.__add__(other)
175
176 def __neg__(self):
9b6cd4a7 177 return -self._value
81447b5b
PP
178
179 def __pos__(self):
9b6cd4a7 180 return +self._value
81447b5b
PP
181
182 def __mul__(self, other):
9b6cd4a7 183 return self._value * self._extract_value(other)
81447b5b
PP
184
185 def __rmul__(self, other):
186 return self.__mul__(other)
187
188 def __truediv__(self, other):
9b6cd4a7 189 return self._value / self._extract_value(other)
81447b5b
PP
190
191 def __rtruediv__(self, other):
9b6cd4a7 192 return self._extract_value(other) / self._value
81447b5b
PP
193
194 def __pow__(self, exponent):
9b6cd4a7 195 return self._value ** self._extract_value(exponent)
81447b5b
PP
196
197 def __rpow__(self, base):
9b6cd4a7 198 return self._extract_value(base) ** self._value
81447b5b
PP
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
229class _IntegralValue(_NumericValue, numbers.Integral):
230 def __lshift__(self, other):
9b6cd4a7 231 return self._value << self._extract_value(other)
81447b5b
PP
232
233 def __rlshift__(self, other):
9b6cd4a7 234 return self._extract_value(other) << self._value
81447b5b
PP
235
236 def __rshift__(self, other):
9b6cd4a7 237 return self._value >> self._extract_value(other)
81447b5b
PP
238
239 def __rrshift__(self, other):
9b6cd4a7 240 return self._extract_value(other) >> self._value
81447b5b
PP
241
242 def __and__(self, other):
9b6cd4a7 243 return self._value & self._extract_value(other)
81447b5b
PP
244
245 def __rand__(self, other):
9b6cd4a7 246 return self._extract_value(other) & self._value
81447b5b
PP
247
248 def __xor__(self, other):
9b6cd4a7 249 return self._value ^ self._extract_value(other)
81447b5b
PP
250
251 def __rxor__(self, other):
9b6cd4a7 252 return self._extract_value(other) ^ self._value
81447b5b
PP
253
254 def __or__(self, other):
9b6cd4a7 255 return self._value | self._extract_value(other)
81447b5b
PP
256
257 def __ror__(self, other):
9b6cd4a7 258 return self._extract_value(other) | self._value
81447b5b
PP
259
260 def __invert__(self):
9b6cd4a7 261 return ~self._value
81447b5b
PP
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
284class _RealValue(_NumericValue, numbers.Real):
285 pass
286
287
10a19b49 288class BoolValue(_Value):
81447b5b
PP
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
b00a769c
PP
300 def __eq__(self, other):
301 try:
302 return self._value == self._value_to_bool(other)
303 except:
304 return False
81447b5b
PP
305
306 def __bool__(self):
9b6cd4a7 307 return self._value
81447b5b 308
83656269
JG
309 def __repr__(self):
310 return repr(self._value)
81447b5b
PP
311
312 def _value_to_bool(self, value):
313 if isinstance(value, BoolValue):
9b6cd4a7 314 value = value._value
81447b5b
PP
315
316 if not isinstance(value, bool):
317 raise TypeError("'{}' object is not a 'bool' or 'BoolValue' object".format(value.__class__))
318
b00a769c 319 return value
81447b5b
PP
320
321 @property
9b6cd4a7 322 def _value(self):
10a19b49
SM
323 value = native_bt.value_bool_get(self._ptr)
324 return value != 0
81447b5b 325
9b6cd4a7 326 def _set_value(self, value):
10a19b49 327 native_bt.value_bool_set(self._ptr, self._value_to_bool(value))
81447b5b 328
9b6cd4a7
PP
329 value = property(fset=_set_value)
330
81447b5b 331
fdd3a2da 332class _IntegerValue(_IntegralValue):
81447b5b
PP
333 def __init__(self, value=None):
334 if value is None:
fdd3a2da 335 ptr = self._create_default_value()
81447b5b 336 else:
fdd3a2da 337 ptr = self._create_value(self._value_to_int(value))
81447b5b
PP
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)
fdd3a2da 347 self._check_int_range(value)
81447b5b
PP
348 return value
349
350 @property
9b6cd4a7 351 def _value(self):
fdd3a2da 352 return self._get_value(self._ptr)
81447b5b 353
fdd3a2da
PP
354 def _prop_set_value(self, value):
355 self._set_value(self._ptr, self._value_to_int(value))
81447b5b 356
fdd3a2da
PP
357 value = property(fset=_prop_set_value)
358
359
360class UnsignedIntegerValue(_IntegerValue):
361 _check_int_range = staticmethod(utils._check_uint64)
2f16a6a2
PP
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)
fdd3a2da
PP
366
367
368class SignedIntegerValue(_IntegerValue):
369 _check_int_range = staticmethod(utils._check_int64)
2f16a6a2
PP
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)
9b6cd4a7 374
81447b5b 375
10a19b49
SM
376class RealValue(_RealValue):
377 _NAME = 'Real number'
81447b5b
PP
378
379 def __init__(self, value=None):
380 if value is None:
10a19b49 381 ptr = native_bt.value_real_create()
81447b5b
PP
382 else:
383 value = self._value_to_float(value)
10a19b49 384 ptr = native_bt.value_real_create_init(value)
81447b5b
PP
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
9b6cd4a7 396 def _value(self):
10a19b49 397 return native_bt.value_real_get(self._ptr)
81447b5b 398
9b6cd4a7 399 def _set_value(self, value):
10a19b49 400 native_bt.value_real_set(self._ptr, self._value_to_float(value))
81447b5b 401
9b6cd4a7
PP
402 value = property(fset=_set_value)
403
81447b5b
PP
404
405@functools.total_ordering
10a19b49 406class StringValue(collections.abc.Sequence, _Value):
81447b5b
PP
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__):
9b6cd4a7 420 value = value._value
81447b5b
PP
421
422 utils._check_str(value)
423 return value
424
425 @property
9b6cd4a7 426 def _value(self):
10a19b49 427 return native_bt.value_string_get(self._ptr)
81447b5b 428
9b6cd4a7 429 def _set_value(self, value):
81447b5b
PP
430 status = native_bt.value_string_set(self._ptr, self._value_to_str(value))
431 self._handle_status(status)
432
9b6cd4a7
PP
433 value = property(fset=_set_value)
434
b00a769c 435 def __eq__(self, other):
81447b5b 436 try:
9b6cd4a7 437 return self._value == self._value_to_str(other)
81447b5b 438 except:
b00a769c 439 return False
81447b5b 440
81447b5b 441 def __lt__(self, other):
9b6cd4a7 442 return self._value < self._value_to_str(other)
81447b5b
PP
443
444 def __bool__(self):
9b6cd4a7 445 return bool(self._value)
81447b5b 446
83656269 447 def __repr__(self):
10a19b49 448 return repr(self._value)
83656269 449
81447b5b 450 def __str__(self):
9b6cd4a7 451 return self._value
81447b5b
PP
452
453 def __getitem__(self, index):
9b6cd4a7 454 return self._value[index]
81447b5b
PP
455
456 def __len__(self):
9b6cd4a7 457 return len(self._value)
81447b5b
PP
458
459 def __iadd__(self, value):
9b6cd4a7 460 curvalue = self._value
81447b5b
PP
461 curvalue += self._value_to_str(value)
462 self.value = curvalue
463 return self
464
465
466class _Container:
467 def __bool__(self):
468 return len(self) != 0
469
81447b5b
PP
470 def __delitem__(self, index):
471 raise NotImplementedError
472
473
474class 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
b00a769c
PP
488 def __eq__(self, other):
489 if not isinstance(other, collections.abc.Sequence):
490 return False
81447b5b 491
b00a769c
PP
492 if len(self) != len(other):
493 # early mismatch
494 return False
81447b5b 495
b00a769c
PP
496 for self_elem, other_elem in zip(self, other):
497 if self_elem != other_elem:
498 return False
499
500 return True
81447b5b
PP
501
502 def __len__(self):
10a19b49 503 size = native_bt.value_array_get_size(self._ptr)
811644b8 504 assert(size >= 0)
81447b5b
PP
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)
10a19b49 519 ptr = native_bt.value_array_borrow_element_by_index(self._ptr, index)
811644b8 520 assert(ptr)
10a19b49 521 return _create_from_ptr_and_get_ref(ptr)
81447b5b
PP
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
10a19b49
SM
532 status = native_bt.value_array_set_element_by_index(
533 self._ptr, index, ptr)
81447b5b
PP
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
10a19b49 544 status = native_bt.value_array_append_element(self._ptr, ptr)
81447b5b
PP
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
83656269
JG
555 def __repr__(self):
556 return '[{}]'.format(', '.join([repr(v) for v in self]))
81447b5b
PP
557
558 def insert(self, value):
559 raise NotImplementedError
560
561
562class _MapValueKeyIterator(collections.abc.Iterator):
563 def __init__(self, map_obj):
564 self._map_obj = map_obj
565 self._at = 0
10a19b49 566 keys_ptr = native_bt.value_map_get_keys(map_obj._ptr)
81447b5b
PP
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
582class 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
81447b5b
PP
596 def __ne__(self, other):
597 return _Value.__ne__(self, other)
598
b00a769c
PP
599 def __eq__(self, other):
600 if not isinstance(other, collections.abc.Mapping):
601 return False
81447b5b 602
b00a769c
PP
603 if len(self) != len(other):
604 # early mismatch
605 return False
81447b5b 606
b00a769c
PP
607 for self_key in self:
608 if self_key not in other:
609 return False
81447b5b 610
b00a769c
PP
611 if self[self_key] != other[self_key]:
612 return False
81447b5b 613
b00a769c 614 return True
81447b5b
PP
615
616 def __len__(self):
10a19b49 617 size = native_bt.value_map_get_size(self._ptr)
811644b8 618 assert(size >= 0)
81447b5b
PP
619 return size
620
621 def __contains__(self, key):
622 self._check_key_type(key)
10a19b49 623 return native_bt.value_map_has_entry(self._ptr, key)
81447b5b
PP
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)
10a19b49 634 ptr = native_bt.value_map_borrow_entry_value(self._ptr, key)
811644b8 635 assert(ptr)
10a19b49 636 return _create_from_ptr_and_get_ref(ptr)
81447b5b
PP
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
10a19b49 650 status = native_bt.value_map_insert_entry(self._ptr, key, ptr)
81447b5b
PP
651 self._handle_status(status)
652
83656269
JG
653 def __repr__(self):
654 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
655 return '{{{}}}'.format(', '.join(items))
81447b5b
PP
656
657
658_TYPE_TO_OBJ = {
659 native_bt.VALUE_TYPE_BOOL: BoolValue,
fdd3a2da
PP
660 native_bt.VALUE_TYPE_UNSIGNED_INTEGER: UnsignedIntegerValue,
661 native_bt.VALUE_TYPE_SIGNED_INTEGER: SignedIntegerValue,
10a19b49 662 native_bt.VALUE_TYPE_REAL: RealValue,
81447b5b
PP
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.06999 seconds and 4 git commands to generate.