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