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