bt2: create_value(): check `numbers` and `collections.abc` types
[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, 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 _handle_status(self, status):
92 _handle_status(status, self._NAME)
93
94 def _check_create_status(self, ptr):
95 if ptr is None:
96 raise bt2.CreationError(
97 'cannot create {} value object'.format(self._NAME.lower()))
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("'{}' object is not a number object".format(other.__class__.__name__))
117
118 def __int__(self):
119 return int(self._value)
120
121 def __float__(self):
122 return float(self._value)
123
124 def __repr__(self):
125 return repr(self._value)
126
127 def __lt__(self, other):
128 return self._value < self._extract_value(other)
129
130 def __eq__(self, other):
131 try:
132 return self._value == self._extract_value(other)
133 except:
134 return False
135
136 def __rmod__(self, other):
137 return self._extract_value(other) % self._value
138
139 def __mod__(self, other):
140 return self._value % self._extract_value(other)
141
142 def __rfloordiv__(self, other):
143 return self._extract_value(other) // self._value
144
145 def __floordiv__(self, other):
146 return self._value // self._extract_value(other)
147
148 def __round__(self, ndigits=None):
149 if ndigits is None:
150 return round(self._value)
151 else:
152 return round(self._value, ndigits)
153
154 def __ceil__(self):
155 return math.ceil(self._value)
156
157 def __floor__(self):
158 return math.floor(self._value)
159
160 def __trunc__(self):
161 return int(self._value)
162
163 def __abs__(self):
164 return abs(self._value)
165
166 def __add__(self, other):
167 return self._value + self._extract_value(other)
168
169 def __radd__(self, other):
170 return self.__add__(other)
171
172 def __neg__(self):
173 return -self._value
174
175 def __pos__(self):
176 return +self._value
177
178 def __mul__(self, other):
179 return self._value * self._extract_value(other)
180
181 def __rmul__(self, other):
182 return self.__mul__(other)
183
184 def __truediv__(self, other):
185 return self._value / self._extract_value(other)
186
187 def __rtruediv__(self, other):
188 return self._extract_value(other) / self._value
189
190 def __pow__(self, exponent):
191 return self._value ** self._extract_value(exponent)
192
193 def __rpow__(self, base):
194 return self._extract_value(base) ** self._value
195
196
197 class _IntegralValue(_NumericValue, numbers.Integral):
198 def __lshift__(self, other):
199 return self._value << self._extract_value(other)
200
201 def __rlshift__(self, other):
202 return self._extract_value(other) << self._value
203
204 def __rshift__(self, other):
205 return self._value >> self._extract_value(other)
206
207 def __rrshift__(self, other):
208 return self._extract_value(other) >> self._value
209
210 def __and__(self, other):
211 return self._value & self._extract_value(other)
212
213 def __rand__(self, other):
214 return self._extract_value(other) & self._value
215
216 def __xor__(self, other):
217 return self._value ^ self._extract_value(other)
218
219 def __rxor__(self, other):
220 return self._extract_value(other) ^ self._value
221
222 def __or__(self, other):
223 return self._value | self._extract_value(other)
224
225 def __ror__(self, other):
226 return self._extract_value(other) | self._value
227
228 def __invert__(self):
229 return ~self._value
230
231
232 class _RealValue(_NumericValue, numbers.Real):
233 pass
234
235
236 class BoolValue(_IntegralValue):
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
248 def __bool__(self):
249 return self._value
250
251 def __repr__(self):
252 return repr(self._value)
253
254 def _value_to_bool(self, value):
255 if isinstance(value, BoolValue):
256 value = value._value
257
258 if not isinstance(value, bool):
259 raise TypeError("'{}' object is not a 'bool' or 'BoolValue' object".format(value.__class__))
260
261 return value
262
263 @property
264 def _value(self):
265 value = native_bt.value_bool_get(self._ptr)
266 return value != 0
267
268 def _set_value(self, value):
269 native_bt.value_bool_set(self._ptr, self._value_to_bool(value))
270
271 value = property(fset=_set_value)
272
273
274 class _IntegerValue(_IntegralValue):
275 def __init__(self, value=None):
276 if value is None:
277 ptr = self._create_default_value()
278 else:
279 ptr = self._create_value(self._value_to_int(value))
280
281 self._check_create_status(ptr)
282 super().__init__(ptr)
283
284 def _value_to_int(self, value):
285 if not isinstance(value, numbers.Integral):
286 raise TypeError('expecting an integral number object')
287
288 value = int(value)
289 self._check_int_range(value)
290 return value
291
292 @property
293 def _value(self):
294 return self._get_value(self._ptr)
295
296 def _prop_set_value(self, value):
297 self._set_value(self._ptr, self._value_to_int(value))
298
299 value = property(fset=_prop_set_value)
300
301
302 class UnsignedIntegerValue(_IntegerValue):
303 _check_int_range = staticmethod(utils._check_uint64)
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)
308
309
310 class SignedIntegerValue(_IntegerValue):
311 _check_int_range = staticmethod(utils._check_int64)
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)
316
317
318 class RealValue(_RealValue):
319 _NAME = 'Real number'
320
321 def __init__(self, value=None):
322 if value is None:
323 ptr = native_bt.value_real_create()
324 else:
325 value = self._value_to_float(value)
326 ptr = native_bt.value_real_create_init(value)
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
338 def _value(self):
339 return native_bt.value_real_get(self._ptr)
340
341 def _set_value(self, value):
342 native_bt.value_real_set(self._ptr, self._value_to_float(value))
343
344 value = property(fset=_set_value)
345
346
347 @functools.total_ordering
348 class StringValue(collections.abc.Sequence, _Value):
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__):
362 value = value._value
363
364 utils._check_str(value)
365 return value
366
367 @property
368 def _value(self):
369 return native_bt.value_string_get(self._ptr)
370
371 def _set_value(self, value):
372 status = native_bt.value_string_set(self._ptr, self._value_to_str(value))
373 self._handle_status(status)
374
375 value = property(fset=_set_value)
376
377 def __eq__(self, other):
378 try:
379 return self._value == self._value_to_str(other)
380 except:
381 return False
382
383 def __lt__(self, other):
384 return self._value < self._value_to_str(other)
385
386 def __bool__(self):
387 return bool(self._value)
388
389 def __repr__(self):
390 return repr(self._value)
391
392 def __str__(self):
393 return self._value
394
395 def __getitem__(self, index):
396 return self._value[index]
397
398 def __len__(self):
399 return len(self._value)
400
401 def __iadd__(self, value):
402 curvalue = self._value
403 curvalue += self._value_to_str(value)
404 self.value = curvalue
405 return self
406
407
408 class _Container:
409 def __bool__(self):
410 return len(self) != 0
411
412 def __delitem__(self, index):
413 raise NotImplementedError
414
415
416 class 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
430 def __eq__(self, other):
431 if not isinstance(other, collections.abc.Sequence):
432 return False
433
434 if len(self) != len(other):
435 # early mismatch
436 return False
437
438 for self_elem, other_elem in zip(self, other):
439 if self_elem != other_elem:
440 return False
441
442 return True
443
444 def __len__(self):
445 size = native_bt.value_array_get_size(self._ptr)
446 assert(size >= 0)
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)
461 ptr = native_bt.value_array_borrow_element_by_index(self._ptr, index)
462 assert(ptr)
463 return _create_from_ptr_and_get_ref(ptr)
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
474 status = native_bt.value_array_set_element_by_index(
475 self._ptr, index, ptr)
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
486 status = native_bt.value_array_append_element(self._ptr, ptr)
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
497 def __repr__(self):
498 return '[{}]'.format(', '.join([repr(v) for v in self]))
499
500 def insert(self, value):
501 raise NotImplementedError
502
503
504 class _MapValueKeyIterator(collections.abc.Iterator):
505 def __init__(self, map_obj):
506 self._map_obj = map_obj
507 self._at = 0
508 keys_ptr = native_bt.value_map_get_keys(map_obj._ptr)
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
524 class 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
538 def __ne__(self, other):
539 return _Value.__ne__(self, other)
540
541 def __eq__(self, other):
542 if not isinstance(other, collections.abc.Mapping):
543 return False
544
545 if len(self) != len(other):
546 # early mismatch
547 return False
548
549 for self_key in self:
550 if self_key not in other:
551 return False
552
553 if self[self_key] != other[self_key]:
554 return False
555
556 return True
557
558 def __len__(self):
559 size = native_bt.value_map_get_size(self._ptr)
560 assert(size >= 0)
561 return size
562
563 def __contains__(self, key):
564 self._check_key_type(key)
565 return native_bt.value_map_has_entry(self._ptr, key)
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)
576 ptr = native_bt.value_map_borrow_entry_value(self._ptr, key)
577 assert(ptr)
578 return _create_from_ptr_and_get_ref(ptr)
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
592 status = native_bt.value_map_insert_entry(self._ptr, key, ptr)
593 self._handle_status(status)
594
595 def __repr__(self):
596 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
597 return '{{{}}}'.format(', '.join(items))
598
599
600 _TYPE_TO_OBJ = {
601 native_bt.VALUE_TYPE_BOOL: BoolValue,
602 native_bt.VALUE_TYPE_UNSIGNED_INTEGER: UnsignedIntegerValue,
603 native_bt.VALUE_TYPE_SIGNED_INTEGER: SignedIntegerValue,
604 native_bt.VALUE_TYPE_REAL: RealValue,
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.041279 seconds and 5 git commands to generate.