~lttng/babeltrace/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2017 Philippe Proulx <pproulx@efficios.com>

from bt2 import native_bt
from bt2 import object as bt2_object
from bt2 import utils as bt2_utils
from bt2 import error as bt2_error
import collections.abc
import functools
import numbers
import math
import abc


def _create_from_ptr_template(ptr, object_map):
    if ptr is None:
        return

    # bt_value_null is translated to None.  However, we are given a reference
    # to it that we are not going to manage anymore, since we don't create a
    # Python wrapper for it.  Therefore put that reference immediately.
    if ptr == native_bt.value_null:
        _Value._put_ref(ptr)
        return

    typeid = native_bt.value_get_type(ptr)
    return object_map[typeid]._create_from_ptr(ptr)


def _create_from_ptr(ptr):
    return _create_from_ptr_template(ptr, _TYPE_TO_OBJ)


def _create_from_const_ptr(ptr):
    return _create_from_ptr_template(ptr, _TYPE_TO_CONST_OBJ)


def _create_from_ptr_and_get_ref_template(ptr, object_map):
    if ptr is None or ptr == native_bt.value_null:
        return

    typeid = native_bt.value_get_type(ptr)
    return object_map[typeid]._create_from_ptr_and_get_ref(ptr)


def _create_from_ptr_and_get_ref(ptr):
    return _create_from_ptr_and_get_ref_template(ptr, _TYPE_TO_OBJ)


def _create_from_const_ptr_and_get_ref(ptr):
    return _create_from_ptr_and_get_ref_template(ptr, _TYPE_TO_CONST_OBJ)


def create_value(value):
    if value is None:
        # null value object
        return

    if isinstance(value, _Value):
        return value

    if isinstance(value, bool):
        return BoolValue(value)

    if isinstance(value, numbers.Integral):
        return SignedIntegerValue(value)

    if isinstance(value, numbers.Real):
        return RealValue(value)

    if isinstance(value, str):
        return StringValue(value)

    if isinstance(value, collections.abc.Sequence):
        return ArrayValue(value)

    if isinstance(value, collections.abc.Mapping):
        return MapValue(value)

    raise TypeError(
        "cannot create value object from '{}' object".format(value.__class__.__name__)
    )


class _ValueConst(bt2_object._SharedObject, metaclass=abc.ABCMeta):
    @staticmethod
    def _get_ref(ptr):
        native_bt.value_get_ref(ptr)

    @staticmethod
    def _put_ref(ptr):
        native_bt.value_put_ref(ptr)

    _create_value_from_ptr = staticmethod(_create_from_const_ptr)
    _create_value_from_ptr_and_get_ref = staticmethod(
        _create_from_const_ptr_and_get_ref
    )

    def __ne__(self, other):
        return not (self == other)

    def _check_create_status(self, ptr):
        if ptr is None:
            raise bt2_error._MemoryError(
                "cannot create {} value object".format(self._NAME.lower())
            )


class _Value(_ValueConst):
    _create_value_from_ptr = staticmethod(_create_from_ptr)
    _create_value_from_ptr_and_get_ref = staticmethod(_create_from_ptr_and_get_ref)


@functools.total_ordering
class _NumericValueConst(_ValueConst):
    @staticmethod
    def _extract_value(other):
        if isinstance(other, _BoolValueConst) or isinstance(other, bool):
            return bool(other)

        if isinstance(other, numbers.Integral):
            return int(other)

        if isinstance(other, numbers.Real):
            return float(other)

        if isinstance(other, numbers.Complex):
            return complex(other)

        raise TypeError(
            "'{}' object is not a number object".format(other.__class__.__name__)
        )

    def __int__(self):
        return int(self._value)

    def __float__(self):
        return float(self._value)

    def __repr__(self):
        return repr(self._value)

    def __lt__(self, other):
        return self._value < self._extract_value(other)

    def __eq__(self, other):
        try:
            return self._value == self._extract_value(other)
        except Exception:
            return False

    def __rmod__(self, other):
        return self._extract_value(other) % self._value

    def __mod__(self, other):
        return self._value % self._extract_value(other)

    def __rfloordiv__(self, other):
        return self._extract_value(other) // self._value

    def __floordiv__(self, other):
        return self._value // self._extract_value(other)

    def __round__(self, ndigits=None):
        if ndigits is None:
            return round(self._value)
        else:
            return round(self._value, ndigits)

    def __ceil__(self):
        return math.ceil(self._value)

    def __floor__(self):
        return math.floor(self._value)

    def __trunc__(self):
        return int(self._value)

    def __abs__(self):
        return abs(self._value)

    def __add__(self, other):
        return self._value + self._extract_value(other)

    def __radd__(self, other):
        return self.__add__(other)

    def __neg__(self):
        return -self._value

    def __pos__(self):
        return +self._value

    def __mul__(self, other):
        return self._value * self._extract_value(other)

    def __rmul__(self, other):
        return self.__mul__(other)

    def __truediv__(self, other):
        return self._value / self._extract_value(other)

    def __rtruediv__(self, other):
        return self._extract_value(other) / self._value

    def __pow__(self, exponent):
        return self._value ** self._extract_value(exponent)

    def __rpow__(self, base):
        return self._extract_value(base) ** self._value


class _NumericValue(_NumericValueConst, _Value):
    pass


class _IntegralValueConst(_NumericValueConst, numbers.Integral):
    def __lshift__(self, other):
        return self._value << self._extract_value(other)

    def __rlshift__(self, other):
        return self._extract_value(other) << self._value

    def __rshift__(self, other):
        return self._value >> self._extract_value(other)

    def __rrshift__(self, other):
        return self._extract_value(other) >> self._value

    def __and__(self, other):
        return self._value & self._extract_value(other)

    def __rand__(self, other):
        return self._extract_value(other) & self._value

    def __xor__(self, other):
        return self._value ^ self._extract_value(other)

    def __rxor__(self, other):
        return self._extract_value(other) ^ self._value

    def __or__(self, other):
        return self._value | self._extract_value(other)

    def __ror__(self, other):
        return self._extract_value(other) | self._value

    def __invert__(self):
        return ~self._value


class _IntegralValue(_IntegralValueConst, _NumericValue):
    pass


class _BoolValueConst(_IntegralValueConst):
    _NAME = "Const boolean"

    def __bool__(self):
        return self._value

    def __repr__(self):
        return repr(self._value)

    @property
    def _value(self):
        value = native_bt.value_bool_get(self._ptr)
        return value != 0


class BoolValue(_BoolValueConst, _IntegralValue):
    _NAME = "Boolean"

    def __init__(self, value=None):
        if value is None:
            ptr = native_bt.value_bool_create()
        else:
            ptr = native_bt.value_bool_create_init(self._value_to_bool(value))

        self._check_create_status(ptr)
        super().__init__(ptr)

    @classmethod
    def _value_to_bool(cls, value):
        if isinstance(value, _BoolValueConst):
            value = value._value

        if not isinstance(value, bool):
            raise TypeError(
                "'{}' object is not a 'bool', 'BoolValue', or '_BoolValueConst' object".format(
                    value.__class__
                )
            )

        return value

    def _set_value(self, value):
        native_bt.value_bool_set(self._ptr, self._value_to_bool(value))

    value = property(fset=_set_value)


class _IntegerValueConst(_IntegralValueConst):
    @property
    def _value(self):
        return self._get_value(self._ptr)


class _IntegerValue(_IntegerValueConst, _IntegralValue):
    def __init__(self, value=None):
        if value is None:
            ptr = self._create_default_value()
        else:
            ptr = self._create_value(self._value_to_int(value))

        self._check_create_status(ptr)
        super().__init__(ptr)

    @classmethod
    def _value_to_int(cls, value):
        if not isinstance(value, numbers.Integral):
            raise TypeError("expecting an integral number object")

        value = int(value)
        cls._check_int_range(value)
        return value

    def _prop_set_value(self, value):
        self._set_value(self._ptr, self._value_to_int(value))

    value = property(fset=_prop_set_value)


class _UnsignedIntegerValueConst(_IntegerValueConst):
    _NAME = "Const unsigned integer"
    _get_value = staticmethod(native_bt.value_integer_unsigned_get)


class UnsignedIntegerValue(_UnsignedIntegerValueConst, _IntegerValue):
    _NAME = "Unsigned integer"
    _check_int_range = staticmethod(bt2_utils._check_uint64)
    _create_default_value = staticmethod(native_bt.value_integer_unsigned_create)
    _create_value = staticmethod(native_bt.value_integer_unsigned_create_init)
    _set_value = staticmethod(native_bt.value_integer_unsigned_set)


class _SignedIntegerValueConst(_IntegerValueConst):
    _NAME = "Const signed integer"
    _get_value = staticmethod(native_bt.value_integer_signed_get)


class SignedIntegerValue(_SignedIntegerValueConst, _IntegerValue):
    _NAME = "Signed integer"
    _check_int_range = staticmethod(bt2_utils._check_int64)
    _create_default_value = staticmethod(native_bt.value_integer_signed_create)
    _create_value = staticmethod(native_bt.value_integer_signed_create_init)
    _set_value = staticmethod(native_bt.value_integer_signed_set)


class _RealValueConst(_NumericValueConst, numbers.Real):
    _NAME = "Const real number"

    @property
    def _value(self):
        return native_bt.value_real_get(self._ptr)


class RealValue(_RealValueConst, _NumericValue):
    _NAME = "Real number"

    def __init__(self, value=None):
        if value is None:
            ptr = native_bt.value_real_create()
        else:
            value = self._value_to_float(value)
            ptr = native_bt.value_real_create_init(value)

        self._check_create_status(ptr)
        super().__init__(ptr)

    @classmethod
    def _value_to_float(cls, value):
        if not isinstance(value, numbers.Real):
            raise TypeError("expecting a real number object")

        return float(value)

    def _set_value(self, value):
        native_bt.value_real_set(self._ptr, self._value_to_float(value))

    value = property(fset=_set_value)


@functools.total_ordering
class _StringValueConst(collections.abc.Sequence, _Value):
    _NAME = "Const string"

    @classmethod
    def _value_to_str(cls, value):
        if isinstance(value, _StringValueConst):
            value = value._value

        bt2_utils._check_str(value)
        return value

    @property
    def _value(self):
        return native_bt.value_string_get(self._ptr)

    def __eq__(self, other):
        try:
            return self._value == self._value_to_str(other)
        except Exception:
            return False

    def __lt__(self, other):
        return self._value < self._value_to_str(other)

    def __bool__(self):
        return bool(self._value)

    def __repr__(self):
        return repr(self._value)

    def __str__(self):
        return self._value

    def __getitem__(self, index):
        return self._value[index]

    def __len__(self):
        return len(self._value)

    def __contains__(self, item):
        return self._value_to_str(item) in self._value


class StringValue(_StringValueConst, _Value):
    _NAME = "String"

    def __init__(self, value=None):
        if value is None:
            ptr = native_bt.value_string_create()
        else:
            ptr = native_bt.value_string_create_init(self._value_to_str(value))

        self._check_create_status(ptr)
        super().__init__(ptr)

    def _set_value(self, value):
        status = native_bt.value_string_set(self._ptr, self._value_to_str(value))
        bt2_utils._handle_func_status(status)

    value = property(fset=_set_value)

    def __iadd__(self, value):
        curvalue = self._value
        curvalue += self._value_to_str(value)
        self.value = curvalue
        return self


class _ContainerConst:
    def __bool__(self):
        return len(self) != 0


class _Container(_ContainerConst):
    def __delitem__(self, index):
        raise NotImplementedError


class _ArrayValueConst(_ContainerConst, collections.abc.Sequence, _ValueConst):
    _NAME = "Const array"
    _borrow_element_by_index = staticmethod(
        native_bt.value_array_borrow_element_by_index_const
    )
    _is_const = True

    def __eq__(self, other):
        if not isinstance(other, collections.abc.Sequence):
            return False

        if len(self) != len(other):
            # early mismatch
            return False

        for self_elem, other_elem in zip(self, other):
            if self_elem != other_elem:
                return False

        return True

    def __len__(self):
        size = native_bt.value_array_get_length(self._ptr)
        assert size >= 0
        return size

    def _check_index(self, index):
        # TODO: support slices also
        if not isinstance(index, numbers.Integral):
            raise TypeError(
                "'{}' object is not an integral number object: invalid index".format(
                    index.__class__.__name__
                )
            )

        index = int(index)

        if index < 0 or index >= len(self):
            raise IndexError("array value object index is out of range")

    def __getitem__(self, index):
        self._check_index(index)
        ptr = self._borrow_element_by_index(self._ptr, index)
        assert ptr
        return self._create_value_from_ptr_and_get_ref(ptr)

    def __repr__(self):
        return "[{}]".format(", ".join([repr(v) for v in self]))


class ArrayValue(_ArrayValueConst, _Container, collections.abc.MutableSequence, _Value):
    _NAME = "Array"
    _borrow_element_by_index = staticmethod(
        native_bt.value_array_borrow_element_by_index
    )

    def __init__(self, value=None):
        ptr = native_bt.value_array_create()
        self._check_create_status(ptr)
        super().__init__(ptr)

        # Python will raise a TypeError if there's anything wrong with
        # the iterable protocol.
        if value is not None:
            for elem in value:
                self.append(elem)

    def __setitem__(self, index, value):
        self._check_index(index)
        value = create_value(value)

        if value is None:
            ptr = native_bt.value_null
        else:
            ptr = value._ptr

        status = native_bt.value_array_set_element_by_index(self._ptr, index, ptr)
        bt2_utils._handle_func_status(status)

    def append(self, value):
        value = create_value(value)

        if value is None:
            ptr = native_bt.value_null
        else:
            ptr = value._ptr

        status = native_bt.value_array_append_element(self._ptr, ptr)
        bt2_utils._handle_func_status(status)

    def __iadd__(self, iterable):
        # Python will raise a TypeError if there's anything wrong with
        # the iterable protocol.
        for elem in iterable:
            self.append(elem)

        return self

    def insert(self, value):
        raise NotImplementedError


class _MapValueKeyIterator(collections.abc.Iterator):
    def __init__(self, map_obj):
        self._map_obj = map_obj
        self._at = 0
        keys_ptr = native_bt.value_map_get_keys(map_obj._ptr)

        if keys_ptr is None:
            raise RuntimeError("unexpected error: cannot get map value object keys")

        self._keys = _create_from_ptr(keys_ptr)

    def __next__(self):
        if self._at == len(self._map_obj):
            raise StopIteration

        key = self._keys[self._at]
        self._at += 1
        return str(key)


class _MapValueConst(_ContainerConst, collections.abc.Mapping, _ValueConst):
    _NAME = "Const map"
    _borrow_entry_value_ptr = staticmethod(native_bt.value_map_borrow_entry_value_const)

    def __ne__(self, other):
        return _Value.__ne__(self, other)

    def __eq__(self, other):
        if not isinstance(other, collections.abc.Mapping):
            return False

        if len(self) != len(other):
            # early mismatch
            return False

        for self_key in self:
            if self_key not in other:
                return False

            if self[self_key] != other[self_key]:
                return False

        return True

    def __len__(self):
        size = native_bt.value_map_get_size(self._ptr)
        assert size >= 0
        return size

    def __contains__(self, key):
        self._check_key_type(key)
        return native_bt.value_map_has_entry(self._ptr, key)

    def _check_key_type(self, key):
        bt2_utils._check_str(key)

    def _check_key(self, key):
        if key not in self:
            raise KeyError(key)

    def __getitem__(self, key):
        self._check_key(key)
        ptr = self._borrow_entry_value_ptr(self._ptr, key)
        assert ptr
        return self._create_value_from_ptr_and_get_ref(ptr)

    def __iter__(self):
        return _MapValueKeyIterator(self)

    def __repr__(self):
        items = ["{}: {}".format(repr(k), repr(v)) for k, v in self.items()]
        return "{{{}}}".format(", ".join(items))


class MapValue(_MapValueConst, _Container, collections.abc.MutableMapping, _Value):
    _NAME = "Map"
    _borrow_entry_value_ptr = staticmethod(native_bt.value_map_borrow_entry_value)

    def __init__(self, value=None):
        ptr = native_bt.value_map_create()
        self._check_create_status(ptr)
        super().__init__(ptr)

        # Python will raise a TypeError if there's anything wrong with
        # the iterable/mapping protocol.
        if value is not None:
            for key, elem in value.items():
                self[key] = elem

    def __setitem__(self, key, value):
        self._check_key_type(key)
        value = create_value(value)

        if value is None:
            ptr = native_bt.value_null
        else:
            ptr = value._ptr

        status = native_bt.value_map_insert_entry(self._ptr, key, ptr)
        bt2_utils._handle_func_status(status)


_TYPE_TO_OBJ = {
    native_bt.VALUE_TYPE_BOOL: BoolValue,
    native_bt.VALUE_TYPE_UNSIGNED_INTEGER: UnsignedIntegerValue,
    native_bt.VALUE_TYPE_SIGNED_INTEGER: SignedIntegerValue,
    native_bt.VALUE_TYPE_REAL: RealValue,
    native_bt.VALUE_TYPE_STRING: StringValue,
    native_bt.VALUE_TYPE_ARRAY: ArrayValue,
    native_bt.VALUE_TYPE_MAP: MapValue,
}

_TYPE_TO_CONST_OBJ = {
    native_bt.VALUE_TYPE_BOOL: _BoolValueConst,
    native_bt.VALUE_TYPE_UNSIGNED_INTEGER: _UnsignedIntegerValueConst,
    native_bt.VALUE_TYPE_SIGNED_INTEGER: _SignedIntegerValueConst,
    native_bt.VALUE_TYPE_REAL: _RealValueConst,
    native_bt.VALUE_TYPE_STRING: _StringValueConst,
    native_bt.VALUE_TYPE_ARRAY: _ArrayValueConst,
    native_bt.VALUE_TYPE_MAP: _MapValueConst,
}