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