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