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