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