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