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