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