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