Apply black code formatter on all Python code
[babeltrace.git] / src / bindings / python / bt2 / bt2 / value.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
24import collections.abc
25import functools
26import numbers
27import math
28import abc
29import bt2
30
31
81447b5b 32def _create_from_ptr(ptr):
b5947615
SM
33 if ptr is None:
34 return
35
36 # bt_value_null is translated to None. However, we are given a reference
37 # to it that we are not going to manage anymore, since we don't create a
38 # Python wrapper for it. Therefore put that reference immediately.
39 if ptr == native_bt.value_null:
40 bt2.value._Value._put_ref(ptr)
81447b5b
PP
41 return
42
43 typeid = native_bt.value_get_type(ptr)
44 return _TYPE_TO_OBJ[typeid]._create_from_ptr(ptr)
45
46
10a19b49
SM
47def _create_from_ptr_and_get_ref(ptr):
48 if ptr is None or ptr == native_bt.value_null:
49 return
50
51 typeid = native_bt.value_get_type(ptr)
52 return _TYPE_TO_OBJ[typeid]._create_from_ptr_and_get_ref(ptr)
53
54
81447b5b
PP
55def create_value(value):
56 if value is None:
57 # null value object
58 return
59
60 if isinstance(value, _Value):
61 return value
62
63 if isinstance(value, bool):
64 return BoolValue(value)
65
665658c2 66 if isinstance(value, numbers.Integral):
fdd3a2da 67 return SignedIntegerValue(value)
81447b5b 68
665658c2 69 if isinstance(value, numbers.Real):
10a19b49 70 return RealValue(value)
81447b5b
PP
71
72 if isinstance(value, str):
73 return StringValue(value)
74
665658c2 75 if isinstance(value, collections.abc.Sequence):
81447b5b 76 return ArrayValue(value)
665658c2
PP
77
78 if isinstance(value, collections.abc.Mapping):
79 return MapValue(value)
81447b5b 80
cfbd7cf3
FD
81 raise TypeError(
82 "cannot create value object from '{}' object".format(value.__class__.__name__)
83 )
81447b5b
PP
84
85
78288f58 86class _Value(object._SharedObject, metaclass=abc.ABCMeta):
2f16a6a2
PP
87 _get_ref = staticmethod(native_bt.value_get_ref)
88 _put_ref = staticmethod(native_bt.value_put_ref)
10a19b49 89
81447b5b
PP
90 def __ne__(self, other):
91 return not (self == other)
92
81447b5b
PP
93 def _check_create_status(self, ptr):
94 if ptr is None:
10a19b49 95 raise bt2.CreationError(
cfbd7cf3
FD
96 'cannot create {} value object'.format(self._NAME.lower())
97 )
81447b5b
PP
98
99
100@functools.total_ordering
10a19b49 101class _NumericValue(_Value):
81447b5b
PP
102 @staticmethod
103 def _extract_value(other):
b00a769c
PP
104 if isinstance(other, BoolValue) or isinstance(other, bool):
105 return bool(other)
81447b5b
PP
106
107 if isinstance(other, numbers.Integral):
108 return int(other)
109
110 if isinstance(other, numbers.Real):
111 return float(other)
112
113 if isinstance(other, numbers.Complex):
114 return complex(other)
115
cfbd7cf3
FD
116 raise TypeError(
117 "'{}' object is not a number object".format(other.__class__.__name__)
118 )
81447b5b
PP
119
120 def __int__(self):
9b6cd4a7 121 return int(self._value)
81447b5b
PP
122
123 def __float__(self):
9b6cd4a7 124 return float(self._value)
81447b5b 125
83656269
JG
126 def __repr__(self):
127 return repr(self._value)
81447b5b
PP
128
129 def __lt__(self, other):
09a926c1 130 return self._value < self._extract_value(other)
81447b5b 131
81447b5b 132 def __eq__(self, other):
b00a769c
PP
133 try:
134 return self._value == self._extract_value(other)
135 except:
81447b5b
PP
136 return False
137
81447b5b 138 def __rmod__(self, other):
9b6cd4a7 139 return self._extract_value(other) % self._value
81447b5b
PP
140
141 def __mod__(self, other):
9b6cd4a7 142 return self._value % self._extract_value(other)
81447b5b
PP
143
144 def __rfloordiv__(self, other):
9b6cd4a7 145 return self._extract_value(other) // self._value
81447b5b
PP
146
147 def __floordiv__(self, other):
9b6cd4a7 148 return self._value // self._extract_value(other)
81447b5b
PP
149
150 def __round__(self, ndigits=None):
151 if ndigits is None:
9b6cd4a7 152 return round(self._value)
81447b5b 153 else:
9b6cd4a7 154 return round(self._value, ndigits)
81447b5b
PP
155
156 def __ceil__(self):
9b6cd4a7 157 return math.ceil(self._value)
81447b5b
PP
158
159 def __floor__(self):
9b6cd4a7 160 return math.floor(self._value)
81447b5b
PP
161
162 def __trunc__(self):
9b6cd4a7 163 return int(self._value)
81447b5b
PP
164
165 def __abs__(self):
9b6cd4a7 166 return abs(self._value)
81447b5b
PP
167
168 def __add__(self, other):
9b6cd4a7 169 return self._value + self._extract_value(other)
81447b5b
PP
170
171 def __radd__(self, other):
172 return self.__add__(other)
173
174 def __neg__(self):
9b6cd4a7 175 return -self._value
81447b5b
PP
176
177 def __pos__(self):
9b6cd4a7 178 return +self._value
81447b5b
PP
179
180 def __mul__(self, other):
9b6cd4a7 181 return self._value * self._extract_value(other)
81447b5b
PP
182
183 def __rmul__(self, other):
184 return self.__mul__(other)
185
186 def __truediv__(self, other):
9b6cd4a7 187 return self._value / self._extract_value(other)
81447b5b
PP
188
189 def __rtruediv__(self, other):
9b6cd4a7 190 return self._extract_value(other) / self._value
81447b5b
PP
191
192 def __pow__(self, exponent):
9b6cd4a7 193 return self._value ** self._extract_value(exponent)
81447b5b
PP
194
195 def __rpow__(self, base):
9b6cd4a7 196 return self._extract_value(base) ** self._value
81447b5b 197
81447b5b
PP
198
199class _IntegralValue(_NumericValue, numbers.Integral):
200 def __lshift__(self, other):
9b6cd4a7 201 return self._value << self._extract_value(other)
81447b5b
PP
202
203 def __rlshift__(self, other):
9b6cd4a7 204 return self._extract_value(other) << self._value
81447b5b
PP
205
206 def __rshift__(self, other):
9b6cd4a7 207 return self._value >> self._extract_value(other)
81447b5b
PP
208
209 def __rrshift__(self, other):
9b6cd4a7 210 return self._extract_value(other) >> self._value
81447b5b
PP
211
212 def __and__(self, other):
9b6cd4a7 213 return self._value & self._extract_value(other)
81447b5b
PP
214
215 def __rand__(self, other):
9b6cd4a7 216 return self._extract_value(other) & self._value
81447b5b
PP
217
218 def __xor__(self, other):
9b6cd4a7 219 return self._value ^ self._extract_value(other)
81447b5b
PP
220
221 def __rxor__(self, other):
9b6cd4a7 222 return self._extract_value(other) ^ self._value
81447b5b
PP
223
224 def __or__(self, other):
9b6cd4a7 225 return self._value | self._extract_value(other)
81447b5b
PP
226
227 def __ror__(self, other):
9b6cd4a7 228 return self._extract_value(other) | self._value
81447b5b
PP
229
230 def __invert__(self):
9b6cd4a7 231 return ~self._value
81447b5b 232
81447b5b
PP
233
234class _RealValue(_NumericValue, numbers.Real):
235 pass
236
237
88d39313 238class BoolValue(_IntegralValue):
81447b5b
PP
239 _NAME = 'Boolean'
240
241 def __init__(self, value=None):
242 if value is None:
243 ptr = native_bt.value_bool_create()
244 else:
245 ptr = native_bt.value_bool_create_init(self._value_to_bool(value))
246
247 self._check_create_status(ptr)
248 super().__init__(ptr)
249
81447b5b 250 def __bool__(self):
9b6cd4a7 251 return self._value
81447b5b 252
83656269
JG
253 def __repr__(self):
254 return repr(self._value)
81447b5b
PP
255
256 def _value_to_bool(self, value):
257 if isinstance(value, BoolValue):
9b6cd4a7 258 value = value._value
81447b5b
PP
259
260 if not isinstance(value, bool):
cfbd7cf3
FD
261 raise TypeError(
262 "'{}' object is not a 'bool' or 'BoolValue' object".format(
263 value.__class__
264 )
265 )
81447b5b 266
b00a769c 267 return value
81447b5b
PP
268
269 @property
9b6cd4a7 270 def _value(self):
10a19b49
SM
271 value = native_bt.value_bool_get(self._ptr)
272 return value != 0
81447b5b 273
9b6cd4a7 274 def _set_value(self, value):
10a19b49 275 native_bt.value_bool_set(self._ptr, self._value_to_bool(value))
81447b5b 276
9b6cd4a7
PP
277 value = property(fset=_set_value)
278
81447b5b 279
fdd3a2da 280class _IntegerValue(_IntegralValue):
81447b5b
PP
281 def __init__(self, value=None):
282 if value is None:
fdd3a2da 283 ptr = self._create_default_value()
81447b5b 284 else:
fdd3a2da 285 ptr = self._create_value(self._value_to_int(value))
81447b5b
PP
286
287 self._check_create_status(ptr)
288 super().__init__(ptr)
289
290 def _value_to_int(self, value):
e502b15a
PP
291 if not isinstance(value, numbers.Integral):
292 raise TypeError('expecting an integral number object')
81447b5b
PP
293
294 value = int(value)
fdd3a2da 295 self._check_int_range(value)
81447b5b
PP
296 return value
297
298 @property
9b6cd4a7 299 def _value(self):
fdd3a2da 300 return self._get_value(self._ptr)
81447b5b 301
fdd3a2da
PP
302 def _prop_set_value(self, value):
303 self._set_value(self._ptr, self._value_to_int(value))
81447b5b 304
fdd3a2da
PP
305 value = property(fset=_prop_set_value)
306
307
308class UnsignedIntegerValue(_IntegerValue):
309 _check_int_range = staticmethod(utils._check_uint64)
2f16a6a2
PP
310 _create_default_value = staticmethod(native_bt.value_unsigned_integer_create)
311 _create_value = staticmethod(native_bt.value_unsigned_integer_create_init)
312 _set_value = staticmethod(native_bt.value_unsigned_integer_set)
313 _get_value = staticmethod(native_bt.value_unsigned_integer_get)
fdd3a2da
PP
314
315
316class SignedIntegerValue(_IntegerValue):
317 _check_int_range = staticmethod(utils._check_int64)
2f16a6a2
PP
318 _create_default_value = staticmethod(native_bt.value_signed_integer_create)
319 _create_value = staticmethod(native_bt.value_signed_integer_create_init)
320 _set_value = staticmethod(native_bt.value_signed_integer_set)
321 _get_value = staticmethod(native_bt.value_signed_integer_get)
9b6cd4a7 322
81447b5b 323
10a19b49
SM
324class RealValue(_RealValue):
325 _NAME = 'Real number'
81447b5b
PP
326
327 def __init__(self, value=None):
328 if value is None:
10a19b49 329 ptr = native_bt.value_real_create()
81447b5b
PP
330 else:
331 value = self._value_to_float(value)
10a19b49 332 ptr = native_bt.value_real_create_init(value)
81447b5b
PP
333
334 self._check_create_status(ptr)
335 super().__init__(ptr)
336
337 def _value_to_float(self, value):
338 if not isinstance(value, numbers.Real):
339 raise TypeError("expecting a real number object")
340
341 return float(value)
342
343 @property
9b6cd4a7 344 def _value(self):
10a19b49 345 return native_bt.value_real_get(self._ptr)
81447b5b 346
9b6cd4a7 347 def _set_value(self, value):
10a19b49 348 native_bt.value_real_set(self._ptr, self._value_to_float(value))
81447b5b 349
9b6cd4a7
PP
350 value = property(fset=_set_value)
351
81447b5b
PP
352
353@functools.total_ordering
10a19b49 354class StringValue(collections.abc.Sequence, _Value):
81447b5b
PP
355 _NAME = 'String'
356
357 def __init__(self, value=None):
358 if value is None:
359 ptr = native_bt.value_string_create()
360 else:
361 ptr = native_bt.value_string_create_init(self._value_to_str(value))
362
363 self._check_create_status(ptr)
364 super().__init__(ptr)
365
366 def _value_to_str(self, value):
367 if isinstance(value, self.__class__):
9b6cd4a7 368 value = value._value
81447b5b
PP
369
370 utils._check_str(value)
371 return value
372
373 @property
9b6cd4a7 374 def _value(self):
10a19b49 375 return native_bt.value_string_get(self._ptr)
81447b5b 376
9b6cd4a7 377 def _set_value(self, value):
81447b5b 378 status = native_bt.value_string_set(self._ptr, self._value_to_str(value))
d24d5663 379 utils._handle_func_status(status)
81447b5b 380
9b6cd4a7
PP
381 value = property(fset=_set_value)
382
b00a769c 383 def __eq__(self, other):
81447b5b 384 try:
9b6cd4a7 385 return self._value == self._value_to_str(other)
81447b5b 386 except:
b00a769c 387 return False
81447b5b 388
81447b5b 389 def __lt__(self, other):
9b6cd4a7 390 return self._value < self._value_to_str(other)
81447b5b
PP
391
392 def __bool__(self):
9b6cd4a7 393 return bool(self._value)
81447b5b 394
83656269 395 def __repr__(self):
10a19b49 396 return repr(self._value)
83656269 397
81447b5b 398 def __str__(self):
9b6cd4a7 399 return self._value
81447b5b
PP
400
401 def __getitem__(self, index):
9b6cd4a7 402 return self._value[index]
81447b5b
PP
403
404 def __len__(self):
9b6cd4a7 405 return len(self._value)
81447b5b
PP
406
407 def __iadd__(self, value):
9b6cd4a7 408 curvalue = self._value
81447b5b
PP
409 curvalue += self._value_to_str(value)
410 self.value = curvalue
411 return self
412
413
414class _Container:
415 def __bool__(self):
416 return len(self) != 0
417
81447b5b
PP
418 def __delitem__(self, index):
419 raise NotImplementedError
420
421
422class ArrayValue(_Container, collections.abc.MutableSequence, _Value):
423 _NAME = 'Array'
424
425 def __init__(self, value=None):
426 ptr = native_bt.value_array_create()
427 self._check_create_status(ptr)
428 super().__init__(ptr)
429
430 # Python will raise a TypeError if there's anything wrong with
431 # the iterable protocol.
432 if value is not None:
433 for elem in value:
434 self.append(elem)
435
b00a769c
PP
436 def __eq__(self, other):
437 if not isinstance(other, collections.abc.Sequence):
438 return False
81447b5b 439
b00a769c
PP
440 if len(self) != len(other):
441 # early mismatch
442 return False
81447b5b 443
b00a769c
PP
444 for self_elem, other_elem in zip(self, other):
445 if self_elem != other_elem:
446 return False
447
448 return True
81447b5b
PP
449
450 def __len__(self):
10a19b49 451 size = native_bt.value_array_get_size(self._ptr)
cfbd7cf3 452 assert size >= 0
81447b5b
PP
453 return size
454
455 def _check_index(self, index):
456 # TODO: support slices also
457 if not isinstance(index, numbers.Integral):
cfbd7cf3
FD
458 raise TypeError(
459 "'{}' object is not an integral number object: invalid index".format(
460 index.__class__.__name__
461 )
462 )
81447b5b
PP
463
464 index = int(index)
465
466 if index < 0 or index >= len(self):
467 raise IndexError('array value object index is out of range')
468
469 def __getitem__(self, index):
470 self._check_index(index)
10a19b49 471 ptr = native_bt.value_array_borrow_element_by_index(self._ptr, index)
cfbd7cf3 472 assert ptr
10a19b49 473 return _create_from_ptr_and_get_ref(ptr)
81447b5b
PP
474
475 def __setitem__(self, index, value):
476 self._check_index(index)
477 value = create_value(value)
478
479 if value is None:
480 ptr = native_bt.value_null
481 else:
482 ptr = value._ptr
483
cfbd7cf3 484 status = native_bt.value_array_set_element_by_index(self._ptr, index, ptr)
d24d5663 485 utils._handle_func_status(status)
81447b5b
PP
486
487 def append(self, value):
488 value = create_value(value)
489
490 if value is None:
491 ptr = native_bt.value_null
492 else:
493 ptr = value._ptr
494
10a19b49 495 status = native_bt.value_array_append_element(self._ptr, ptr)
d24d5663 496 utils._handle_func_status(status)
81447b5b
PP
497
498 def __iadd__(self, iterable):
499 # Python will raise a TypeError if there's anything wrong with
500 # the iterable protocol.
501 for elem in iterable:
502 self.append(elem)
503
504 return self
505
83656269
JG
506 def __repr__(self):
507 return '[{}]'.format(', '.join([repr(v) for v in self]))
81447b5b
PP
508
509 def insert(self, value):
510 raise NotImplementedError
511
512
513class _MapValueKeyIterator(collections.abc.Iterator):
514 def __init__(self, map_obj):
515 self._map_obj = map_obj
516 self._at = 0
10a19b49 517 keys_ptr = native_bt.value_map_get_keys(map_obj._ptr)
81447b5b
PP
518
519 if keys_ptr is None:
520 raise RuntimeError('unexpected error: cannot get map value object keys')
521
522 self._keys = _create_from_ptr(keys_ptr)
523
524 def __next__(self):
525 if self._at == len(self._map_obj):
526 raise StopIteration
527
528 key = self._keys[self._at]
529 self._at += 1
530 return str(key)
531
532
533class MapValue(_Container, collections.abc.MutableMapping, _Value):
534 _NAME = 'Map'
535
536 def __init__(self, value=None):
537 ptr = native_bt.value_map_create()
538 self._check_create_status(ptr)
539 super().__init__(ptr)
540
541 # Python will raise a TypeError if there's anything wrong with
542 # the iterable/mapping protocol.
543 if value is not None:
544 for key, elem in value.items():
545 self[key] = elem
546
81447b5b
PP
547 def __ne__(self, other):
548 return _Value.__ne__(self, other)
549
b00a769c
PP
550 def __eq__(self, other):
551 if not isinstance(other, collections.abc.Mapping):
552 return False
81447b5b 553
b00a769c
PP
554 if len(self) != len(other):
555 # early mismatch
556 return False
81447b5b 557
b00a769c
PP
558 for self_key in self:
559 if self_key not in other:
560 return False
81447b5b 561
b00a769c
PP
562 if self[self_key] != other[self_key]:
563 return False
81447b5b 564
b00a769c 565 return True
81447b5b
PP
566
567 def __len__(self):
10a19b49 568 size = native_bt.value_map_get_size(self._ptr)
cfbd7cf3 569 assert size >= 0
81447b5b
PP
570 return size
571
572 def __contains__(self, key):
573 self._check_key_type(key)
10a19b49 574 return native_bt.value_map_has_entry(self._ptr, key)
81447b5b
PP
575
576 def _check_key_type(self, key):
577 utils._check_str(key)
578
579 def _check_key(self, key):
580 if key not in self:
581 raise KeyError(key)
582
583 def __getitem__(self, key):
584 self._check_key(key)
10a19b49 585 ptr = native_bt.value_map_borrow_entry_value(self._ptr, key)
cfbd7cf3 586 assert ptr
10a19b49 587 return _create_from_ptr_and_get_ref(ptr)
81447b5b
PP
588
589 def __iter__(self):
590 return _MapValueKeyIterator(self)
591
592 def __setitem__(self, key, value):
593 self._check_key_type(key)
594 value = create_value(value)
595
596 if value is None:
597 ptr = native_bt.value_null
598 else:
599 ptr = value._ptr
600
10a19b49 601 status = native_bt.value_map_insert_entry(self._ptr, key, ptr)
d24d5663 602 utils._handle_func_status(status)
81447b5b 603
83656269
JG
604 def __repr__(self):
605 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
606 return '{{{}}}'.format(', '.join(items))
81447b5b
PP
607
608
609_TYPE_TO_OBJ = {
610 native_bt.VALUE_TYPE_BOOL: BoolValue,
fdd3a2da
PP
611 native_bt.VALUE_TYPE_UNSIGNED_INTEGER: UnsignedIntegerValue,
612 native_bt.VALUE_TYPE_SIGNED_INTEGER: SignedIntegerValue,
10a19b49 613 native_bt.VALUE_TYPE_REAL: RealValue,
81447b5b
PP
614 native_bt.VALUE_TYPE_STRING: StringValue,
615 native_bt.VALUE_TYPE_ARRAY: ArrayValue,
616 native_bt.VALUE_TYPE_MAP: MapValue,
617}
This page took 0.071801 seconds and 4 git commands to generate.