Apply black code formatter on all Python code
[babeltrace.git] / src / bindings / python / bt2 / bt2 / value.py
1 # The MIT License (MIT)
2 #
3 # Copyright (c) 2017 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
23 from bt2 import native_bt, object, utils
24 import collections.abc
25 import functools
26 import numbers
27 import math
28 import abc
29 import bt2
30
31
32 def _create_from_ptr(ptr):
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)
41 return
42
43 typeid = native_bt.value_get_type(ptr)
44 return _TYPE_TO_OBJ[typeid]._create_from_ptr(ptr)
45
46
47 def _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
55 def 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
66 if isinstance(value, numbers.Integral):
67 return SignedIntegerValue(value)
68
69 if isinstance(value, numbers.Real):
70 return RealValue(value)
71
72 if isinstance(value, str):
73 return StringValue(value)
74
75 if isinstance(value, collections.abc.Sequence):
76 return ArrayValue(value)
77
78 if isinstance(value, collections.abc.Mapping):
79 return MapValue(value)
80
81 raise TypeError(
82 "cannot create value object from '{}' object".format(value.__class__.__name__)
83 )
84
85
86 class _Value(object._SharedObject, metaclass=abc.ABCMeta):
87 _get_ref = staticmethod(native_bt.value_get_ref)
88 _put_ref = staticmethod(native_bt.value_put_ref)
89
90 def __ne__(self, other):
91 return not (self == other)
92
93 def _check_create_status(self, ptr):
94 if ptr is None:
95 raise bt2.CreationError(
96 'cannot create {} value object'.format(self._NAME.lower())
97 )
98
99
100 @functools.total_ordering
101 class _NumericValue(_Value):
102 @staticmethod
103 def _extract_value(other):
104 if isinstance(other, BoolValue) or isinstance(other, bool):
105 return bool(other)
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(
117 "'{}' object is not a number object".format(other.__class__.__name__)
118 )
119
120 def __int__(self):
121 return int(self._value)
122
123 def __float__(self):
124 return float(self._value)
125
126 def __repr__(self):
127 return repr(self._value)
128
129 def __lt__(self, other):
130 return self._value < self._extract_value(other)
131
132 def __eq__(self, other):
133 try:
134 return self._value == self._extract_value(other)
135 except:
136 return False
137
138 def __rmod__(self, other):
139 return self._extract_value(other) % self._value
140
141 def __mod__(self, other):
142 return self._value % self._extract_value(other)
143
144 def __rfloordiv__(self, other):
145 return self._extract_value(other) // self._value
146
147 def __floordiv__(self, other):
148 return self._value // self._extract_value(other)
149
150 def __round__(self, ndigits=None):
151 if ndigits is None:
152 return round(self._value)
153 else:
154 return round(self._value, ndigits)
155
156 def __ceil__(self):
157 return math.ceil(self._value)
158
159 def __floor__(self):
160 return math.floor(self._value)
161
162 def __trunc__(self):
163 return int(self._value)
164
165 def __abs__(self):
166 return abs(self._value)
167
168 def __add__(self, other):
169 return self._value + self._extract_value(other)
170
171 def __radd__(self, other):
172 return self.__add__(other)
173
174 def __neg__(self):
175 return -self._value
176
177 def __pos__(self):
178 return +self._value
179
180 def __mul__(self, other):
181 return self._value * self._extract_value(other)
182
183 def __rmul__(self, other):
184 return self.__mul__(other)
185
186 def __truediv__(self, other):
187 return self._value / self._extract_value(other)
188
189 def __rtruediv__(self, other):
190 return self._extract_value(other) / self._value
191
192 def __pow__(self, exponent):
193 return self._value ** self._extract_value(exponent)
194
195 def __rpow__(self, base):
196 return self._extract_value(base) ** self._value
197
198
199 class _IntegralValue(_NumericValue, numbers.Integral):
200 def __lshift__(self, other):
201 return self._value << self._extract_value(other)
202
203 def __rlshift__(self, other):
204 return self._extract_value(other) << self._value
205
206 def __rshift__(self, other):
207 return self._value >> self._extract_value(other)
208
209 def __rrshift__(self, other):
210 return self._extract_value(other) >> self._value
211
212 def __and__(self, other):
213 return self._value & self._extract_value(other)
214
215 def __rand__(self, other):
216 return self._extract_value(other) & self._value
217
218 def __xor__(self, other):
219 return self._value ^ self._extract_value(other)
220
221 def __rxor__(self, other):
222 return self._extract_value(other) ^ self._value
223
224 def __or__(self, other):
225 return self._value | self._extract_value(other)
226
227 def __ror__(self, other):
228 return self._extract_value(other) | self._value
229
230 def __invert__(self):
231 return ~self._value
232
233
234 class _RealValue(_NumericValue, numbers.Real):
235 pass
236
237
238 class BoolValue(_IntegralValue):
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
250 def __bool__(self):
251 return self._value
252
253 def __repr__(self):
254 return repr(self._value)
255
256 def _value_to_bool(self, value):
257 if isinstance(value, BoolValue):
258 value = value._value
259
260 if not isinstance(value, bool):
261 raise TypeError(
262 "'{}' object is not a 'bool' or 'BoolValue' object".format(
263 value.__class__
264 )
265 )
266
267 return value
268
269 @property
270 def _value(self):
271 value = native_bt.value_bool_get(self._ptr)
272 return value != 0
273
274 def _set_value(self, value):
275 native_bt.value_bool_set(self._ptr, self._value_to_bool(value))
276
277 value = property(fset=_set_value)
278
279
280 class _IntegerValue(_IntegralValue):
281 def __init__(self, value=None):
282 if value is None:
283 ptr = self._create_default_value()
284 else:
285 ptr = self._create_value(self._value_to_int(value))
286
287 self._check_create_status(ptr)
288 super().__init__(ptr)
289
290 def _value_to_int(self, value):
291 if not isinstance(value, numbers.Integral):
292 raise TypeError('expecting an integral number object')
293
294 value = int(value)
295 self._check_int_range(value)
296 return value
297
298 @property
299 def _value(self):
300 return self._get_value(self._ptr)
301
302 def _prop_set_value(self, value):
303 self._set_value(self._ptr, self._value_to_int(value))
304
305 value = property(fset=_prop_set_value)
306
307
308 class UnsignedIntegerValue(_IntegerValue):
309 _check_int_range = staticmethod(utils._check_uint64)
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)
314
315
316 class SignedIntegerValue(_IntegerValue):
317 _check_int_range = staticmethod(utils._check_int64)
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)
322
323
324 class RealValue(_RealValue):
325 _NAME = 'Real number'
326
327 def __init__(self, value=None):
328 if value is None:
329 ptr = native_bt.value_real_create()
330 else:
331 value = self._value_to_float(value)
332 ptr = native_bt.value_real_create_init(value)
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
344 def _value(self):
345 return native_bt.value_real_get(self._ptr)
346
347 def _set_value(self, value):
348 native_bt.value_real_set(self._ptr, self._value_to_float(value))
349
350 value = property(fset=_set_value)
351
352
353 @functools.total_ordering
354 class StringValue(collections.abc.Sequence, _Value):
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__):
368 value = value._value
369
370 utils._check_str(value)
371 return value
372
373 @property
374 def _value(self):
375 return native_bt.value_string_get(self._ptr)
376
377 def _set_value(self, value):
378 status = native_bt.value_string_set(self._ptr, self._value_to_str(value))
379 utils._handle_func_status(status)
380
381 value = property(fset=_set_value)
382
383 def __eq__(self, other):
384 try:
385 return self._value == self._value_to_str(other)
386 except:
387 return False
388
389 def __lt__(self, other):
390 return self._value < self._value_to_str(other)
391
392 def __bool__(self):
393 return bool(self._value)
394
395 def __repr__(self):
396 return repr(self._value)
397
398 def __str__(self):
399 return self._value
400
401 def __getitem__(self, index):
402 return self._value[index]
403
404 def __len__(self):
405 return len(self._value)
406
407 def __iadd__(self, value):
408 curvalue = self._value
409 curvalue += self._value_to_str(value)
410 self.value = curvalue
411 return self
412
413
414 class _Container:
415 def __bool__(self):
416 return len(self) != 0
417
418 def __delitem__(self, index):
419 raise NotImplementedError
420
421
422 class 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
436 def __eq__(self, other):
437 if not isinstance(other, collections.abc.Sequence):
438 return False
439
440 if len(self) != len(other):
441 # early mismatch
442 return False
443
444 for self_elem, other_elem in zip(self, other):
445 if self_elem != other_elem:
446 return False
447
448 return True
449
450 def __len__(self):
451 size = native_bt.value_array_get_size(self._ptr)
452 assert size >= 0
453 return size
454
455 def _check_index(self, index):
456 # TODO: support slices also
457 if not isinstance(index, numbers.Integral):
458 raise TypeError(
459 "'{}' object is not an integral number object: invalid index".format(
460 index.__class__.__name__
461 )
462 )
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)
471 ptr = native_bt.value_array_borrow_element_by_index(self._ptr, index)
472 assert ptr
473 return _create_from_ptr_and_get_ref(ptr)
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
484 status = native_bt.value_array_set_element_by_index(self._ptr, index, ptr)
485 utils._handle_func_status(status)
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
495 status = native_bt.value_array_append_element(self._ptr, ptr)
496 utils._handle_func_status(status)
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
506 def __repr__(self):
507 return '[{}]'.format(', '.join([repr(v) for v in self]))
508
509 def insert(self, value):
510 raise NotImplementedError
511
512
513 class _MapValueKeyIterator(collections.abc.Iterator):
514 def __init__(self, map_obj):
515 self._map_obj = map_obj
516 self._at = 0
517 keys_ptr = native_bt.value_map_get_keys(map_obj._ptr)
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
533 class 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
547 def __ne__(self, other):
548 return _Value.__ne__(self, other)
549
550 def __eq__(self, other):
551 if not isinstance(other, collections.abc.Mapping):
552 return False
553
554 if len(self) != len(other):
555 # early mismatch
556 return False
557
558 for self_key in self:
559 if self_key not in other:
560 return False
561
562 if self[self_key] != other[self_key]:
563 return False
564
565 return True
566
567 def __len__(self):
568 size = native_bt.value_map_get_size(self._ptr)
569 assert size >= 0
570 return size
571
572 def __contains__(self, key):
573 self._check_key_type(key)
574 return native_bt.value_map_has_entry(self._ptr, key)
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)
585 ptr = native_bt.value_map_borrow_entry_value(self._ptr, key)
586 assert ptr
587 return _create_from_ptr_and_get_ref(ptr)
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
601 status = native_bt.value_map_insert_entry(self._ptr, key, ptr)
602 utils._handle_func_status(status)
603
604 def __repr__(self):
605 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
606 return '{{{}}}'.format(', '.join(items))
607
608
609 _TYPE_TO_OBJ = {
610 native_bt.VALUE_TYPE_BOOL: BoolValue,
611 native_bt.VALUE_TYPE_UNSIGNED_INTEGER: UnsignedIntegerValue,
612 native_bt.VALUE_TYPE_SIGNED_INTEGER: SignedIntegerValue,
613 native_bt.VALUE_TYPE_REAL: RealValue,
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.042585 seconds and 4 git commands to generate.