Add Babeltrace 2 Python bindings
[babeltrace.git] / bindings / python / bt2 / fields.py
CommitLineData
81447b5b
PP
1# The MIT License (MIT)
2#
3# Copyright (c) 2016 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
23from bt2 import native_bt, object, utils
24import bt2.field_types
25import collections.abc
26import functools
27import numbers
28import math
29import abc
30import bt2
31
32
33def _create_from_ptr(ptr):
34 # recreate the field type wrapper of this field's type (the identity
35 # could be different, but the underlying address should be the
36 # same)
37 field_type_ptr = native_bt.ctf_field_get_type(ptr)
38 utils._handle_ptr(field_type_ptr, "cannot get field object's type")
39 field_type = bt2.field_types._create_from_ptr(field_type_ptr)
40 typeid = native_bt.ctf_field_type_get_type_id(field_type._ptr)
41 field = _TYPE_ID_TO_OBJ[typeid]._create_from_ptr(ptr)
42 field._field_type = field_type
43 return field
44
45
46class _Field(object._Object, metaclass=abc.ABCMeta):
47 def __copy__(self):
48 ptr = native_bt.ctf_field_copy(self._ptr)
49 utils._handle_ptr(ptr, 'cannot copy {} field object'.format(self._NAME.lower()))
50 return _create_from_ptr(ptr)
51
52 def __deepcopy__(self, memo):
53 cpy = self.__copy__()
54 memo[id(self)] = cpy
55 return cpy
56
57 @property
58 def field_type(self):
59 return self._field_type
60
61
62@functools.total_ordering
63class _NumericField(_Field):
64 @staticmethod
65 def _extract_value(other):
66 if other is True or other is False:
67 return other
68
69 if isinstance(other, numbers.Integral):
70 return int(other)
71
72 if isinstance(other, numbers.Real):
73 return float(other)
74
75 if isinstance(other, numbers.Complex):
76 return complex(other)
77
78 raise TypeError("'{}' object is not a number object".format(other.__class__.__name__))
79
80 def __int__(self):
81 return int(self.value)
82
83 def __float__(self):
84 return float(self.value)
85
86 def __str__(self):
87 return str(self.value)
88
89 def __lt__(self, other):
90 if not isinstance(other, numbers.Number):
91 raise TypeError('unorderable types: {}() < {}()'.format(self.__class__.__name__,
92 other.__class__.__name__))
93
94 return self.value < float(other)
95
96 def __le__(self, other):
97 if not isinstance(other, numbers.Number):
98 raise TypeError('unorderable types: {}() <= {}()'.format(self.__class__.__name__,
99 other.__class__.__name__))
100
101 return self.value <= float(other)
102
103 def __eq__(self, other):
104 if not isinstance(other, numbers.Number):
105 return False
106
107 return self.value == complex(other)
108
109 def __rmod__(self, other):
110 return self._extract_value(other) % self.value
111
112 def __mod__(self, other):
113 return self.value % self._extract_value(other)
114
115 def __rfloordiv__(self, other):
116 return self._extract_value(other) // self.value
117
118 def __floordiv__(self, other):
119 return self.value // self._extract_value(other)
120
121 def __round__(self, ndigits=None):
122 if ndigits is None:
123 return round(self.value)
124 else:
125 return round(self.value, ndigits)
126
127 def __ceil__(self):
128 return math.ceil(self.value)
129
130 def __floor__(self):
131 return math.floor(self.value)
132
133 def __trunc__(self):
134 return int(self.value)
135
136 def __abs__(self):
137 return abs(self.value)
138
139 def __add__(self, other):
140 return self.value + self._extract_value(other)
141
142 def __radd__(self, other):
143 return self.__add__(other)
144
145 def __neg__(self):
146 return -self.value
147
148 def __pos__(self):
149 return +self.value
150
151 def __mul__(self, other):
152 return self.value * self._extract_value(other)
153
154 def __rmul__(self, other):
155 return self.__mul__(other)
156
157 def __truediv__(self, other):
158 return self.value / self._extract_value(other)
159
160 def __rtruediv__(self, other):
161 return self._extract_value(other) / self.value
162
163 def __pow__(self, exponent):
164 return self.value ** self._extract_value(exponent)
165
166 def __rpow__(self, base):
167 return self._extract_value(base) ** self.value
168
169 def __iadd__(self, other):
170 self.value = self + other
171 return self
172
173 def __isub__(self, other):
174 self.value = self - other
175 return self
176
177 def __imul__(self, other):
178 self.value = self * other
179 return self
180
181 def __itruediv__(self, other):
182 self.value = self / other
183 return self
184
185 def __ifloordiv__(self, other):
186 self.value = self // other
187 return self
188
189 def __imod__(self, other):
190 self.value = self % other
191 return self
192
193 def __ipow__(self, other):
194 self.value = self ** other
195 return self
196
197
198class _IntegralField(_NumericField, numbers.Integral):
199 def __lshift__(self, other):
200 return self.value << self._extract_value(other)
201
202 def __rlshift__(self, other):
203 return self._extract_value(other) << self.value
204
205 def __rshift__(self, other):
206 return self.value >> self._extract_value(other)
207
208 def __rrshift__(self, other):
209 return self._extract_value(other) >> self.value
210
211 def __and__(self, other):
212 return self.value & self._extract_value(other)
213
214 def __rand__(self, other):
215 return self._extract_value(other) & self.value
216
217 def __xor__(self, other):
218 return self.value ^ self._extract_value(other)
219
220 def __rxor__(self, other):
221 return self._extract_value(other) ^ self.value
222
223 def __or__(self, other):
224 return self.value | self._extract_value(other)
225
226 def __ror__(self, other):
227 return self._extract_value(other) | self.value
228
229 def __invert__(self):
230 return ~self.value
231
232 def __ilshift__(self, other):
233 self.value = self << other
234 return self
235
236 def __irshift__(self, other):
237 self.value = self >> other
238 return self
239
240 def __iand__(self, other):
241 self.value = self & other
242 return self
243
244 def __ixor__(self, other):
245 self.value = self ^ other
246 return self
247
248 def __ior__(self, other):
249 self.value = self | other
250 return self
251
252
253class _RealField(_NumericField, numbers.Real):
254 pass
255
256
257class _IntegerField(_IntegralField):
258 _NAME = 'Integer'
259
260 def _value_to_int(self, value):
261 if not isinstance(value, numbers.Real):
262 raise TypeError('expecting a real number object')
263
264 value = int(value)
265
266 if self.field_type.is_signed:
267 utils._check_int64(value)
268 else:
269 utils._check_uint64(value)
270
271 return value
272
273 @property
274 def value(self):
275 if self.field_type.is_signed:
276 ret, value = native_bt.ctf_field_signed_integer_get_value(self._ptr)
277 else:
278 ret, value = native_bt.ctf_field_unsigned_integer_get_value(self._ptr)
279
280 utils._handle_ret(ret, "cannot get integer field object's value")
281 return value
282
283 @value.setter
284 def value(self, value):
285 value = self._value_to_int(value)
286
287 if self.field_type.is_signed:
288 ret = native_bt.ctf_field_signed_integer_set_value(self._ptr, value)
289 else:
290 ret = native_bt.ctf_field_unsigned_integer_set_value(self._ptr, value)
291
292 utils._handle_ret(ret, "cannot set integer field object's value")
293
294
295class _FloatingPointNumberField(_RealField):
296 _NAME = 'Floating point number'
297
298 def _value_to_float(self, value):
299 if not isinstance(value, numbers.Real):
300 raise TypeError("expecting a real number object")
301
302 return float(value)
303
304 @property
305 def value(self):
306 ret, value = native_bt.ctf_field_floating_point_get_value(self._ptr)
307 utils._handle_ret(ret, "cannot get floating point number field object's value")
308 return value
309
310 @value.setter
311 def value(self, value):
312 value = self._value_to_float(value)
313 ret = native_bt.ctf_field_floating_point_set_value(self._ptr, value)
314 utils._handle_ret(ret, "cannot set floating point number field object's value")
315
316
317class _EnumerationField(_IntegerField):
318 _NAME = 'Enumeration'
319
320 @property
321 def integer_field(self):
322 int_field_ptr = native_bt.ctf_field_enumeration_get_container(self._ptr)
323 utils._handle_ptr(int_field_ptr,
324 "cannot get enumeration field object's underlying integer field")
325 return _create_from_ptr(int_field_ptr)
326
327 @property
328 def value(self):
329 return self.integer_field.value
330
331 @value.setter
332 def value(self, value):
333 self.integer_field.value = value
334
335 @property
336 def mappings(self):
337 iter_ptr = bt_ctf_field_enumeration_get_mappings(self._ptr)
338 return self.field_type._get_mapping_iter(iter_ptr)
339
340
341@functools.total_ordering
342class _StringField(_Field, collections.abc.Sequence):
343 _NAME = 'String'
344
345 def _value_to_str(self, value):
346 if isinstance(value, self.__class__):
347 value = value.value
348
349 if not isinstance(value, str):
350 raise TypeError("expecting a 'str' object")
351
352 return value
353
354 @property
355 def value(self):
356 value = native_bt.ctf_field_string_get_value(self._ptr)
357 utils._handle_ptr(value, "cannot get string field object's value")
358 return value
359
360 @value.setter
361 def value(self, value):
362 value = self._value_to_str(value)
363 ret = native_bt.ctf_field_string_set_value(self._ptr, value)
364 utils._handle_ret(ret, "cannot set string field object's value")
365
366 def __eq__(self, other):
367 try:
368 other = self._value_to_str(other)
369 except:
370 return False
371
372 return self.value == other
373
374 def __le__(self, other):
375 return self.value <= self._value_to_str(other)
376
377 def __lt__(self, other):
378 return self.value < self._value_to_str(other)
379
380 def __bool__(self):
381 return bool(self.value)
382
383 def __str__(self):
384 return self.value
385
386 def __getitem__(self, index):
387 return self.value[index]
388
389 def __len__(self):
390 return len(self.value)
391
392 def __iadd__(self, value):
393 value = self._value_to_str(value)
394 ret = native_bt.ctf_field_string_append(self._ptr, value)
395 utils._handle_ret(ret, "cannot append to string field object's value")
396 return self
397
398
399class _ContainerField(_Field):
400 def __bool__(self):
401 return len(self) != 0
402
403 def __len__(self):
404 count = self._count()
405 utils._handle_ret(count, "cannot get {} field object's field count".format(self._NAME.lower()))
406 return count
407
408 def __delitem__(self, index):
409 raise NotImplementedError
410
411
412class _StructureField(_ContainerField, collections.abc.MutableMapping):
413 _NAME = 'Structure'
414
415 def _count(self):
416 return len(self.field_type)
417
418 def __getitem__(self, key):
419 utils._check_str(key)
420 ptr = native_bt.ctf_field_structure_get_field(self._ptr, key)
421
422 if ptr is None:
423 raise KeyError(key)
424
425 return _create_from_ptr(ptr)
426
427 def __setitem__(self, key, value):
428 # we can only set numbers and strings
429 if not isinstance(value, (numbers.Number, str)):
430 raise TypeError('expecting number object or string')
431
432 # raises if index is somehow invalid
433 field = self[key]
434
435 if not isinstance(field, (_NumericField, _StringField)):
436 raise TypeError('can only set the value of a number or string field')
437
438 # the field's property does the appropriate conversion or raises
439 # the appropriate exception
440 field.value = value
441
442 def at_index(self, index):
443 utils._check_uint64(index)
444 field_ptr = native_bt.ctf_field_structure_get_field_by_index(self._ptr, index)
445 utils._handle_ptr(field_ptr, "cannot get structure field object's field")
446 return _create_from_ptr(field_ptr)
447
448 def __iter__(self):
449 # same name iterator
450 return iter(self.field_type)
451
452 def __eq__(self, other):
453 if not isinstance(other, collections.abc.Mapping):
454 return False
455
456 if len(self) != len(other):
457 return False
458
459 for self_key, self_value in self.items():
460 if self_key not in other:
461 return False
462
463 other_value = other[self_key]
464
465 if self_value != other_value:
466 return False
467
468 return True
469
470
471class _VariantField(_Field):
472 _NAME = 'Variant'
473
474 @property
475 def tag_field(self):
476 field_ptr = native_bt.ctf_field_variant_get_tag(self._ptr)
477 utils._handle_ptr(field_ptr, "cannot get variant field object's tag field")
478 return _create_from_ptr(field_ptr)
479
480 @property
481 def selected_field(self):
482 return self.field()
483
484 def field(self, tag_field=None):
485 if tag_field is None:
486 field_ptr = native_bt.ctf_field_variant_get_current_field(self._ptr)
487 utils._handle_ptr(field_ptr, "cannot get variant field object's selected field")
488 else:
489 utils._check_type(tag_field, _EnumerationField)
490 field_ptr = native_bt.ctf_field_variant_get_field(self._ptr, tag_field._ptr)
491 utils._handle_ptr(field_ptr, "cannot select variant field object's field")
492
493 return _create_from_ptr(field_ptr)
494
495 def __eq__(self, other):
496 return self.field == other
497
498
499class _ArraySequenceField(_ContainerField, collections.abc.MutableSequence):
500 def __getitem__(self, index):
501 if not isinstance(index, numbers.Integral):
502 raise TypeError("'{}' is not an integral number object: invalid index".format(index.__class__.__name__))
503
504 index = int(index)
505
506 if index < 0 or index >= len(self):
507 raise IndexError('{} field object index is out of range'.format(self._NAME))
508
509 field_ptr = self._get_field_ptr_at_index(index)
510 utils._handle_ptr(field_ptr, "cannot get {} field object's field".format(self._NAME))
511 return _create_from_ptr(field_ptr)
512
513 def __setitem__(self, index, value):
514 # we can only set numbers and strings
515 if not isinstance(value, (numbers.Number, _StringField, str)):
516 raise TypeError('expecting number or string object')
517
518 # raises if index is somehow invalid
519 field = self[index]
520
521 if not isinstance(field, (_NumericField, _StringField)):
522 raise TypeError('can only set the value of a number or string field')
523
524 # the field's property does the appropriate conversion or raises
525 # the appropriate exception
526 field.value = value
527
528 def insert(self, index, value):
529 raise NotImplementedError
530
531 def __eq__(self, other):
532 if not isinstance(other, collections.abc.Sequence):
533 return False
534
535 if len(self) != len(other):
536 return False
537
538 for self_field, other_field in zip(self, other):
539 if self_field != other_field:
540 return False
541
542 return True
543
544
545class _ArrayField(_ArraySequenceField):
546 _NAME = 'Array'
547
548 def _count(self):
549 return self.field_type.length
550
551 def _get_field_ptr_at_index(self, index):
552 return native_bt.ctf_field_array_get_field(self._ptr, index)
553
554
555class _SequenceField(_ArraySequenceField):
556 _NAME = 'Sequence'
557
558 def _count(self):
559 return self.length_field.value
560
561 @property
562 def length_field(self):
563 field_ptr = native_bt.ctf_field_sequence_get_length(self._ptr)
564 utils._handle_ptr("cannot get sequence field object's length field")
565 return _create_from_ptr(field_ptr)
566
567 @length_field.setter
568 def length_field(self, length_field):
569 utils._check_type(length_field, _IntegerField)
570 ret = native_bt.ctf_field_sequence_set_length(self._ptr, length_field._ptr)
571 utils._handle_ret(ret, "cannot set sequence field object's length field")
572
573 def _get_field_ptr_at_index(self, index):
574 return native_bt.ctf_field_sequence_get_field(self._ptr, index)
575
576
577_TYPE_ID_TO_OBJ = {
578 native_bt.CTF_TYPE_ID_INTEGER: _IntegerField,
579 native_bt.CTF_TYPE_ID_FLOAT: _FloatingPointNumberField,
580 native_bt.CTF_TYPE_ID_ENUM: _EnumerationField,
581 native_bt.CTF_TYPE_ID_STRING: _StringField,
582 native_bt.CTF_TYPE_ID_STRUCT: _StructureField,
583 native_bt.CTF_TYPE_ID_ARRAY: _ArrayField,
584 native_bt.CTF_TYPE_ID_SEQUENCE: _SequenceField,
585 native_bt.CTF_TYPE_ID_VARIANT: _VariantField,
586 native_bt.CTF_TYPE_ID_UNTAGGED_VARIANT: _VariantField,
587}
This page took 0.046011 seconds and 4 git commands to generate.