bt2: remove unused imports
[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, bool):
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(
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 _IntegerField(_IntegralField, _Field):
212 pass
213
214
215 class _UnsignedIntegerField(_IntegerField, _Field):
216 _NAME = 'Unsigned integer'
217
218 def _value_to_int(self, value):
219 if not isinstance(value, numbers.Integral):
220 raise TypeError('expecting an integral number object')
221
222 value = int(value)
223 utils._check_uint64(value)
224
225 return value
226
227 @property
228 def _value(self):
229 return native_bt.field_integer_unsigned_get_value(self._ptr)
230
231 def _set_value(self, value):
232 value = self._value_to_int(value)
233 native_bt.field_integer_unsigned_set_value(self._ptr, value)
234
235 value = property(fset=_set_value)
236
237
238 class _SignedIntegerField(_IntegerField, _Field):
239 _NAME = 'Signed integer'
240
241 def _value_to_int(self, value):
242 if not isinstance(value, numbers.Integral):
243 raise TypeError('expecting an integral number object')
244
245 value = int(value)
246 utils._check_int64(value)
247
248 return value
249
250 @property
251 def _value(self):
252 return native_bt.field_integer_signed_get_value(self._ptr)
253
254 def _set_value(self, value):
255 value = self._value_to_int(value)
256 native_bt.field_integer_signed_set_value(self._ptr, value)
257
258 value = property(fset=_set_value)
259
260
261 class _RealField(_NumericField, numbers.Real):
262 _NAME = 'Real'
263
264 def _value_to_float(self, value):
265 if not isinstance(value, numbers.Real):
266 raise TypeError("expecting a real number object")
267
268 return float(value)
269
270 @property
271 def _value(self):
272 return native_bt.field_real_get_value(self._ptr)
273
274 def _set_value(self, value):
275 value = self._value_to_float(value)
276 native_bt.field_real_set_value(self._ptr, value)
277
278 value = property(fset=_set_value)
279
280
281 class _EnumerationField(_IntegerField):
282 def _repr(self):
283 return '{} ({})'.format(self._value, ', '.join(self.labels))
284
285 @property
286 def labels(self):
287 status, labels = self._get_mapping_labels(self._ptr)
288 utils._handle_func_status(status, "cannot get label for enumeration field")
289
290 assert labels is not None
291 return labels
292
293
294 class _UnsignedEnumerationField(_EnumerationField, _UnsignedIntegerField):
295 _NAME = 'Unsigned Enumeration'
296 _get_mapping_labels = staticmethod(
297 native_bt.field_enumeration_unsigned_get_mapping_labels
298 )
299
300
301 class _SignedEnumerationField(_EnumerationField, _SignedIntegerField):
302 _NAME = 'Signed Enumeration'
303 _get_mapping_labels = staticmethod(
304 native_bt.field_enumeration_signed_get_mapping_labels
305 )
306
307
308 @functools.total_ordering
309 class _StringField(_Field):
310 _NAME = 'String'
311
312 def _value_to_str(self, value):
313 if isinstance(value, self.__class__):
314 value = value._value
315
316 if not isinstance(value, str):
317 raise TypeError("expecting a 'str' object")
318
319 return value
320
321 @property
322 def _value(self):
323 return native_bt.field_string_get_value(self._ptr)
324
325 def _set_value(self, value):
326 value = self._value_to_str(value)
327 native_bt.field_string_set_value(self._ptr, value)
328
329 value = property(fset=_set_value)
330
331 def _spec_eq(self, other):
332 try:
333 return self._value == self._value_to_str(other)
334 except:
335 return False
336
337 def __lt__(self, other):
338 return self._value < self._value_to_str(other)
339
340 def __bool__(self):
341 return bool(self._value)
342
343 def _repr(self):
344 return repr(self._value)
345
346 def __str__(self):
347 return str(self._value)
348
349 def __getitem__(self, index):
350 return self._value[index]
351
352 def __len__(self):
353 return native_bt.field_string_get_length(self._ptr)
354
355 def __iadd__(self, value):
356 value = self._value_to_str(value)
357 status = native_bt.field_string_append(self._ptr, value)
358 utils._handle_func_status(
359 status, "cannot append to string field object's value"
360 )
361 return self
362
363
364 class _ContainerField(_Field):
365 def __bool__(self):
366 return len(self) != 0
367
368 def __len__(self):
369 count = self._count()
370 assert count >= 0
371 return count
372
373 def __delitem__(self, index):
374 raise NotImplementedError
375
376
377 class _StructureField(_ContainerField, collections.abc.MutableMapping):
378 _NAME = 'Structure'
379
380 def _count(self):
381 return len(self.field_class)
382
383 def __setitem__(self, key, value):
384 # raises if key is somehow invalid
385 field = self[key]
386
387 # the field's property does the appropriate conversion or raises
388 # the appropriate exception
389 field.value = value
390
391 def __iter__(self):
392 # same name iterator
393 return iter(self.field_class)
394
395 def _spec_eq(self, other):
396 if not isinstance(other, collections.abc.Mapping):
397 return False
398
399 if len(self) != len(other):
400 # early mismatch
401 return False
402
403 for self_key in self:
404 if self_key not in other:
405 return False
406
407 if self[self_key] != other[self_key]:
408 return False
409
410 return True
411
412 def _set_value(self, values):
413 try:
414 for key, value in values.items():
415 self[key].value = value
416 except Exception:
417 raise
418
419 value = property(fset=_set_value)
420
421 def _repr(self):
422 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
423 return '{{{}}}'.format(', '.join(items))
424
425 def __getitem__(self, key):
426 utils._check_str(key)
427 field_ptr = native_bt.field_structure_borrow_member_field_by_name(
428 self._ptr, key
429 )
430
431 if field_ptr is None:
432 raise KeyError(key)
433
434 return _create_field_from_ptr(
435 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
436 )
437
438 def member_at_index(self, index):
439 utils._check_uint64(index)
440
441 if index >= len(self):
442 raise IndexError
443
444 field_ptr = native_bt.field_structure_borrow_member_field_by_index(
445 self._ptr, index
446 )
447 assert field_ptr is not None
448 return _create_field_from_ptr(
449 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
450 )
451
452
453 class _VariantField(_ContainerField, _Field):
454 _NAME = 'Variant'
455
456 @property
457 def selected_option_index(self):
458 return native_bt.field_variant_get_selected_option_field_index(self._ptr)
459
460 @selected_option_index.setter
461 def selected_option_index(self, index):
462 native_bt.field_variant_select_option_field_by_index(self._ptr, index)
463
464 @property
465 def selected_option(self):
466 # TODO: Is there a way to check if the variant field has a selected_option,
467 # so we can raise an exception instead of hitting a pre-condition check?
468 # If there is something, that check should be added to selected_option_index too.
469 field_ptr = native_bt.field_variant_borrow_selected_option_field(self._ptr)
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_array_dynamic_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.042643 seconds and 5 git commands to generate.