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