Fix: bt2: erroneous integer comparison of Field and Value
[babeltrace.git] / src / bindings / python / bt2 / bt2 / field.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
b4f45851 24import bt2.field_class
81447b5b
PP
25import collections.abc
26import functools
27import numbers
28import math
81447b5b
PP
29import bt2
30
31
2ae9f48c
SM
32def _create_field_from_ptr(ptr, owner_ptr, owner_get_ref, owner_put_ref):
33 field_class_ptr = native_bt.field_borrow_class_const(ptr)
34 utils._handle_ptr(field_class_ptr, "cannot get field object's class")
35 typeid = native_bt.field_class_get_type(field_class_ptr)
36 field = _TYPE_ID_TO_OBJ[typeid]._create_from_ptr_and_get_ref(
37 ptr, owner_ptr, owner_get_ref, owner_put_ref)
81447b5b
PP
38 return field
39
40
1eccc498
SM
41# Get the "effective" field of `field`. If `field` is a variant, return the
42# currently selected field. If `field` is of any other type, return `field`
43# directly.
81447b5b 44
1eccc498
SM
45def _get_leaf_field(field):
46 if not isinstance(field, _VariantField):
47 return field
48
49 return _get_leaf_field(field.selected_option)
81447b5b 50
e1c6bebd 51
1eccc498
SM
52class _Field(object._UniqueObject):
53 def __eq__(self, other):
e1c6bebd
JG
54 other = _get_leaf_field(other)
55 return self._spec_eq(other)
56
81447b5b 57 @property
b4f45851 58 def field_class(self):
838a5a52
SM
59 field_class_ptr = native_bt.field_borrow_class_const(self._ptr)
60 assert field_class_ptr is not None
61 return bt2.field_class._create_field_class_from_ptr_and_get_ref(field_class_ptr)
81447b5b 62
12bf0d88
JG
63 def _repr(self):
64 raise NotImplementedError
65
66 def __repr__(self):
1eccc498 67 return self._repr()
12bf0d88 68
81447b5b
PP
69
70@functools.total_ordering
71class _NumericField(_Field):
72 @staticmethod
73 def _extract_value(other):
74 if other is True or other is False:
75 return other
76
77 if isinstance(other, numbers.Integral):
78 return int(other)
79
80 if isinstance(other, numbers.Real):
81 return float(other)
82
83 if isinstance(other, numbers.Complex):
84 return complex(other)
85
86 raise TypeError("'{}' object is not a number object".format(other.__class__.__name__))
87
88 def __int__(self):
e1c6bebd 89 return int(self._value)
81447b5b
PP
90
91 def __float__(self):
e1c6bebd 92 return float(self._value)
81447b5b 93
12bf0d88 94 def _repr(self):
5abb9e33 95 return repr(self._value)
81447b5b
PP
96
97 def __lt__(self, other):
98 if not isinstance(other, numbers.Number):
99 raise TypeError('unorderable types: {}() < {}()'.format(self.__class__.__name__,
100 other.__class__.__name__))
101
e1c6bebd 102 return self._value < float(other)
81447b5b 103
e1c6bebd 104 def _spec_eq(self, other):
81447b5b 105 if not isinstance(other, numbers.Number):
1eccc498 106 return NotImplemented
81447b5b 107
e1c6bebd 108 return self._value == complex(other)
81447b5b
PP
109
110 def __rmod__(self, other):
e1c6bebd 111 return self._extract_value(other) % self._value
81447b5b
PP
112
113 def __mod__(self, other):
e1c6bebd 114 return self._value % self._extract_value(other)
81447b5b
PP
115
116 def __rfloordiv__(self, other):
e1c6bebd 117 return self._extract_value(other) // self._value
81447b5b
PP
118
119 def __floordiv__(self, other):
e1c6bebd 120 return self._value // self._extract_value(other)
81447b5b
PP
121
122 def __round__(self, ndigits=None):
123 if ndigits is None:
e1c6bebd 124 return round(self._value)
81447b5b 125 else:
e1c6bebd 126 return round(self._value, ndigits)
81447b5b
PP
127
128 def __ceil__(self):
e1c6bebd 129 return math.ceil(self._value)
81447b5b
PP
130
131 def __floor__(self):
e1c6bebd 132 return math.floor(self._value)
81447b5b
PP
133
134 def __trunc__(self):
e1c6bebd 135 return int(self._value)
81447b5b
PP
136
137 def __abs__(self):
e1c6bebd 138 return abs(self._value)
81447b5b
PP
139
140 def __add__(self, other):
e1c6bebd 141 return self._value + self._extract_value(other)
81447b5b
PP
142
143 def __radd__(self, other):
144 return self.__add__(other)
145
146 def __neg__(self):
e1c6bebd 147 return -self._value
81447b5b
PP
148
149 def __pos__(self):
e1c6bebd 150 return +self._value
81447b5b
PP
151
152 def __mul__(self, other):
e1c6bebd 153 return self._value * self._extract_value(other)
81447b5b
PP
154
155 def __rmul__(self, other):
156 return self.__mul__(other)
157
158 def __truediv__(self, other):
e1c6bebd 159 return self._value / self._extract_value(other)
81447b5b
PP
160
161 def __rtruediv__(self, other):
e1c6bebd 162 return self._extract_value(other) / self._value
81447b5b
PP
163
164 def __pow__(self, exponent):
e1c6bebd 165 return self._value ** self._extract_value(exponent)
81447b5b
PP
166
167 def __rpow__(self, base):
e1c6bebd 168 return self._extract_value(base) ** self._value
81447b5b
PP
169
170 def __iadd__(self, other):
171 self.value = self + other
172 return self
173
174 def __isub__(self, other):
175 self.value = self - other
176 return self
177
178 def __imul__(self, other):
179 self.value = self * other
180 return self
181
182 def __itruediv__(self, other):
183 self.value = self / other
184 return self
185
186 def __ifloordiv__(self, other):
187 self.value = self // other
188 return self
189
190 def __imod__(self, other):
191 self.value = self % other
192 return self
193
194 def __ipow__(self, other):
195 self.value = self ** other
196 return self
197
198
199class _IntegralField(_NumericField, numbers.Integral):
200 def __lshift__(self, other):
e1c6bebd 201 return self._value << self._extract_value(other)
81447b5b
PP
202
203 def __rlshift__(self, other):
e1c6bebd 204 return self._extract_value(other) << self._value
81447b5b
PP
205
206 def __rshift__(self, other):
e1c6bebd 207 return self._value >> self._extract_value(other)
81447b5b
PP
208
209 def __rrshift__(self, other):
e1c6bebd 210 return self._extract_value(other) >> self._value
81447b5b
PP
211
212 def __and__(self, other):
e1c6bebd 213 return self._value & self._extract_value(other)
81447b5b
PP
214
215 def __rand__(self, other):
e1c6bebd 216 return self._extract_value(other) & self._value
81447b5b
PP
217
218 def __xor__(self, other):
e1c6bebd 219 return self._value ^ self._extract_value(other)
81447b5b
PP
220
221 def __rxor__(self, other):
e1c6bebd 222 return self._extract_value(other) ^ self._value
81447b5b
PP
223
224 def __or__(self, other):
e1c6bebd 225 return self._value | self._extract_value(other)
81447b5b
PP
226
227 def __ror__(self, other):
e1c6bebd 228 return self._extract_value(other) | self._value
81447b5b
PP
229
230 def __invert__(self):
e1c6bebd 231 return ~self._value
81447b5b
PP
232
233 def __ilshift__(self, other):
234 self.value = self << other
235 return self
236
237 def __irshift__(self, other):
238 self.value = self >> other
239 return self
240
241 def __iand__(self, other):
242 self.value = self & other
243 return self
244
245 def __ixor__(self, other):
246 self.value = self ^ other
247 return self
248
249 def __ior__(self, other):
250 self.value = self | other
251 return self
252
7bb4180f
FD
253 def __lt__(self, other):
254 if not isinstance(other, numbers.Integral):
255 return super().__lt__(other);
256
257 return self._value < int(other)
258
259 def _spec_eq(self, other):
260 if not isinstance(other, numbers.Integral):
261 return super()._spec_eq(other);
262
263 return self._value == int(other)
264
81447b5b 265
2ae9f48c 266class _IntegerField(_IntegralField, _Field):
81447b5b
PP
267 pass
268
269
2ae9f48c
SM
270class _UnsignedIntegerField(_IntegerField, _Field):
271 _NAME = 'Unsigned integer'
1eccc498 272
81447b5b
PP
273 def _value_to_int(self, value):
274 if not isinstance(value, numbers.Real):
275 raise TypeError('expecting a real number object')
276
277 value = int(value)
2ae9f48c 278 utils._check_uint64(value)
81447b5b
PP
279
280 return value
281
282 @property
e1c6bebd 283 def _value(self):
2ae9f48c 284 return native_bt.field_unsigned_integer_get_value(self._ptr)
81447b5b 285
2ae9f48c
SM
286 def _set_value(self, value):
287 value = self._value_to_int(value)
288 native_bt.field_unsigned_integer_set_value(self._ptr, value)
289
290 value = property(fset=_set_value)
291
292
293class _SignedIntegerField(_IntegerField, _Field):
294 _NAME = 'Signed integer'
1eccc498 295
2ae9f48c
SM
296 def _value_to_int(self, value):
297 if not isinstance(value, numbers.Real):
298 raise TypeError('expecting a real number object')
e1c6bebd 299
2ae9f48c
SM
300 value = int(value)
301 utils._check_int64(value)
811644b8 302
81447b5b
PP
303 return value
304
2ae9f48c
SM
305 @property
306 def _value(self):
307 return native_bt.field_signed_integer_get_value(self._ptr)
308
e1c6bebd 309 def _set_value(self, value):
81447b5b 310 value = self._value_to_int(value)
2ae9f48c 311 native_bt.field_signed_integer_set_value(self._ptr, value)
81447b5b 312
e1c6bebd 313 value = property(fset=_set_value)
81447b5b 314
0b03f63e 315
2ae9f48c
SM
316class _RealField(_NumericField, numbers.Real):
317 _NAME = 'Real'
81447b5b
PP
318
319 def _value_to_float(self, value):
320 if not isinstance(value, numbers.Real):
321 raise TypeError("expecting a real number object")
322
323 return float(value)
324
325 @property
e1c6bebd 326 def _value(self):
2ae9f48c 327 return native_bt.field_real_get_value(self._ptr)
81447b5b 328
e1c6bebd 329 def _set_value(self, value):
81447b5b 330 value = self._value_to_float(value)
2ae9f48c 331 native_bt.field_real_set_value(self._ptr, value)
81447b5b 332
e1c6bebd 333 value = property(fset=_set_value)
81447b5b 334
0b03f63e 335
81447b5b 336class _EnumerationField(_IntegerField):
1eccc498
SM
337 def _repr(self):
338 return '{} ({})'.format(self._value, ', '.join(self.labels))
81447b5b
PP
339
340 @property
1eccc498
SM
341 def labels(self):
342 ret, labels = self._get_mapping_labels(self._ptr)
343 utils._handle_ret(ret, "cannot get label for enumeration field")
81447b5b 344
1eccc498
SM
345 assert labels is not None
346 return labels
81447b5b 347
4addd228 348
1eccc498
SM
349class _UnsignedEnumerationField(_EnumerationField, _UnsignedIntegerField):
350 _NAME = 'Unsigned Enumeration'
351 _get_mapping_labels = staticmethod(native_bt.field_unsigned_enumeration_get_mapping_labels)
e1c6bebd 352
e1c6bebd 353
1eccc498
SM
354class _SignedEnumerationField(_EnumerationField, _SignedIntegerField):
355 _NAME = 'Signed Enumeration'
356 _get_mapping_labels = staticmethod(native_bt.field_signed_enumeration_get_mapping_labels)
81447b5b
PP
357
358
359@functools.total_ordering
1eccc498 360class _StringField(_Field):
81447b5b
PP
361 _NAME = 'String'
362
363 def _value_to_str(self, value):
364 if isinstance(value, self.__class__):
e1c6bebd 365 value = value._value
81447b5b
PP
366
367 if not isinstance(value, str):
368 raise TypeError("expecting a 'str' object")
369
370 return value
371
372 @property
e1c6bebd 373 def _value(self):
1eccc498 374 return native_bt.field_string_get_value(self._ptr)
81447b5b 375
e1c6bebd 376 def _set_value(self, value):
81447b5b 377 value = self._value_to_str(value)
1eccc498 378 native_bt.field_string_set_value(self._ptr, value)
81447b5b 379
e1c6bebd
JG
380 value = property(fset=_set_value)
381
382 def _spec_eq(self, other):
81447b5b
PP
383 try:
384 other = self._value_to_str(other)
1eccc498 385 except Exception:
81447b5b
PP
386 return False
387
e1c6bebd 388 return self._value == other
81447b5b 389
81447b5b 390 def __lt__(self, other):
e1c6bebd 391 return self._value < self._value_to_str(other)
81447b5b
PP
392
393 def __bool__(self):
e1c6bebd 394 return bool(self._value)
81447b5b 395
12bf0d88 396 def _repr(self):
d623d2e9
JG
397 return repr(self._value)
398
81447b5b 399 def __str__(self):
1eccc498 400 return str(self._value)
81447b5b
PP
401
402 def __getitem__(self, index):
e1c6bebd 403 return self._value[index]
81447b5b
PP
404
405 def __len__(self):
1eccc498 406 return native_bt.field_string_get_length(self._ptr)
81447b5b
PP
407
408 def __iadd__(self, value):
409 value = self._value_to_str(value)
50842bdc 410 ret = native_bt.field_string_append(self._ptr, value)
81447b5b
PP
411 utils._handle_ret(ret, "cannot append to string field object's value")
412 return self
413
414
415class _ContainerField(_Field):
416 def __bool__(self):
417 return len(self) != 0
418
419 def __len__(self):
420 count = self._count()
1eccc498 421 assert count >= 0
81447b5b
PP
422 return count
423
424 def __delitem__(self, index):
425 raise NotImplementedError
426
427
428class _StructureField(_ContainerField, collections.abc.MutableMapping):
429 _NAME = 'Structure'
430
431 def _count(self):
b4f45851 432 return len(self.field_class)
81447b5b 433
81447b5b 434 def __setitem__(self, key, value):
236355c2 435 # raises if key is somehow invalid
81447b5b
PP
436 field = self[key]
437
81447b5b
PP
438 # the field's property does the appropriate conversion or raises
439 # the appropriate exception
440 field.value = value
441
81447b5b
PP
442 def __iter__(self):
443 # same name iterator
b4f45851 444 return iter(self.field_class)
81447b5b 445
e1c6bebd
JG
446 def _spec_eq(self, other):
447 try:
448 if len(self) != len(other):
81447b5b
PP
449 return False
450
e1c6bebd
JG
451 for self_key, self_value in self.items():
452 if self_key not in other:
453 return False
81447b5b 454
e1c6bebd 455 other_value = other[self_key]
81447b5b 456
e1c6bebd
JG
457 if self_value != other_value:
458 return False
459
460 return True
1eccc498 461 except Exception:
e1c6bebd 462 return False
81447b5b 463
e1c6bebd 464 def _set_value(self, values):
e1c6bebd
JG
465 try:
466 for key, value in values.items():
467 self[key].value = value
1eccc498 468 except Exception:
e1c6bebd 469 raise
7c54e2e7 470
e1c6bebd 471 value = property(fset=_set_value)
81447b5b 472
12bf0d88 473 def _repr(self):
ac7e2dc6
JG
474 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
475 return '{{{}}}'.format(', '.join(items))
476
1eccc498
SM
477 def __getitem__(self, key):
478 utils._check_str(key)
479 field_ptr = native_bt.field_structure_borrow_member_field_by_name(self._ptr, key)
0b03f63e 480
1eccc498
SM
481 if field_ptr is None:
482 raise KeyError(key)
81447b5b 483
1eccc498
SM
484 return _create_field_from_ptr(field_ptr, self._owner_ptr,
485 self._owner_get_ref,
486 self._owner_put_ref)
811644b8 487
1eccc498
SM
488 def member_at_index(self, index):
489 utils._check_uint64(index)
811644b8 490
1eccc498
SM
491 if index >= len(self):
492 raise IndexError
493
494 field_ptr = native_bt.field_structure_borrow_member_field_by_index(self._ptr, index)
495 assert field_ptr is not None
496 return _create_field_from_ptr(field_ptr, self._owner_ptr,
497 self._owner_get_ref,
498 self._owner_put_ref)
499
500
501class _VariantField(_ContainerField, _Field):
502 _NAME = 'Variant'
81447b5b
PP
503
504 @property
1eccc498
SM
505 def selected_option_index(self):
506 return native_bt.field_variant_get_selected_option_field_index(self._ptr)
81447b5b 507
1eccc498
SM
508 @selected_option_index.setter
509 def selected_option_index(self, index):
510 native_bt.field_variant_select_option_field(self._ptr, index)
811644b8 511
1eccc498
SM
512 @property
513 def selected_option(self):
514 field_ptr = native_bt.field_variant_borrow_selected_option_field(self._ptr)
515 utils._handle_ptr(field_ptr, "cannot get variant field's selected option")
81447b5b 516
1eccc498
SM
517 return _create_field_from_ptr(field_ptr, self._owner_ptr,
518 self._owner_get_ref,
519 self._owner_put_ref)
81447b5b 520
e1c6bebd 521 def _spec_eq(self, other):
1eccc498
SM
522 new_self = _get_leaf_field(self)
523 return new_self == other
811644b8
PP
524
525 def __bool__(self):
1eccc498 526 raise NotImplementedError
81447b5b 527
12bf0d88 528 def __str__(self):
1eccc498 529 return str(self.selected_option)
12bf0d88
JG
530
531 def _repr(self):
1eccc498 532 return repr(self.selected_option)
e1c6bebd
JG
533
534 def _set_value(self, value):
1eccc498 535 self.selected_option.value = value
e1c6bebd
JG
536
537 value = property(fset=_set_value)
81447b5b 538
0b03f63e 539
1eccc498
SM
540class _ArrayField(_ContainerField, _Field):
541
542 def _get_length(self):
543 return native_bt.field_array_get_length(self._ptr)
544
545 length = property(fget=_get_length)
546
81447b5b
PP
547 def __getitem__(self, index):
548 if not isinstance(index, numbers.Integral):
549 raise TypeError("'{}' is not an integral number object: invalid index".format(index.__class__.__name__))
550
551 index = int(index)
552
553 if index < 0 or index >= len(self):
554 raise IndexError('{} field object index is out of range'.format(self._NAME))
555
1eccc498 556 field_ptr = native_bt.field_array_borrow_element_field_by_index(self._ptr, index)
811644b8 557 assert(field_ptr)
1eccc498
SM
558 return _create_field_from_ptr(field_ptr, self._owner_ptr,
559 self._owner_get_ref,
560 self._owner_put_ref)
81447b5b
PP
561
562 def __setitem__(self, index, value):
563 # we can only set numbers and strings
564 if not isinstance(value, (numbers.Number, _StringField, str)):
565 raise TypeError('expecting number or string object')
566
567 # raises if index is somehow invalid
568 field = self[index]
569
570 if not isinstance(field, (_NumericField, _StringField)):
571 raise TypeError('can only set the value of a number or string field')
572
573 # the field's property does the appropriate conversion or raises
574 # the appropriate exception
575 field.value = value
576
577 def insert(self, index, value):
578 raise NotImplementedError
579
e1c6bebd
JG
580 def _spec_eq(self, other):
581 try:
582 if len(self) != len(other):
81447b5b
PP
583 return False
584
e1c6bebd
JG
585 for self_field, other_field in zip(self, other):
586 if self_field != other_field:
587 return False
7c54e2e7 588
e1c6bebd 589 return True
1eccc498 590 except Exception:
e1c6bebd 591 return False
7c54e2e7 592
12bf0d88 593 def _repr(self):
2bc21382
JG
594 return '[{}]'.format(', '.join([repr(v) for v in self]))
595
81447b5b 596
1eccc498
SM
597class _StaticArrayField(_ArrayField, _Field):
598 _NAME = 'Static array'
81447b5b
PP
599
600 def _count(self):
1eccc498 601 return native_bt.field_array_get_length(self._ptr)
81447b5b 602
e1c6bebd
JG
603 def _set_value(self, values):
604 if len(self) != len(values):
605 raise ValueError(
606 'expected length of value and array field to match')
607
1eccc498
SM
608 for index, value in enumerate(values):
609 if value is not None:
610 self[index].value = value
e1c6bebd
JG
611
612 value = property(fset=_set_value)
613
81447b5b 614
1eccc498
SM
615class _DynamicArrayField(_ArrayField, _Field):
616 _NAME = 'Dynamic array'
81447b5b
PP
617
618 def _count(self):
1eccc498 619 return self.length
81447b5b 620
1eccc498
SM
621 def _set_length(self, length):
622 utils._check_uint64(length)
623 ret = native_bt.field_dynamic_array_set_length(self._ptr, length)
624 utils._handle_ret(ret, "cannot set dynamic array length")
81447b5b 625
1eccc498 626 length = property(fget=_ArrayField._get_length, fset=_set_length)
81447b5b 627
e1c6bebd 628 def _set_value(self, values):
1eccc498
SM
629 if len(values) != self.length:
630 self.length = len(values)
e1c6bebd 631
1eccc498
SM
632 for index, value in enumerate(values):
633 if value is not None:
634 self[index].value = value
e1c6bebd
JG
635
636 value = property(fset=_set_value)
81447b5b 637
0b03f63e 638
81447b5b 639_TYPE_ID_TO_OBJ = {
2ae9f48c
SM
640 native_bt.FIELD_CLASS_TYPE_UNSIGNED_INTEGER: _UnsignedIntegerField,
641 native_bt.FIELD_CLASS_TYPE_SIGNED_INTEGER: _SignedIntegerField,
642 native_bt.FIELD_CLASS_TYPE_REAL: _RealField,
1eccc498
SM
643 native_bt.FIELD_CLASS_TYPE_UNSIGNED_ENUMERATION: _UnsignedEnumerationField,
644 native_bt.FIELD_CLASS_TYPE_SIGNED_ENUMERATION: _SignedEnumerationField,
2ae9f48c
SM
645 native_bt.FIELD_CLASS_TYPE_STRING: _StringField,
646 native_bt.FIELD_CLASS_TYPE_STRUCTURE: _StructureField,
1eccc498
SM
647 native_bt.FIELD_CLASS_TYPE_STATIC_ARRAY: _StaticArrayField,
648 native_bt.FIELD_CLASS_TYPE_DYNAMIC_ARRAY: _DynamicArrayField,
649 native_bt.FIELD_CLASS_TYPE_VARIANT: _VariantField,
81447b5b 650}
This page took 0.071252 seconds and 4 git commands to generate.