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