bt2: Adapt test_field.py and make it pass
[babeltrace.git] / 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 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 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 other is True or other is False:
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):
89 return int(self._value)
90
91 def __float__(self):
92 return float(self._value)
93
94 def _repr(self):
95 return repr(self._value)
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
102 return self._value < float(other)
103
104 def __le__(self, other):
105 if not isinstance(other, numbers.Number):
106 raise TypeError('unorderable types: {}() <= {}()'.format(self.__class__.__name__,
107 other.__class__.__name__))
108
109 return self._value <= float(other)
110
111 def _spec_eq(self, other):
112 if not isinstance(other, numbers.Number):
113 return NotImplemented
114
115 return self._value == complex(other)
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 def __iadd__(self, other):
178 self.value = self + other
179 return self
180
181 def __isub__(self, other):
182 self.value = self - other
183 return self
184
185 def __imul__(self, other):
186 self.value = self * other
187 return self
188
189 def __itruediv__(self, other):
190 self.value = self / other
191 return self
192
193 def __ifloordiv__(self, other):
194 self.value = self // other
195 return self
196
197 def __imod__(self, other):
198 self.value = self % other
199 return self
200
201 def __ipow__(self, other):
202 self.value = self ** other
203 return self
204
205
206 class _IntegralField(_NumericField, numbers.Integral):
207 def __lshift__(self, other):
208 return self._value << self._extract_value(other)
209
210 def __rlshift__(self, other):
211 return self._extract_value(other) << self._value
212
213 def __rshift__(self, other):
214 return self._value >> self._extract_value(other)
215
216 def __rrshift__(self, other):
217 return self._extract_value(other) >> self._value
218
219 def __and__(self, other):
220 return self._value & self._extract_value(other)
221
222 def __rand__(self, other):
223 return self._extract_value(other) & self._value
224
225 def __xor__(self, other):
226 return self._value ^ self._extract_value(other)
227
228 def __rxor__(self, other):
229 return self._extract_value(other) ^ self._value
230
231 def __or__(self, other):
232 return self._value | self._extract_value(other)
233
234 def __ror__(self, other):
235 return self._extract_value(other) | self._value
236
237 def __invert__(self):
238 return ~self._value
239
240 def __ilshift__(self, other):
241 self.value = self << other
242 return self
243
244 def __irshift__(self, other):
245 self.value = self >> other
246 return self
247
248 def __iand__(self, other):
249 self.value = self & other
250 return self
251
252 def __ixor__(self, other):
253 self.value = self ^ other
254 return self
255
256 def __ior__(self, other):
257 self.value = self | other
258 return self
259
260
261 class _IntegerField(_IntegralField, _Field):
262 pass
263
264
265 class _UnsignedIntegerField(_IntegerField, _Field):
266 _NAME = 'Unsigned integer'
267
268 def _value_to_int(self, value):
269 if not isinstance(value, numbers.Real):
270 raise TypeError('expecting a real number object')
271
272 value = int(value)
273 utils._check_uint64(value)
274
275 return value
276
277 @property
278 def _value(self):
279 return native_bt.field_unsigned_integer_get_value(self._ptr)
280
281 def _set_value(self, value):
282 value = self._value_to_int(value)
283 native_bt.field_unsigned_integer_set_value(self._ptr, value)
284
285 value = property(fset=_set_value)
286
287
288 class _SignedIntegerField(_IntegerField, _Field):
289 _NAME = 'Signed integer'
290
291 def _value_to_int(self, value):
292 if not isinstance(value, numbers.Real):
293 raise TypeError('expecting a real number object')
294
295 value = int(value)
296 utils._check_int64(value)
297
298 return value
299
300 @property
301 def _value(self):
302 return native_bt.field_signed_integer_get_value(self._ptr)
303
304 def _set_value(self, value):
305 value = self._value_to_int(value)
306 native_bt.field_signed_integer_set_value(self._ptr, value)
307
308 value = property(fset=_set_value)
309
310
311 class _RealField(_NumericField, numbers.Real):
312 _NAME = 'Real'
313
314 def _value_to_float(self, value):
315 if not isinstance(value, numbers.Real):
316 raise TypeError("expecting a real number object")
317
318 return float(value)
319
320 @property
321 def _value(self):
322 return native_bt.field_real_get_value(self._ptr)
323
324 def _set_value(self, value):
325 value = self._value_to_float(value)
326 native_bt.field_real_set_value(self._ptr, value)
327
328 value = property(fset=_set_value)
329
330
331 class _EnumerationField(_IntegerField):
332 def _repr(self):
333 return '{} ({})'.format(self._value, ', '.join(self.labels))
334
335 @property
336 def labels(self):
337 ret, labels = self._get_mapping_labels(self._ptr)
338 utils._handle_ret(ret, "cannot get label for enumeration field")
339
340 assert labels is not None
341 return labels
342
343
344 class _UnsignedEnumerationField(_EnumerationField, _UnsignedIntegerField):
345 _NAME = 'Unsigned Enumeration'
346 _get_mapping_labels = staticmethod(native_bt.field_unsigned_enumeration_get_mapping_labels)
347
348
349 class _SignedEnumerationField(_EnumerationField, _SignedIntegerField):
350 _NAME = 'Signed Enumeration'
351 _get_mapping_labels = staticmethod(native_bt.field_signed_enumeration_get_mapping_labels)
352
353
354 @functools.total_ordering
355 class _StringField(_Field):
356 _NAME = 'String'
357
358 def _value_to_str(self, value):
359 if isinstance(value, self.__class__):
360 value = value._value
361
362 if not isinstance(value, str):
363 raise TypeError("expecting a 'str' object")
364
365 return value
366
367 @property
368 def _value(self):
369 return native_bt.field_string_get_value(self._ptr)
370
371 def _set_value(self, value):
372 value = self._value_to_str(value)
373 native_bt.field_string_set_value(self._ptr, value)
374
375 value = property(fset=_set_value)
376
377 def _spec_eq(self, other):
378 try:
379 other = self._value_to_str(other)
380 except Exception:
381 return False
382
383 return self._value == other
384
385 def __le__(self, other):
386 return self._value <= self._value_to_str(other)
387
388 def __lt__(self, other):
389 return self._value < self._value_to_str(other)
390
391 def __bool__(self):
392 return bool(self._value)
393
394 def _repr(self):
395 return repr(self._value)
396
397 def __str__(self):
398 return str(self._value)
399
400 def __getitem__(self, index):
401 return self._value[index]
402
403 def __len__(self):
404 return native_bt.field_string_get_length(self._ptr)
405
406 def __iadd__(self, value):
407 value = self._value_to_str(value)
408 ret = native_bt.field_string_append(self._ptr, value)
409 utils._handle_ret(ret, "cannot append to string field object's value")
410 return self
411
412
413 class _ContainerField(_Field):
414 def __bool__(self):
415 return len(self) != 0
416
417 def __len__(self):
418 count = self._count()
419 assert count >= 0
420 return count
421
422 def __delitem__(self, index):
423 raise NotImplementedError
424
425
426 class _StructureField(_ContainerField, collections.abc.MutableMapping):
427 _NAME = 'Structure'
428
429 def _count(self):
430 return len(self.field_class)
431
432 def __setitem__(self, key, value):
433 # raises if key is somehow invalid
434 field = self[key]
435
436 # the field's property does the appropriate conversion or raises
437 # the appropriate exception
438 field.value = value
439
440 def __iter__(self):
441 # same name iterator
442 return iter(self.field_class)
443
444 def _spec_eq(self, other):
445 try:
446 if len(self) != len(other):
447 return False
448
449 for self_key, self_value in self.items():
450 if self_key not in other:
451 return False
452
453 other_value = other[self_key]
454
455 if self_value != other_value:
456 return False
457
458 return True
459 except Exception:
460 return False
461
462 def _set_value(self, values):
463 try:
464 for key, value in values.items():
465 self[key].value = value
466 except Exception:
467 raise
468
469 value = property(fset=_set_value)
470
471 def _repr(self):
472 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
473 return '{{{}}}'.format(', '.join(items))
474
475 def __getitem__(self, key):
476 utils._check_str(key)
477 field_ptr = native_bt.field_structure_borrow_member_field_by_name(self._ptr, key)
478
479 if field_ptr is None:
480 raise KeyError(key)
481
482 return _create_field_from_ptr(field_ptr, self._owner_ptr,
483 self._owner_get_ref,
484 self._owner_put_ref)
485
486 def member_at_index(self, index):
487 utils._check_uint64(index)
488
489 if index >= len(self):
490 raise IndexError
491
492 field_ptr = native_bt.field_structure_borrow_member_field_by_index(self._ptr, index)
493 assert field_ptr is not None
494 return _create_field_from_ptr(field_ptr, self._owner_ptr,
495 self._owner_get_ref,
496 self._owner_put_ref)
497
498
499 class _VariantField(_ContainerField, _Field):
500 _NAME = 'Variant'
501
502 @property
503 def selected_option_index(self):
504 return native_bt.field_variant_get_selected_option_field_index(self._ptr)
505
506 @selected_option_index.setter
507 def selected_option_index(self, index):
508 native_bt.field_variant_select_option_field(self._ptr, index)
509
510 @property
511 def selected_option(self):
512 field_ptr = native_bt.field_variant_borrow_selected_option_field(self._ptr)
513 utils._handle_ptr(field_ptr, "cannot get variant field's selected option")
514
515 return _create_field_from_ptr(field_ptr, self._owner_ptr,
516 self._owner_get_ref,
517 self._owner_put_ref)
518
519 def _spec_eq(self, other):
520 new_self = _get_leaf_field(self)
521 return new_self == other
522
523 def __bool__(self):
524 raise NotImplementedError
525
526 def __str__(self):
527 return str(self.selected_option)
528
529 def _repr(self):
530 return repr(self.selected_option)
531
532 def _set_value(self, value):
533 self.selected_option.value = value
534
535 value = property(fset=_set_value)
536
537
538 class _ArrayField(_ContainerField, _Field):
539
540 def _get_length(self):
541 return native_bt.field_array_get_length(self._ptr)
542
543 length = property(fget=_get_length)
544
545 def __getitem__(self, index):
546 if not isinstance(index, numbers.Integral):
547 raise TypeError("'{}' is not an integral number object: invalid index".format(index.__class__.__name__))
548
549 index = int(index)
550
551 if index < 0 or index >= len(self):
552 raise IndexError('{} field object index is out of range'.format(self._NAME))
553
554 field_ptr = native_bt.field_array_borrow_element_field_by_index(self._ptr, index)
555 assert(field_ptr)
556 return _create_field_from_ptr(field_ptr, self._owner_ptr,
557 self._owner_get_ref,
558 self._owner_put_ref)
559
560 def __setitem__(self, index, value):
561 # we can only set numbers and strings
562 if not isinstance(value, (numbers.Number, _StringField, str)):
563 raise TypeError('expecting number or string object')
564
565 # raises if index is somehow invalid
566 field = self[index]
567
568 if not isinstance(field, (_NumericField, _StringField)):
569 raise TypeError('can only set the value of a number or string field')
570
571 # the field's property does the appropriate conversion or raises
572 # the appropriate exception
573 field.value = value
574
575 def insert(self, index, value):
576 raise NotImplementedError
577
578 def _spec_eq(self, other):
579 try:
580 if len(self) != len(other):
581 return False
582
583 for self_field, other_field in zip(self, other):
584 if self_field != other_field:
585 return False
586
587 return True
588 except Exception:
589 return False
590
591 def _repr(self):
592 return '[{}]'.format(', '.join([repr(v) for v in self]))
593
594
595 class _StaticArrayField(_ArrayField, _Field):
596 _NAME = 'Static array'
597
598 def _count(self):
599 return native_bt.field_array_get_length(self._ptr)
600
601 def _set_value(self, values):
602 if len(self) != len(values):
603 raise ValueError(
604 'expected length of value and array field to match')
605
606 for index, value in enumerate(values):
607 if value is not None:
608 self[index].value = value
609
610 value = property(fset=_set_value)
611
612
613 class _DynamicArrayField(_ArrayField, _Field):
614 _NAME = 'Dynamic array'
615
616 def _count(self):
617 return self.length
618
619 def _set_length(self, length):
620 utils._check_uint64(length)
621 ret = native_bt.field_dynamic_array_set_length(self._ptr, length)
622 utils._handle_ret(ret, "cannot set dynamic array length")
623
624 length = property(fget=_ArrayField._get_length, fset=_set_length)
625
626 def _set_value(self, values):
627 if len(values) != self.length:
628 self.length = len(values)
629
630 for index, value in enumerate(values):
631 if value is not None:
632 self[index].value = value
633
634 value = property(fset=_set_value)
635
636
637 _TYPE_ID_TO_OBJ = {
638 native_bt.FIELD_CLASS_TYPE_UNSIGNED_INTEGER: _UnsignedIntegerField,
639 native_bt.FIELD_CLASS_TYPE_SIGNED_INTEGER: _SignedIntegerField,
640 native_bt.FIELD_CLASS_TYPE_REAL: _RealField,
641 native_bt.FIELD_CLASS_TYPE_UNSIGNED_ENUMERATION: _UnsignedEnumerationField,
642 native_bt.FIELD_CLASS_TYPE_SIGNED_ENUMERATION: _SignedEnumerationField,
643 native_bt.FIELD_CLASS_TYPE_STRING: _StringField,
644 native_bt.FIELD_CLASS_TYPE_STRUCTURE: _StructureField,
645 native_bt.FIELD_CLASS_TYPE_STATIC_ARRAY: _StaticArrayField,
646 native_bt.FIELD_CLASS_TYPE_DYNAMIC_ARRAY: _DynamicArrayField,
647 native_bt.FIELD_CLASS_TYPE_VARIANT: _VariantField,
648 }
This page took 0.043579 seconds and 5 git commands to generate.