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