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