Implement __repr__ for _ArraySequenceField
[babeltrace.git] / bindings / python / bt2 / bt2 / fields.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 bt2.field_types
25import collections.abc
26import functools
27import numbers
28import math
29import abc
30import bt2
31
32
e1c6bebd
JG
33def _get_leaf_field(obj):
34 if type(obj) is not _VariantField:
35 return obj
36
37 return _get_leaf_field(obj.selected_field)
38
39
81447b5b
PP
40def _create_from_ptr(ptr):
41 # recreate the field type wrapper of this field's type (the identity
42 # could be different, but the underlying address should be the
43 # same)
50842bdc 44 field_type_ptr = native_bt.field_get_type(ptr)
81447b5b
PP
45 utils._handle_ptr(field_type_ptr, "cannot get field object's type")
46 field_type = bt2.field_types._create_from_ptr(field_type_ptr)
50842bdc 47 typeid = native_bt.field_type_get_type_id(field_type._ptr)
81447b5b
PP
48 field = _TYPE_ID_TO_OBJ[typeid]._create_from_ptr(ptr)
49 field._field_type = field_type
50 return field
51
52
53class _Field(object._Object, metaclass=abc.ABCMeta):
54 def __copy__(self):
50842bdc 55 ptr = native_bt.field_copy(self._ptr)
81447b5b
PP
56 utils._handle_ptr(ptr, 'cannot copy {} field object'.format(self._NAME.lower()))
57 return _create_from_ptr(ptr)
58
59 def __deepcopy__(self, memo):
60 cpy = self.__copy__()
61 memo[id(self)] = cpy
62 return cpy
63
e1c6bebd
JG
64 def __eq__(self, other):
65 # special case: two unset fields with the same field type are equal
66 if isinstance(other, _Field):
67 if not self.is_set or not other.is_set:
68 if not self.is_set and not other.is_set and self.field_type == other.field_type:
69 return True
70 return False
71
72 other = _get_leaf_field(other)
73 return self._spec_eq(other)
74
81447b5b
PP
75 @property
76 def field_type(self):
77 return self._field_type
78
742e4747
JG
79 @property
80 def is_set(self):
50842bdc 81 is_set = native_bt.field_is_set(self._ptr)
742e4747
JG
82 return is_set > 0
83
84 def reset(self):
50842bdc 85 ret = native_bt.field_reset(self._ptr)
742e4747
JG
86 utils._handle_ret(ret, "cannot reset field object's value")
87
81447b5b
PP
88
89@functools.total_ordering
90class _NumericField(_Field):
91 @staticmethod
92 def _extract_value(other):
93 if other is True or other is False:
94 return other
95
96 if isinstance(other, numbers.Integral):
97 return int(other)
98
99 if isinstance(other, numbers.Real):
100 return float(other)
101
102 if isinstance(other, numbers.Complex):
103 return complex(other)
104
105 raise TypeError("'{}' object is not a number object".format(other.__class__.__name__))
106
107 def __int__(self):
e1c6bebd 108 return int(self._value)
81447b5b
PP
109
110 def __float__(self):
e1c6bebd 111 return float(self._value)
81447b5b
PP
112
113 def __str__(self):
e1c6bebd 114 return str(self._value)
81447b5b
PP
115
116 def __lt__(self, other):
117 if not isinstance(other, numbers.Number):
118 raise TypeError('unorderable types: {}() < {}()'.format(self.__class__.__name__,
119 other.__class__.__name__))
120
e1c6bebd 121 return self._value < float(other)
81447b5b
PP
122
123 def __le__(self, other):
124 if not isinstance(other, numbers.Number):
125 raise TypeError('unorderable types: {}() <= {}()'.format(self.__class__.__name__,
126 other.__class__.__name__))
127
e1c6bebd 128 return self._value <= float(other)
81447b5b 129
e1c6bebd 130 def _spec_eq(self, other):
81447b5b
PP
131 if not isinstance(other, numbers.Number):
132 return False
133
e1c6bebd 134 return self._value == complex(other)
81447b5b
PP
135
136 def __rmod__(self, other):
e1c6bebd 137 return self._extract_value(other) % self._value
81447b5b
PP
138
139 def __mod__(self, other):
e1c6bebd 140 return self._value % self._extract_value(other)
81447b5b
PP
141
142 def __rfloordiv__(self, other):
e1c6bebd 143 return self._extract_value(other) // self._value
81447b5b
PP
144
145 def __floordiv__(self, other):
e1c6bebd 146 return self._value // self._extract_value(other)
81447b5b
PP
147
148 def __round__(self, ndigits=None):
149 if ndigits is None:
e1c6bebd 150 return round(self._value)
81447b5b 151 else:
e1c6bebd 152 return round(self._value, ndigits)
81447b5b
PP
153
154 def __ceil__(self):
e1c6bebd 155 return math.ceil(self._value)
81447b5b
PP
156
157 def __floor__(self):
e1c6bebd 158 return math.floor(self._value)
81447b5b
PP
159
160 def __trunc__(self):
e1c6bebd 161 return int(self._value)
81447b5b
PP
162
163 def __abs__(self):
e1c6bebd 164 return abs(self._value)
81447b5b
PP
165
166 def __add__(self, other):
e1c6bebd 167 return self._value + self._extract_value(other)
81447b5b
PP
168
169 def __radd__(self, other):
170 return self.__add__(other)
171
172 def __neg__(self):
e1c6bebd 173 return -self._value
81447b5b
PP
174
175 def __pos__(self):
e1c6bebd 176 return +self._value
81447b5b
PP
177
178 def __mul__(self, other):
e1c6bebd 179 return self._value * self._extract_value(other)
81447b5b
PP
180
181 def __rmul__(self, other):
182 return self.__mul__(other)
183
184 def __truediv__(self, other):
e1c6bebd 185 return self._value / self._extract_value(other)
81447b5b
PP
186
187 def __rtruediv__(self, other):
e1c6bebd 188 return self._extract_value(other) / self._value
81447b5b
PP
189
190 def __pow__(self, exponent):
e1c6bebd 191 return self._value ** self._extract_value(exponent)
81447b5b
PP
192
193 def __rpow__(self, base):
e1c6bebd 194 return self._extract_value(base) ** self._value
81447b5b
PP
195
196 def __iadd__(self, other):
197 self.value = self + other
198 return self
199
200 def __isub__(self, other):
201 self.value = self - other
202 return self
203
204 def __imul__(self, other):
205 self.value = self * other
206 return self
207
208 def __itruediv__(self, other):
209 self.value = self / other
210 return self
211
212 def __ifloordiv__(self, other):
213 self.value = self // other
214 return self
215
216 def __imod__(self, other):
217 self.value = self % other
218 return self
219
220 def __ipow__(self, other):
221 self.value = self ** other
222 return self
223
224
225class _IntegralField(_NumericField, numbers.Integral):
226 def __lshift__(self, other):
e1c6bebd 227 return self._value << self._extract_value(other)
81447b5b
PP
228
229 def __rlshift__(self, other):
e1c6bebd 230 return self._extract_value(other) << self._value
81447b5b
PP
231
232 def __rshift__(self, other):
e1c6bebd 233 return self._value >> self._extract_value(other)
81447b5b
PP
234
235 def __rrshift__(self, other):
e1c6bebd 236 return self._extract_value(other) >> self._value
81447b5b
PP
237
238 def __and__(self, other):
e1c6bebd 239 return self._value & self._extract_value(other)
81447b5b
PP
240
241 def __rand__(self, other):
e1c6bebd 242 return self._extract_value(other) & self._value
81447b5b
PP
243
244 def __xor__(self, other):
e1c6bebd 245 return self._value ^ self._extract_value(other)
81447b5b
PP
246
247 def __rxor__(self, other):
e1c6bebd 248 return self._extract_value(other) ^ self._value
81447b5b
PP
249
250 def __or__(self, other):
e1c6bebd 251 return self._value | self._extract_value(other)
81447b5b
PP
252
253 def __ror__(self, other):
e1c6bebd 254 return self._extract_value(other) | self._value
81447b5b
PP
255
256 def __invert__(self):
e1c6bebd 257 return ~self._value
81447b5b
PP
258
259 def __ilshift__(self, other):
260 self.value = self << other
261 return self
262
263 def __irshift__(self, other):
264 self.value = self >> other
265 return self
266
267 def __iand__(self, other):
268 self.value = self & other
269 return self
270
271 def __ixor__(self, other):
272 self.value = self ^ other
273 return self
274
275 def __ior__(self, other):
276 self.value = self | other
277 return self
278
279
280class _RealField(_NumericField, numbers.Real):
281 pass
282
283
284class _IntegerField(_IntegralField):
285 _NAME = 'Integer'
286
287 def _value_to_int(self, value):
288 if not isinstance(value, numbers.Real):
289 raise TypeError('expecting a real number object')
290
291 value = int(value)
292
293 if self.field_type.is_signed:
294 utils._check_int64(value)
295 else:
296 utils._check_uint64(value)
297
298 return value
299
300 @property
e1c6bebd 301 def _value(self):
81447b5b 302 if self.field_type.is_signed:
50842bdc 303 ret, value = native_bt.field_signed_integer_get_value(self._ptr)
81447b5b 304 else:
50842bdc 305 ret, value = native_bt.field_unsigned_integer_get_value(self._ptr)
81447b5b 306
811644b8 307 if ret < 0:
e1c6bebd
JG
308 if not self.is_set:
309 return
310
311 utils._handle_ret(ret, "cannot get integer field's value")
811644b8 312
81447b5b
PP
313 return value
314
e1c6bebd 315 def _set_value(self, value):
81447b5b
PP
316 value = self._value_to_int(value)
317
318 if self.field_type.is_signed:
50842bdc 319 ret = native_bt.field_signed_integer_set_value(self._ptr, value)
81447b5b 320 else:
50842bdc 321 ret = native_bt.field_unsigned_integer_set_value(self._ptr, value)
81447b5b
PP
322
323 utils._handle_ret(ret, "cannot set integer field object's value")
324
e1c6bebd 325 value = property(fset=_set_value)
81447b5b 326
0b03f63e 327
81447b5b
PP
328class _FloatingPointNumberField(_RealField):
329 _NAME = 'Floating point number'
330
331 def _value_to_float(self, value):
332 if not isinstance(value, numbers.Real):
333 raise TypeError("expecting a real number object")
334
335 return float(value)
336
337 @property
e1c6bebd 338 def _value(self):
50842bdc 339 ret, value = native_bt.field_floating_point_get_value(self._ptr)
811644b8
PP
340
341 if ret < 0:
e1c6bebd
JG
342 if not self.is_set:
343 return
344
345 utils._handle_ret(ret, "cannot get floating point number field's value")
811644b8 346
81447b5b
PP
347 return value
348
e1c6bebd 349 def _set_value(self, value):
81447b5b 350 value = self._value_to_float(value)
50842bdc 351 ret = native_bt.field_floating_point_set_value(self._ptr, value)
81447b5b
PP
352 utils._handle_ret(ret, "cannot set floating point number field object's value")
353
e1c6bebd 354 value = property(fset=_set_value)
81447b5b 355
0b03f63e 356
81447b5b
PP
357class _EnumerationField(_IntegerField):
358 _NAME = 'Enumeration'
359
360 @property
361 def integer_field(self):
50842bdc 362 int_field_ptr = native_bt.field_enumeration_get_container(self._ptr)
811644b8 363 assert(int_field_ptr)
81447b5b
PP
364 return _create_from_ptr(int_field_ptr)
365
e1c6bebd 366 def _set_value(self, value):
81447b5b
PP
367 self.integer_field.value = value
368
4addd228
JG
369 def __repr__(self):
370 labels = [repr(v.name) for v in self.mappings]
371 return '{} ({})'.format(self._value, ', '.join(labels))
372
e1c6bebd
JG
373 value = property(fset=_set_value)
374
375 @property
376 def _value(self):
377 return self.integer_field._value
378
81447b5b
PP
379 @property
380 def mappings(self):
50842bdc 381 iter_ptr = native_bt.field_enumeration_get_mappings(self._ptr)
811644b8
PP
382 assert(iter_ptr)
383 return bt2.field_types._EnumerationFieldTypeMappingIterator(iter_ptr,
384 self.field_type.is_signed)
81447b5b
PP
385
386
387@functools.total_ordering
388class _StringField(_Field, collections.abc.Sequence):
389 _NAME = 'String'
390
391 def _value_to_str(self, value):
392 if isinstance(value, self.__class__):
e1c6bebd 393 value = value._value
81447b5b
PP
394
395 if not isinstance(value, str):
396 raise TypeError("expecting a 'str' object")
397
398 return value
399
400 @property
e1c6bebd 401 def _value(self):
50842bdc 402 value = native_bt.field_string_get_value(self._ptr)
81447b5b
PP
403 return value
404
e1c6bebd 405 def _set_value(self, value):
81447b5b 406 value = self._value_to_str(value)
50842bdc 407 ret = native_bt.field_string_set_value(self._ptr, value)
81447b5b
PP
408 utils._handle_ret(ret, "cannot set string field object's value")
409
e1c6bebd
JG
410 value = property(fset=_set_value)
411
412 def _spec_eq(self, other):
81447b5b
PP
413 try:
414 other = self._value_to_str(other)
415 except:
416 return False
417
e1c6bebd 418 return self._value == other
81447b5b
PP
419
420 def __le__(self, other):
e1c6bebd 421 return self._value <= self._value_to_str(other)
81447b5b
PP
422
423 def __lt__(self, other):
e1c6bebd 424 return self._value < self._value_to_str(other)
81447b5b
PP
425
426 def __bool__(self):
e1c6bebd 427 return bool(self._value)
81447b5b
PP
428
429 def __str__(self):
e1c6bebd 430 return self._value
81447b5b
PP
431
432 def __getitem__(self, index):
e1c6bebd 433 return self._value[index]
81447b5b
PP
434
435 def __len__(self):
e1c6bebd 436 return len(self._value)
81447b5b
PP
437
438 def __iadd__(self, value):
439 value = self._value_to_str(value)
50842bdc 440 ret = native_bt.field_string_append(self._ptr, value)
81447b5b
PP
441 utils._handle_ret(ret, "cannot append to string field object's value")
442 return self
443
444
445class _ContainerField(_Field):
446 def __bool__(self):
447 return len(self) != 0
448
449 def __len__(self):
450 count = self._count()
811644b8 451 assert(count >= 0)
81447b5b
PP
452 return count
453
454 def __delitem__(self, index):
455 raise NotImplementedError
456
457
458class _StructureField(_ContainerField, collections.abc.MutableMapping):
459 _NAME = 'Structure'
460
461 def _count(self):
462 return len(self.field_type)
463
464 def __getitem__(self, key):
465 utils._check_str(key)
50842bdc 466 ptr = native_bt.field_structure_get_field_by_name(self._ptr, key)
81447b5b
PP
467
468 if ptr is None:
469 raise KeyError(key)
470
471 return _create_from_ptr(ptr)
472
473 def __setitem__(self, key, value):
236355c2 474 # raises if key is somehow invalid
81447b5b
PP
475 field = self[key]
476
81447b5b
PP
477 # the field's property does the appropriate conversion or raises
478 # the appropriate exception
479 field.value = value
480
481 def at_index(self, index):
482 utils._check_uint64(index)
811644b8
PP
483
484 if index >= len(self):
485 raise IndexError
486
50842bdc 487 field_ptr = native_bt.field_structure_get_field_by_index(self._ptr, index)
811644b8 488 assert(field_ptr)
81447b5b
PP
489 return _create_from_ptr(field_ptr)
490
491 def __iter__(self):
492 # same name iterator
493 return iter(self.field_type)
494
e1c6bebd
JG
495 def _spec_eq(self, other):
496 try:
497 if len(self) != len(other):
81447b5b
PP
498 return False
499
e1c6bebd
JG
500 for self_key, self_value in self.items():
501 if self_key not in other:
502 return False
81447b5b 503
e1c6bebd 504 other_value = other[self_key]
81447b5b 505
e1c6bebd
JG
506 if self_value != other_value:
507 return False
508
509 return True
510 except:
511 return False
81447b5b 512
7c54e2e7 513 @property
e1c6bebd
JG
514 def _value(self):
515 return {key: value._value for key, value in self.items()}
7c54e2e7 516
e1c6bebd
JG
517 def _set_value(self, values):
518 original_values = self._value
7c54e2e7 519
e1c6bebd
JG
520 try:
521 for key, value in values.items():
522 self[key].value = value
523 except:
524 self.value = original_values
525 raise
7c54e2e7 526
e1c6bebd 527 value = property(fset=_set_value)
81447b5b 528
ac7e2dc6
JG
529 def __repr__(self):
530 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
531 return '{{{}}}'.format(', '.join(items))
532
0b03f63e 533
81447b5b
PP
534class _VariantField(_Field):
535 _NAME = 'Variant'
536
537 @property
538 def tag_field(self):
50842bdc 539 field_ptr = native_bt.field_variant_get_tag(self._ptr)
811644b8
PP
540
541 if field_ptr is None:
542 return
543
81447b5b
PP
544 return _create_from_ptr(field_ptr)
545
546 @property
547 def selected_field(self):
548 return self.field()
549
550 def field(self, tag_field=None):
551 if tag_field is None:
50842bdc 552 field_ptr = native_bt.field_variant_get_current_field(self._ptr)
811644b8
PP
553
554 if field_ptr is None:
555 return
81447b5b
PP
556 else:
557 utils._check_type(tag_field, _EnumerationField)
50842bdc 558 field_ptr = native_bt.field_variant_get_field(self._ptr, tag_field._ptr)
81447b5b
PP
559 utils._handle_ptr(field_ptr, "cannot select variant field object's field")
560
561 return _create_from_ptr(field_ptr)
562
e1c6bebd
JG
563 def _spec_eq(self, other):
564 return _get_leaf_field(self) == other
811644b8
PP
565
566 def __bool__(self):
567 return bool(self.selected_field)
81447b5b 568
872eeccb
JG
569 def __repr__(self):
570 return repr(self._value)
571
e1c6bebd
JG
572 @property
573 def _value(self):
574 if self.selected_field is not None:
575 return self.selected_field._value
576
577 def _set_value(self, value):
578 self.selected_field.value = value
579
580 value = property(fset=_set_value)
81447b5b 581
0b03f63e 582
81447b5b
PP
583class _ArraySequenceField(_ContainerField, collections.abc.MutableSequence):
584 def __getitem__(self, index):
585 if not isinstance(index, numbers.Integral):
586 raise TypeError("'{}' is not an integral number object: invalid index".format(index.__class__.__name__))
587
588 index = int(index)
589
590 if index < 0 or index >= len(self):
591 raise IndexError('{} field object index is out of range'.format(self._NAME))
592
593 field_ptr = self._get_field_ptr_at_index(index)
811644b8 594 assert(field_ptr)
81447b5b
PP
595 return _create_from_ptr(field_ptr)
596
597 def __setitem__(self, index, value):
598 # we can only set numbers and strings
599 if not isinstance(value, (numbers.Number, _StringField, str)):
600 raise TypeError('expecting number or string object')
601
602 # raises if index is somehow invalid
603 field = self[index]
604
605 if not isinstance(field, (_NumericField, _StringField)):
606 raise TypeError('can only set the value of a number or string field')
607
608 # the field's property does the appropriate conversion or raises
609 # the appropriate exception
610 field.value = value
611
612 def insert(self, index, value):
613 raise NotImplementedError
614
e1c6bebd
JG
615 def _spec_eq(self, other):
616 try:
617 if len(self) != len(other):
81447b5b
PP
618 return False
619
e1c6bebd
JG
620 for self_field, other_field in zip(self, other):
621 if self_field != other_field:
622 return False
7c54e2e7 623
e1c6bebd
JG
624 return True
625 except:
626 return False
7c54e2e7 627
e1c6bebd
JG
628 @property
629 def _value(self):
630 return [field._value for field in self]
7c54e2e7 631
2bc21382
JG
632 def __repr__(self):
633 return '[{}]'.format(', '.join([repr(v) for v in self]))
634
81447b5b
PP
635
636class _ArrayField(_ArraySequenceField):
637 _NAME = 'Array'
638
639 def _count(self):
640 return self.field_type.length
641
642 def _get_field_ptr_at_index(self, index):
50842bdc 643 return native_bt.field_array_get_field(self._ptr, index)
81447b5b 644
e1c6bebd
JG
645 def _set_value(self, values):
646 if len(self) != len(values):
647 raise ValueError(
648 'expected length of value and array field to match')
649
650 original_values = self._value
651 try:
652 for index, value in enumerate(values):
653 if value is not None:
654 self[index].value = value
655 else:
656 self[index].reset()
657 except:
658 self.value = original_values
659 raise
660
661 value = property(fset=_set_value)
662
81447b5b
PP
663
664class _SequenceField(_ArraySequenceField):
665 _NAME = 'Sequence'
666
667 def _count(self):
a29094be 668 return int(self.length_field)
81447b5b
PP
669
670 @property
671 def length_field(self):
50842bdc 672 field_ptr = native_bt.field_sequence_get_length(self._ptr)
a29094be
JG
673 if field_ptr is None:
674 return
81447b5b
PP
675 return _create_from_ptr(field_ptr)
676
677 @length_field.setter
678 def length_field(self, length_field):
679 utils._check_type(length_field, _IntegerField)
50842bdc 680 ret = native_bt.field_sequence_set_length(self._ptr, length_field._ptr)
81447b5b
PP
681 utils._handle_ret(ret, "cannot set sequence field object's length field")
682
683 def _get_field_ptr_at_index(self, index):
50842bdc 684 return native_bt.field_sequence_get_field(self._ptr, index)
81447b5b 685
e1c6bebd
JG
686 def _set_value(self, values):
687 original_length_field = self.length_field
688 if original_length_field is not None:
689 original_values = self._value
690
691 if len(values) != self.length_field:
692 if self.length_field is not None:
693 length_ft = self.length_field.field_type
694 else:
695 length_ft = bt2.IntegerFieldType(size=64, is_signed=False)
696 self.length_field = length_ft(len(values))
697
698 try:
699 for index, value in enumerate(values):
700 if value is not None:
701 self[index].value = value
702 else:
703 self[index].reset()
704 except:
705 if original_length_field is not None:
706 self.length_field = original_length_field
707 self.value = original_values
708 else:
709 self.reset()
710 raise
711
712 value = property(fset=_set_value)
81447b5b 713
0b03f63e 714
81447b5b 715_TYPE_ID_TO_OBJ = {
50842bdc
PP
716 native_bt.FIELD_TYPE_ID_INTEGER: _IntegerField,
717 native_bt.FIELD_TYPE_ID_FLOAT: _FloatingPointNumberField,
718 native_bt.FIELD_TYPE_ID_ENUM: _EnumerationField,
719 native_bt.FIELD_TYPE_ID_STRING: _StringField,
720 native_bt.FIELD_TYPE_ID_STRUCT: _StructureField,
721 native_bt.FIELD_TYPE_ID_ARRAY: _ArrayField,
722 native_bt.FIELD_TYPE_ID_SEQUENCE: _SequenceField,
723 native_bt.FIELD_TYPE_ID_VARIANT: _VariantField,
81447b5b 724}
This page took 0.062638 seconds and 4 git commands to generate.