bt2: remove unused import
[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
f0a42b33
FD
31def _create_field_from_ptr_template(
32 object_map, ptr, owner_ptr, owner_get_ref, owner_put_ref
33):
34
2ae9f48c 35 field_class_ptr = native_bt.field_borrow_class_const(ptr)
2ae9f48c 36 typeid = native_bt.field_class_get_type(field_class_ptr)
f0a42b33 37 field = object_map[typeid]._create_from_ptr_and_get_ref(
cfbd7cf3
FD
38 ptr, owner_ptr, owner_get_ref, owner_put_ref
39 )
81447b5b
PP
40 return field
41
42
f0a42b33
FD
43def _create_field_from_ptr(ptr, owner_ptr, owner_get_ref, owner_put_ref):
44 return _create_field_from_ptr_template(
45 _TYPE_ID_TO_OBJ, ptr, owner_ptr, owner_get_ref, owner_put_ref
46 )
47
48
49def _create_field_from_const_ptr(ptr, owner_ptr, owner_get_ref, owner_put_ref):
50 return _create_field_from_ptr_template(
51 _TYPE_ID_TO_CONST_OBJ, ptr, owner_ptr, owner_get_ref, owner_put_ref
52 )
53
54
cec0261d
PP
55# Get the "effective" field of `field`. If `field` is a variant, return
56# the currently selected field. If `field` is an option, return the
57# content field. If `field` is of any other type, return `field`
1eccc498 58# directly.
81447b5b 59
cfbd7cf3 60
1eccc498 61def _get_leaf_field(field):
f0a42b33 62 if isinstance(field, _VariantFieldConst):
cec0261d 63 return _get_leaf_field(field.selected_option)
1eccc498 64
f0a42b33 65 if isinstance(field, _OptionFieldConst):
cec0261d
PP
66 return _get_leaf_field(field.field)
67
68 return field
81447b5b 69
e1c6bebd 70
f0a42b33
FD
71class _FieldConst(object._UniqueObject):
72 _create_field_from_ptr = staticmethod(_create_field_from_const_ptr)
73 _create_field_class_from_ptr_and_get_ref = staticmethod(
74 bt2_field_class._create_field_class_from_const_ptr_and_get_ref
75 )
76 _borrow_class_ptr = staticmethod(native_bt.field_borrow_class_const)
77
1eccc498 78 def __eq__(self, other):
e1c6bebd
JG
79 other = _get_leaf_field(other)
80 return self._spec_eq(other)
81
81447b5b 82 @property
d8e2073c 83 def cls(self):
f0a42b33 84 field_class_ptr = self._borrow_class_ptr(self._ptr)
838a5a52 85 assert field_class_ptr is not None
f0a42b33 86 return self._create_field_class_from_ptr_and_get_ref(field_class_ptr)
81447b5b 87
12bf0d88
JG
88 def _repr(self):
89 raise NotImplementedError
90
91 def __repr__(self):
1eccc498 92 return self._repr()
12bf0d88 93
81447b5b 94
f0a42b33
FD
95class _Field(_FieldConst):
96 _create_field_from_ptr = staticmethod(_create_field_from_ptr)
97 _create_field_class_from_ptr_and_get_ref = staticmethod(
98 bt2_field_class._create_field_class_from_ptr_and_get_ref
99 )
100 _borrow_class_ptr = staticmethod(native_bt.field_borrow_class)
101
102
103class _BitArrayFieldConst(_FieldConst):
104 _NAME = 'Const bit array'
ead8c3d4
PP
105
106 @property
107 def value_as_integer(self):
108 return native_bt.field_bit_array_get_value_as_integer(self._ptr)
109
ead8c3d4
PP
110 def _spec_eq(self, other):
111 if type(other) is not type(self):
112 return False
113
114 return self.value_as_integer == other.value_as_integer
115
116 def _repr(self):
117 return repr(self.value_as_integer)
118
119 def __str__(self):
120 return str(self.value_as_integer)
121
122 def __len__(self):
d8e2073c 123 return self.cls.length
ead8c3d4
PP
124
125
f0a42b33
FD
126class _BitArrayField(_BitArrayFieldConst, _Field):
127 _NAME = 'Bit array'
128
129 def _value_as_integer(self, value):
130 utils._check_uint64(value)
131 native_bt.field_bit_array_set_value_as_integer(self._ptr, value)
132
133 value_as_integer = property(
134 fget=_BitArrayFieldConst.value_as_integer.fget, fset=_value_as_integer
135 )
136
137
81447b5b 138@functools.total_ordering
f0a42b33 139class _NumericFieldConst(_FieldConst):
81447b5b
PP
140 @staticmethod
141 def _extract_value(other):
f0a42b33 142 if isinstance(other, _BoolFieldConst) or isinstance(other, bool):
aae30e61 143 return bool(other)
81447b5b
PP
144
145 if isinstance(other, numbers.Integral):
146 return int(other)
147
148 if isinstance(other, numbers.Real):
149 return float(other)
150
151 if isinstance(other, numbers.Complex):
152 return complex(other)
153
cfbd7cf3
FD
154 raise TypeError(
155 "'{}' object is not a number object".format(other.__class__.__name__)
156 )
81447b5b
PP
157
158 def __int__(self):
e1c6bebd 159 return int(self._value)
81447b5b
PP
160
161 def __float__(self):
e1c6bebd 162 return float(self._value)
81447b5b 163
12bf0d88 164 def _repr(self):
5abb9e33 165 return repr(self._value)
81447b5b
PP
166
167 def __lt__(self, other):
168 if not isinstance(other, numbers.Number):
cfbd7cf3
FD
169 raise TypeError(
170 'unorderable types: {}() < {}()'.format(
171 self.__class__.__name__, other.__class__.__name__
172 )
173 )
81447b5b 174
09a926c1 175 return self._value < self._extract_value(other)
81447b5b 176
e1c6bebd 177 def _spec_eq(self, other):
f11ed062
PP
178 try:
179 return self._value == self._extract_value(other)
4c4935bf 180 except Exception:
f11ed062 181 return False
81447b5b 182
dda659b3
FD
183 def __hash__(self):
184 return hash(self._value)
185
81447b5b 186 def __rmod__(self, other):
e1c6bebd 187 return self._extract_value(other) % self._value
81447b5b
PP
188
189 def __mod__(self, other):
e1c6bebd 190 return self._value % self._extract_value(other)
81447b5b
PP
191
192 def __rfloordiv__(self, other):
e1c6bebd 193 return self._extract_value(other) // self._value
81447b5b
PP
194
195 def __floordiv__(self, other):
e1c6bebd 196 return self._value // self._extract_value(other)
81447b5b
PP
197
198 def __round__(self, ndigits=None):
199 if ndigits is None:
e1c6bebd 200 return round(self._value)
81447b5b 201 else:
e1c6bebd 202 return round(self._value, ndigits)
81447b5b
PP
203
204 def __ceil__(self):
e1c6bebd 205 return math.ceil(self._value)
81447b5b
PP
206
207 def __floor__(self):
e1c6bebd 208 return math.floor(self._value)
81447b5b
PP
209
210 def __trunc__(self):
e1c6bebd 211 return int(self._value)
81447b5b
PP
212
213 def __abs__(self):
e1c6bebd 214 return abs(self._value)
81447b5b
PP
215
216 def __add__(self, other):
e1c6bebd 217 return self._value + self._extract_value(other)
81447b5b
PP
218
219 def __radd__(self, other):
220 return self.__add__(other)
221
222 def __neg__(self):
e1c6bebd 223 return -self._value
81447b5b
PP
224
225 def __pos__(self):
e1c6bebd 226 return +self._value
81447b5b
PP
227
228 def __mul__(self, other):
e1c6bebd 229 return self._value * self._extract_value(other)
81447b5b
PP
230
231 def __rmul__(self, other):
232 return self.__mul__(other)
233
234 def __truediv__(self, other):
e1c6bebd 235 return self._value / self._extract_value(other)
81447b5b
PP
236
237 def __rtruediv__(self, other):
e1c6bebd 238 return self._extract_value(other) / self._value
81447b5b
PP
239
240 def __pow__(self, exponent):
e1c6bebd 241 return self._value ** self._extract_value(exponent)
81447b5b
PP
242
243 def __rpow__(self, base):
e1c6bebd 244 return self._extract_value(base) ** self._value
81447b5b 245
81447b5b 246
f0a42b33 247class _NumericField(_NumericFieldConst, _Field):
dda659b3
FD
248 def __hash__(self):
249 # Non const field are not hashable as their value may be modified
250 # without changing the underlying Python object.
251 raise TypeError('unhashable type: \'{}\''.format(self._NAME))
f0a42b33
FD
252
253
254class _IntegralFieldConst(_NumericFieldConst, numbers.Integral):
81447b5b 255 def __lshift__(self, other):
e1c6bebd 256 return self._value << self._extract_value(other)
81447b5b
PP
257
258 def __rlshift__(self, other):
e1c6bebd 259 return self._extract_value(other) << self._value
81447b5b
PP
260
261 def __rshift__(self, other):
e1c6bebd 262 return self._value >> self._extract_value(other)
81447b5b
PP
263
264 def __rrshift__(self, other):
e1c6bebd 265 return self._extract_value(other) >> self._value
81447b5b
PP
266
267 def __and__(self, other):
e1c6bebd 268 return self._value & self._extract_value(other)
81447b5b
PP
269
270 def __rand__(self, other):
e1c6bebd 271 return self._extract_value(other) & self._value
81447b5b
PP
272
273 def __xor__(self, other):
e1c6bebd 274 return self._value ^ self._extract_value(other)
81447b5b
PP
275
276 def __rxor__(self, other):
e1c6bebd 277 return self._extract_value(other) ^ self._value
81447b5b
PP
278
279 def __or__(self, other):
e1c6bebd 280 return self._value | self._extract_value(other)
81447b5b
PP
281
282 def __ror__(self, other):
e1c6bebd 283 return self._extract_value(other) | self._value
81447b5b
PP
284
285 def __invert__(self):
e1c6bebd 286 return ~self._value
81447b5b 287
81447b5b 288
f0a42b33
FD
289class _IntegralField(_IntegralFieldConst, _NumericField):
290 pass
291
292
293class _BoolFieldConst(_IntegralFieldConst, _FieldConst):
294 _NAME = 'Const boolean'
aae30e61
PP
295
296 def __bool__(self):
297 return self._value
298
f0a42b33
FD
299 @classmethod
300 def _value_to_bool(cls, value):
301 if isinstance(value, _BoolFieldConst):
aae30e61
PP
302 value = value._value
303
304 if not isinstance(value, bool):
305 raise TypeError(
f0a42b33 306 "'{}' object is not a 'bool', '_BoolFieldConst', or '_BoolField' object".format(
aae30e61
PP
307 value.__class__
308 )
309 )
310
311 return value
312
313 @property
314 def _value(self):
315 return bool(native_bt.field_bool_get_value(self._ptr))
316
f0a42b33
FD
317
318class _BoolField(_BoolFieldConst, _IntegralField, _Field):
319 _NAME = 'Boolean'
320
aae30e61
PP
321 def _set_value(self, value):
322 value = self._value_to_bool(value)
323 native_bt.field_bool_set_value(self._ptr, value)
324
325 value = property(fset=_set_value)
326
327
f0a42b33 328class _IntegerFieldConst(_IntegralFieldConst, _FieldConst):
81447b5b
PP
329 pass
330
331
f0a42b33
FD
332class _IntegerField(_IntegerFieldConst, _IntegralField, _Field):
333 pass
334
335
336class _UnsignedIntegerFieldConst(_IntegerFieldConst, _FieldConst):
337 _NAME = 'Const unsigned integer'
1eccc498 338
f0a42b33
FD
339 @classmethod
340 def _value_to_int(cls, value):
25bb9bab
PP
341 if not isinstance(value, numbers.Integral):
342 raise TypeError('expecting an integral number object')
81447b5b
PP
343
344 value = int(value)
2ae9f48c 345 utils._check_uint64(value)
81447b5b
PP
346
347 return value
348
349 @property
e1c6bebd 350 def _value(self):
9c08c816 351 return native_bt.field_integer_unsigned_get_value(self._ptr)
81447b5b 352
f0a42b33
FD
353
354class _UnsignedIntegerField(_UnsignedIntegerFieldConst, _IntegerField, _Field):
355 _NAME = 'Unsigned integer'
356
2ae9f48c
SM
357 def _set_value(self, value):
358 value = self._value_to_int(value)
9c08c816 359 native_bt.field_integer_unsigned_set_value(self._ptr, value)
2ae9f48c
SM
360
361 value = property(fset=_set_value)
362
363
f0a42b33
FD
364class _SignedIntegerFieldConst(_IntegerFieldConst, _FieldConst):
365 _NAME = 'Const signed integer'
1eccc498 366
f0a42b33
FD
367 @classmethod
368 def _value_to_int(cls, value):
25bb9bab
PP
369 if not isinstance(value, numbers.Integral):
370 raise TypeError('expecting an integral number object')
e1c6bebd 371
2ae9f48c
SM
372 value = int(value)
373 utils._check_int64(value)
811644b8 374
81447b5b
PP
375 return value
376
2ae9f48c
SM
377 @property
378 def _value(self):
9c08c816 379 return native_bt.field_integer_signed_get_value(self._ptr)
2ae9f48c 380
f0a42b33
FD
381
382class _SignedIntegerField(_SignedIntegerFieldConst, _IntegerField, _Field):
383 _NAME = 'Signed integer'
384
e1c6bebd 385 def _set_value(self, value):
81447b5b 386 value = self._value_to_int(value)
9c08c816 387 native_bt.field_integer_signed_set_value(self._ptr, value)
81447b5b 388
e1c6bebd 389 value = property(fset=_set_value)
81447b5b 390
0b03f63e 391
f0a42b33
FD
392class _RealFieldConst(_NumericFieldConst, numbers.Real):
393 _NAME = 'Const real'
81447b5b 394
f0a42b33
FD
395 @classmethod
396 def _value_to_float(cls, value):
81447b5b
PP
397 if not isinstance(value, numbers.Real):
398 raise TypeError("expecting a real number object")
399
400 return float(value)
401
402 @property
e1c6bebd 403 def _value(self):
2ae9f48c 404 return native_bt.field_real_get_value(self._ptr)
81447b5b 405
f0a42b33
FD
406
407class _RealField(_RealFieldConst, _NumericField):
408 _NAME = 'Real'
409
e1c6bebd 410 def _set_value(self, value):
81447b5b 411 value = self._value_to_float(value)
2ae9f48c 412 native_bt.field_real_set_value(self._ptr, value)
81447b5b 413
e1c6bebd 414 value = property(fset=_set_value)
81447b5b 415
0b03f63e 416
f0a42b33 417class _EnumerationFieldConst(_IntegerFieldConst):
1eccc498
SM
418 def _repr(self):
419 return '{} ({})'.format(self._value, ', '.join(self.labels))
81447b5b
PP
420
421 @property
1eccc498 422 def labels(self):
d24d5663 423 status, labels = self._get_mapping_labels(self._ptr)
cfbd7cf3 424 utils._handle_func_status(status, "cannot get label for enumeration field")
81447b5b 425
1eccc498
SM
426 assert labels is not None
427 return labels
81447b5b 428
4addd228 429
f0a42b33
FD
430class _EnumerationField(_EnumerationFieldConst, _IntegerField):
431 pass
432
433
434class _UnsignedEnumerationFieldConst(
435 _EnumerationFieldConst, _UnsignedIntegerFieldConst
436):
437 _NAME = 'Const unsigned Enumeration'
cfbd7cf3 438 _get_mapping_labels = staticmethod(
9c08c816 439 native_bt.field_enumeration_unsigned_get_mapping_labels
cfbd7cf3 440 )
e1c6bebd 441
e1c6bebd 442
f0a42b33
FD
443class _UnsignedEnumerationField(
444 _UnsignedEnumerationFieldConst, _EnumerationField, _UnsignedIntegerField
445):
446 _NAME = 'Unsigned enumeration'
447
448
449class _SignedEnumerationFieldConst(_EnumerationFieldConst, _SignedIntegerFieldConst):
450 _NAME = 'Const signed Enumeration'
cfbd7cf3 451 _get_mapping_labels = staticmethod(
9c08c816 452 native_bt.field_enumeration_signed_get_mapping_labels
cfbd7cf3 453 )
81447b5b
PP
454
455
f0a42b33
FD
456class _SignedEnumerationField(
457 _SignedEnumerationFieldConst, _EnumerationField, _SignedIntegerField
458):
459 _NAME = 'Signed enumeration'
460
461
81447b5b 462@functools.total_ordering
f0a42b33
FD
463class _StringFieldConst(_FieldConst):
464 _NAME = 'Const string'
81447b5b 465
f0a42b33
FD
466 @classmethod
467 def _value_to_str(cls, value):
468 if isinstance(value, _StringFieldConst):
e1c6bebd 469 value = value._value
81447b5b
PP
470
471 if not isinstance(value, str):
472 raise TypeError("expecting a 'str' object")
473
474 return value
475
476 @property
e1c6bebd 477 def _value(self):
1eccc498 478 return native_bt.field_string_get_value(self._ptr)
81447b5b 479
e1c6bebd 480 def _spec_eq(self, other):
81447b5b 481 try:
f11ed062 482 return self._value == self._value_to_str(other)
4c4935bf 483 except Exception:
81447b5b
PP
484 return False
485
81447b5b 486 def __lt__(self, other):
e1c6bebd 487 return self._value < self._value_to_str(other)
81447b5b
PP
488
489 def __bool__(self):
e1c6bebd 490 return bool(self._value)
81447b5b 491
dda659b3
FD
492 def __hash__(self):
493 return hash(self._value)
494
12bf0d88 495 def _repr(self):
d623d2e9
JG
496 return repr(self._value)
497
81447b5b 498 def __str__(self):
1eccc498 499 return str(self._value)
81447b5b
PP
500
501 def __getitem__(self, index):
e1c6bebd 502 return self._value[index]
81447b5b
PP
503
504 def __len__(self):
1eccc498 505 return native_bt.field_string_get_length(self._ptr)
81447b5b 506
f0a42b33
FD
507
508class _StringField(_StringFieldConst, _Field):
509 _NAME = 'String'
510
511 def _set_value(self, value):
512 value = self._value_to_str(value)
513 native_bt.field_string_set_value(self._ptr, value)
514
515 value = property(fset=_set_value)
516
81447b5b
PP
517 def __iadd__(self, value):
518 value = self._value_to_str(value)
d24d5663 519 status = native_bt.field_string_append(self._ptr, value)
cfbd7cf3
FD
520 utils._handle_func_status(
521 status, "cannot append to string field object's value"
522 )
81447b5b
PP
523 return self
524
dda659b3
FD
525 def __hash__(self):
526 # Non const field are not hashable as their value may be modified
527 # without changing the underlying Python object.
528 raise TypeError('unhashable type: \'{}\''.format(self._NAME))
529
81447b5b 530
f0a42b33 531class _ContainerFieldConst(_FieldConst):
81447b5b
PP
532 def __bool__(self):
533 return len(self) != 0
534
f0a42b33
FD
535 def _count(self):
536 return len(self.cls)
537
81447b5b
PP
538 def __len__(self):
539 count = self._count()
1eccc498 540 assert count >= 0
81447b5b
PP
541 return count
542
543 def __delitem__(self, index):
544 raise NotImplementedError
545
f0a42b33
FD
546 def __setitem__(self, index, value):
547 raise TypeError(
548 '\'{}\' object does not support item assignment'.format(self.__class__)
549 )
81447b5b 550
81447b5b 551
f0a42b33
FD
552class _ContainerField(_ContainerFieldConst, _Field):
553 pass
81447b5b 554
81447b5b 555
f0a42b33
FD
556class _StructureFieldConst(_ContainerFieldConst, collections.abc.Mapping):
557 _NAME = 'Const structure'
558 _borrow_member_field_ptr_by_index = staticmethod(
559 native_bt.field_structure_borrow_member_field_by_index_const
560 )
561 _borrow_member_field_ptr_by_name = staticmethod(
562 native_bt.field_structure_borrow_member_field_by_name_const
563 )
564
565 def _count(self):
566 return len(self.cls)
81447b5b 567
81447b5b
PP
568 def __iter__(self):
569 # same name iterator
d8e2073c 570 return iter(self.cls)
81447b5b 571
e1c6bebd 572 def _spec_eq(self, other):
f11ed062
PP
573 if not isinstance(other, collections.abc.Mapping):
574 return False
81447b5b 575
f11ed062
PP
576 if len(self) != len(other):
577 # early mismatch
578 return False
81447b5b 579
f11ed062
PP
580 for self_key in self:
581 if self_key not in other:
582 return False
81447b5b 583
f11ed062
PP
584 if self[self_key] != other[self_key]:
585 return False
e1c6bebd 586
f11ed062 587 return True
81447b5b 588
12bf0d88 589 def _repr(self):
ac7e2dc6
JG
590 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
591 return '{{{}}}'.format(', '.join(items))
592
1eccc498
SM
593 def __getitem__(self, key):
594 utils._check_str(key)
f0a42b33 595 field_ptr = self._borrow_member_field_ptr_by_name(self._ptr, key)
0b03f63e 596
1eccc498
SM
597 if field_ptr is None:
598 raise KeyError(key)
81447b5b 599
f0a42b33 600 return self._create_field_from_ptr(
cfbd7cf3
FD
601 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
602 )
811644b8 603
1eccc498
SM
604 def member_at_index(self, index):
605 utils._check_uint64(index)
811644b8 606
1eccc498
SM
607 if index >= len(self):
608 raise IndexError
f0a42b33 609 field_ptr = self._borrow_member_field_ptr_by_index(self._ptr, index)
1eccc498 610 assert field_ptr is not None
f0a42b33 611 return self._create_field_from_ptr(
cfbd7cf3
FD
612 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
613 )
1eccc498
SM
614
615
f0a42b33
FD
616class _StructureField(
617 _StructureFieldConst, _ContainerField, collections.abc.MutableMapping
618):
619 _NAME = 'Structure'
620 _borrow_member_field_ptr_by_index = staticmethod(
621 native_bt.field_structure_borrow_member_field_by_index
622 )
623 _borrow_member_field_ptr_by_name = staticmethod(
624 native_bt.field_structure_borrow_member_field_by_name
625 )
626
627 def __setitem__(self, key, value):
628 # raises if key is somehow invalid
629 field = self[key]
630
631 # the field's property does the appropriate conversion or raises
632 # the appropriate exception
633 field.value = value
634
635 def _set_value(self, values):
636 try:
637 for key, value in values.items():
638 self[key].value = value
639 except Exception:
640 raise
641
642 value = property(fset=_set_value)
643
644
645class _OptionFieldConst(_FieldConst):
646 _NAME = 'Const option'
647 _borrow_field_ptr = staticmethod(native_bt.field_option_borrow_field_const)
cec0261d
PP
648
649 @property
650 def field(self):
f0a42b33 651 field_ptr = self._borrow_field_ptr(self._ptr)
cec0261d
PP
652
653 if field_ptr is None:
654 return
655
f0a42b33 656 return self._create_field_from_ptr(
cec0261d
PP
657 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
658 )
659
660 @property
661 def has_field(self):
662 return self.field is not None
663
cec0261d
PP
664 def _spec_eq(self, other):
665 return _get_leaf_field(self) == other
666
667 def __bool__(self):
668 return self.has_field
669
670 def __str__(self):
671 return str(self.field)
672
673 def _repr(self):
674 return repr(self.field)
675
f0a42b33
FD
676
677class _OptionField(_OptionFieldConst, _Field):
678 _NAME = 'Option'
679 _borrow_field_ptr = staticmethod(native_bt.field_option_borrow_field)
680
681 def _has_field(self, value):
682 utils._check_bool(value)
683 native_bt.field_option_set_has_field(self._ptr, value)
684
685 has_field = property(fget=_OptionFieldConst.has_field.fget, fset=_has_field)
686
cec0261d
PP
687 def _set_value(self, value):
688 self.has_field = True
689 field = self.field
690 assert field is not None
691 field.value = value
692
693 value = property(fset=_set_value)
694
695
f0a42b33
FD
696class _VariantFieldConst(_ContainerFieldConst, _FieldConst):
697 _NAME = 'Const variant'
698 _borrow_selected_option_field_ptr = staticmethod(
699 native_bt.field_variant_borrow_selected_option_field_const
700 )
81447b5b 701
2b9aa00b
FD
702 def _count(self):
703 return len(self.cls)
704
81447b5b 705 @property
1eccc498
SM
706 def selected_option_index(self):
707 return native_bt.field_variant_get_selected_option_field_index(self._ptr)
81447b5b 708
1eccc498
SM
709 @property
710 def selected_option(self):
5ae9f1bf
SM
711 # TODO: Is there a way to check if the variant field has a selected_option,
712 # so we can raise an exception instead of hitting a pre-condition check?
713 # If there is something, that check should be added to selected_option_index too.
f0a42b33 714 field_ptr = self._borrow_selected_option_field_ptr(self._ptr)
81447b5b 715
f0a42b33 716 return self._create_field_from_ptr(
cfbd7cf3
FD
717 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
718 )
81447b5b 719
e1c6bebd 720 def _spec_eq(self, other):
f11ed062 721 return _get_leaf_field(self) == other
811644b8
PP
722
723 def __bool__(self):
1eccc498 724 raise NotImplementedError
81447b5b 725
12bf0d88 726 def __str__(self):
1eccc498 727 return str(self.selected_option)
12bf0d88
JG
728
729 def _repr(self):
1eccc498 730 return repr(self.selected_option)
e1c6bebd 731
f0a42b33
FD
732
733class _VariantField(_VariantFieldConst, _ContainerField, _Field):
734 _NAME = 'Variant'
735 _borrow_selected_option_field_ptr = staticmethod(
736 native_bt.field_variant_borrow_selected_option_field
737 )
738
739 def _selected_option_index(self, index):
740 if index < 0 or index >= len(self):
741 raise IndexError('{} field object index is out of range'.format(self._NAME))
742
743 native_bt.field_variant_select_option_field_by_index(self._ptr, index)
744
745 selected_option_index = property(
746 fget=_VariantFieldConst.selected_option_index.fget, fset=_selected_option_index
747 )
748
e1c6bebd 749 def _set_value(self, value):
1eccc498 750 self.selected_option.value = value
e1c6bebd
JG
751
752 value = property(fset=_set_value)
81447b5b 753
0b03f63e 754
f0a42b33
FD
755class _ArrayFieldConst(_ContainerFieldConst, _FieldConst, collections.abc.Sequence):
756 _borrow_element_field_ptr_by_index = staticmethod(
757 native_bt.field_array_borrow_element_field_by_index_const
758 )
759
1eccc498
SM
760 def _get_length(self):
761 return native_bt.field_array_get_length(self._ptr)
762
763 length = property(fget=_get_length)
764
81447b5b
PP
765 def __getitem__(self, index):
766 if not isinstance(index, numbers.Integral):
cfbd7cf3
FD
767 raise TypeError(
768 "'{}' is not an integral number object: invalid index".format(
769 index.__class__.__name__
770 )
771 )
81447b5b
PP
772
773 index = int(index)
774
775 if index < 0 or index >= len(self):
776 raise IndexError('{} field object index is out of range'.format(self._NAME))
777
f0a42b33 778 field_ptr = self._borrow_element_field_ptr_by_index(self._ptr, index)
cfbd7cf3 779 assert field_ptr
f0a42b33 780 return self._create_field_from_ptr(
cfbd7cf3
FD
781 field_ptr, self._owner_ptr, self._owner_get_ref, self._owner_put_ref
782 )
81447b5b 783
81447b5b
PP
784 def insert(self, index, value):
785 raise NotImplementedError
786
e1c6bebd 787 def _spec_eq(self, other):
f11ed062
PP
788 if not isinstance(other, collections.abc.Sequence):
789 return False
7c54e2e7 790
f11ed062
PP
791 if len(self) != len(other):
792 # early mismatch
e1c6bebd 793 return False
7c54e2e7 794
f11ed062
PP
795 for self_elem, other_elem in zip(self, other):
796 if self_elem != other_elem:
797 return False
798
799 return True
800
12bf0d88 801 def _repr(self):
2bc21382
JG
802 return '[{}]'.format(', '.join([repr(v) for v in self]))
803
81447b5b 804
f0a42b33
FD
805class _ArrayField(
806 _ArrayFieldConst, _ContainerField, _Field, collections.abc.MutableSequence
807):
808 _borrow_element_field_ptr_by_index = staticmethod(
809 native_bt.field_array_borrow_element_field_by_index
810 )
811
812 def __setitem__(self, index, value):
813 # raises if index is somehow invalid
814 field = self[index]
815
816 if not isinstance(field, (_NumericField, _StringField)):
817 raise TypeError('can only set the value of a number or string field')
818
819 # the field's property does the appropriate conversion or raises
820 # the appropriate exception
821 field.value = value
822
823
824class _StaticArrayFieldConst(_ArrayFieldConst, _FieldConst):
825 _NAME = 'Const static array'
81447b5b
PP
826
827 def _count(self):
1eccc498 828 return native_bt.field_array_get_length(self._ptr)
81447b5b 829
f0a42b33
FD
830
831class _StaticArrayField(_StaticArrayFieldConst, _ArrayField, _Field):
832 _NAME = 'Static array'
833
e1c6bebd
JG
834 def _set_value(self, values):
835 if len(self) != len(values):
cfbd7cf3 836 raise ValueError('expected length of value and array field to match')
e1c6bebd 837
1eccc498
SM
838 for index, value in enumerate(values):
839 if value is not None:
840 self[index].value = value
e1c6bebd
JG
841
842 value = property(fset=_set_value)
843
81447b5b 844
f0a42b33
FD
845class _DynamicArrayFieldConst(_ArrayFieldConst, _FieldConst):
846 _NAME = 'Const dynamic array'
81447b5b
PP
847
848 def _count(self):
1eccc498 849 return self.length
81447b5b 850
f0a42b33
FD
851
852class _DynamicArrayField(_DynamicArrayFieldConst, _ArrayField, _Field):
853 _NAME = 'Dynamic array'
854
1eccc498
SM
855 def _set_length(self, length):
856 utils._check_uint64(length)
9c08c816 857 status = native_bt.field_array_dynamic_set_length(self._ptr, length)
d24d5663 858 utils._handle_func_status(status, "cannot set dynamic array length")
81447b5b 859
1eccc498 860 length = property(fget=_ArrayField._get_length, fset=_set_length)
81447b5b 861
e1c6bebd 862 def _set_value(self, values):
1eccc498
SM
863 if len(values) != self.length:
864 self.length = len(values)
e1c6bebd 865
1eccc498
SM
866 for index, value in enumerate(values):
867 if value is not None:
868 self[index].value = value
e1c6bebd
JG
869
870 value = property(fset=_set_value)
81447b5b 871
0b03f63e 872
f0a42b33
FD
873_TYPE_ID_TO_CONST_OBJ = {
874 native_bt.FIELD_CLASS_TYPE_BOOL: _BoolFieldConst,
875 native_bt.FIELD_CLASS_TYPE_BIT_ARRAY: _BitArrayFieldConst,
876 native_bt.FIELD_CLASS_TYPE_UNSIGNED_INTEGER: _UnsignedIntegerFieldConst,
877 native_bt.FIELD_CLASS_TYPE_SIGNED_INTEGER: _SignedIntegerFieldConst,
878 native_bt.FIELD_CLASS_TYPE_REAL: _RealFieldConst,
879 native_bt.FIELD_CLASS_TYPE_UNSIGNED_ENUMERATION: _UnsignedEnumerationFieldConst,
880 native_bt.FIELD_CLASS_TYPE_SIGNED_ENUMERATION: _SignedEnumerationFieldConst,
881 native_bt.FIELD_CLASS_TYPE_STRING: _StringFieldConst,
882 native_bt.FIELD_CLASS_TYPE_STRUCTURE: _StructureFieldConst,
883 native_bt.FIELD_CLASS_TYPE_STATIC_ARRAY: _StaticArrayFieldConst,
884 native_bt.FIELD_CLASS_TYPE_DYNAMIC_ARRAY: _DynamicArrayFieldConst,
885 native_bt.FIELD_CLASS_TYPE_OPTION: _OptionFieldConst,
886 native_bt.FIELD_CLASS_TYPE_VARIANT_WITHOUT_SELECTOR: _VariantFieldConst,
887 native_bt.FIELD_CLASS_TYPE_VARIANT_WITH_UNSIGNED_SELECTOR: _VariantFieldConst,
888 native_bt.FIELD_CLASS_TYPE_VARIANT_WITH_SIGNED_SELECTOR: _VariantFieldConst,
889}
890
81447b5b 891_TYPE_ID_TO_OBJ = {
aae30e61 892 native_bt.FIELD_CLASS_TYPE_BOOL: _BoolField,
ead8c3d4 893 native_bt.FIELD_CLASS_TYPE_BIT_ARRAY: _BitArrayField,
2ae9f48c
SM
894 native_bt.FIELD_CLASS_TYPE_UNSIGNED_INTEGER: _UnsignedIntegerField,
895 native_bt.FIELD_CLASS_TYPE_SIGNED_INTEGER: _SignedIntegerField,
896 native_bt.FIELD_CLASS_TYPE_REAL: _RealField,
1eccc498
SM
897 native_bt.FIELD_CLASS_TYPE_UNSIGNED_ENUMERATION: _UnsignedEnumerationField,
898 native_bt.FIELD_CLASS_TYPE_SIGNED_ENUMERATION: _SignedEnumerationField,
2ae9f48c
SM
899 native_bt.FIELD_CLASS_TYPE_STRING: _StringField,
900 native_bt.FIELD_CLASS_TYPE_STRUCTURE: _StructureField,
1eccc498
SM
901 native_bt.FIELD_CLASS_TYPE_STATIC_ARRAY: _StaticArrayField,
902 native_bt.FIELD_CLASS_TYPE_DYNAMIC_ARRAY: _DynamicArrayField,
cec0261d 903 native_bt.FIELD_CLASS_TYPE_OPTION: _OptionField,
45c51519
PP
904 native_bt.FIELD_CLASS_TYPE_VARIANT_WITHOUT_SELECTOR: _VariantField,
905 native_bt.FIELD_CLASS_TYPE_VARIANT_WITH_UNSIGNED_SELECTOR: _VariantField,
906 native_bt.FIELD_CLASS_TYPE_VARIANT_WITH_SIGNED_SELECTOR: _VariantField,
81447b5b 907}
This page took 0.102401 seconds and 4 git commands to generate.