• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Nic30 / pyMathBitPrecise / 1021c388-66bb-4d89-a469-3f139b55e4e2

26 Oct 2024 02:03PM UTC coverage: 76.055% (-1.6%) from 77.639%
1021c388-66bb-4d89-a469-3f139b55e4e2

push

circleci

Nic30
style(Bits3t): better err msgs

200 of 286 branches covered (69.93%)

Branch coverage included in aggregate %.

0 of 1 new or added line in 1 file covered. (0.0%)

36 existing lines in 1 file now uncovered.

737 of 946 relevant lines covered (77.91%)

0.78 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.54
/pyMathBitPrecise/bits3t.py
1
#!/usr/bin/env python3
2
# -*- coding: UTF-8 -*-
3

4
from copy import copy
1✔
5
from enum import Enum
1✔
6
from math import log2, ceil
1✔
7
from operator import le, ge, gt, lt, ne, eq, and_, or_, xor, sub, add
1✔
8
from typing import Union, Optional
1✔
9

10
from pyMathBitPrecise.array3t import Array3t
1✔
11
from pyMathBitPrecise.bit_utils import mask, get_bit, get_bit_range, \
1✔
12
    to_signed, set_bit_range, bit_set_to, bit_field, to_unsigned, INT_BASES, \
13
    ValidityError, normalize_slice
14
from pyMathBitPrecise.bits3t_vld_masks import vld_mask_for_xor, vld_mask_for_and, \
1✔
15
    vld_mask_for_or
16

17

18
class Bits3t():
1✔
19
    """
20
    Meta type for integer of specified size where
21
    each bit can be '1', '0' or 'X' for undefined value.
22

23
    :ivar ~.bit_length: number representation of value of this type
24
    :ivar ~.signed: flag which tells if this type is signed or not
25
    :ivar ~._all_mask: cached value of mask for all bits
26
    :ivar ~.name: name for annotation
27
    :ivar ~.force_vector: use always hdl vector type
28
            (for example std_logic_vector(0 downto 0)
29
             instead of std_logic in VHDL,
30
             wire[1] instead of wire)
31
    :ivar ~.strict_sign: same thing as strict_width just for signed/unsigned
32
    :ivar ~.strict_width: if True the arithmetic, bitwise
33
        and comparison operators can be performed only on value
34
        of this exact same width
35
    :note: operation is not strict if at least one operand
36
        does not have strict flag set,
37
        the result width/sign is taken from other operand
38
        (or first if both are not strict)
39
    """
40

41
    def __init__(self, bit_length: int, signed:Optional[bool]=False, name: Optional[str]=None,
1✔
42
                 force_vector=False,
43
                 strict_sign=True, strict_width=True):
44
        if force_vector and bit_length != 1:
1!
45
            assert bit_length == 1, "force_vector=True is appliable only for 1b values"
×
46
        self._bit_length = bit_length
1✔
47
        self.signed = signed
1✔
48
        self._all_mask = mask(bit_length)
1✔
49
        self.name = name
1✔
50
        self.force_vector = force_vector
1✔
51
        self.strict_sign = strict_sign
1✔
52
        self.strict_width = strict_width
1✔
53

54
    def __copy__(self):
1✔
55
        t = self.__class__(self._bit_length, signed=self.signed,
1✔
56
                           name=self.name,
57
                           force_vector=self.force_vector,
58
                           strict_sign=self.strict_sign,
59
                           strict_width=self.strict_width)
60
        return t
1✔
61

62
    def all_mask(self):
1✔
63
        """
64
        :return: mask for bites of this type ( 0b111 for Bits(3) )
65
        """
66
        return self._all_mask
1✔
67

68
    def bit_length(self):
1✔
69
        """
70
        :return: number of bits required for representation
71
            of value of this type
72
        """
73
        return self._bit_length
1✔
74

75
    def __eq__(self, other):
1✔
76
        return (self is other
×
77
                or (isinstance(other, Bits3t)
78
                    and self._bit_length == other._bit_length
79
                    and self.name == other.name
80
                    and self.force_vector == other.force_vector
81
                    and self.strict_sign == other.strict_sign
82
                    and self.strict_width == other.strict_width
83
                    and self.signed == other.signed
84
                    )
85
                )
86

87
    def _normalize_val_and_mask(self, val, vld_mask):
1✔
88
        if val is None:
1✔
89
            vld = 0
1✔
90
            val = 0
1✔
91
            assert vld_mask is None or vld_mask == 0
1✔
92
        else:
93
            all_mask = self.all_mask()
1✔
94
            w = self._bit_length
1✔
95
            if isinstance(val, int):
1✔
96
                pass
1✔
97
            elif isinstance(val, bytes):
1!
98
                val = int.from_bytes(
×
99
                    val, byteorder="little", signed=bool(self.signed))
100
            elif isinstance(val, str):
1✔
101
                if not (val.startswith("0") and len(val) > 2):
1!
102
                    raise ValueError(val)
×
103

104
                base = INT_BASES[val[1]]
1✔
105
                try:
1✔
106
                    _val = int(val[2:], base)
1✔
107
                except ValueError:
1✔
108
                    _val = None
1✔
109

110
                if _val is None:
1!
111
                    assert vld_mask is None
1✔
112
                    val = val.lower()
1✔
113
                    if base == 10 and "x" in val:
1✔
114
                        raise NotImplementedError()
115
                    v = 0
1✔
116
                    m = 0
1✔
117
                    bits_per_char = ceil(log2(base))
1✔
118
                    char_mask = mask(bits_per_char)
1✔
119
                    for digit in val[2:]:
1✔
120
                        v <<= bits_per_char
1✔
121
                        m <<= bits_per_char
1✔
122
                        if digit == "x":
1✔
123
                            pass
1✔
124
                        else:
125
                            m |= char_mask
1✔
126
                            v |= int(digit, base)
1✔
127
                    val = v
1✔
128
                    vld_mask = m
1✔
129
                else:
130
                    val = _val
×
131
            else:
132
                try:
1✔
133
                    val = int(val)
1✔
134
                except TypeError as e:
1✔
135
                    if isinstance(val, Enum):
1!
136
                        val = int(val.value)
×
137
                    else:
138
                        raise e
1✔
139

140
            if vld_mask is None:
1✔
141
                vld = all_mask
1✔
142
            else:
143
                if vld_mask > all_mask or vld_mask < 0:
1!
NEW
144
                    raise ValueError("Mask in incorrect format", vld_mask, w, all_mask)
×
145
                vld = vld_mask
1✔
146

147
            if val < 0:
1✔
148
                if not self.signed:
1✔
149
                    raise ValueError("Negative value for unsigned int")
1✔
150
                _val = to_signed(val & all_mask, w)
1✔
151
                if _val != val:
1✔
152
                    raise ValueError("Too large value", val, _val)
1✔
153
                val = _val
1✔
154
            else:
155
                if self.signed:
1✔
156
                    msb = 1 << (w - 1)
1✔
157
                    if msb & val:
1✔
158
                        if val > 0:
1!
159
                            raise ValueError(
1✔
160
                                "Value too large to fit in this type", val)
161

162
                if val & all_mask != val:
1✔
163
                    raise ValueError(
1✔
164
                        "Not enough bits to represent value",
165
                        val, "on", w, "bit" if w == 1 else "bits", val & all_mask)
166
                val = val & vld
1✔
167
        return val, vld
1✔
168

169
    def _from_py(self, val, vld_mask):
1✔
170
        """
171
        from_py without normalization
172
        """
173
        return Bits3val(self, val, vld_mask)
1✔
174

175
    def from_py(self, val: Union[int, bytes, str, Enum],
1✔
176
                vld_mask: Optional[int]=None) -> "Bits3val":
177
        """
178
        Construct value from pythonic value
179
        :note: str value has to start with base specifier (0b, 0h)
180
            and is much slower than the value specified
181
            by 'val' and 'vld_mask'. Does support x.
182
        """
183
        val, vld_mask = self._normalize_val_and_mask(val, vld_mask)
1✔
184
        return Bits3val(self, val, vld_mask)
1✔
185

186
    def __getitem__(self, i):
1✔
187
        ":return: an item from this array"
188
        return Array3t(self, i)
1✔
189

190
    def __hash__(self):
1✔
191
        return hash((
×
192
            self._bit_length,
193
            self.signed,
194
            self._all_mask,
195
            self.name,
196
            self.force_vector,
197
            self.strict_sign,
198
            self.strict_width
199
        ))
200

201
    def __repr__(self):
202
        """
203
        :param indent: number of indentation
204
        :param withAddr: if is not None is used as a additional
205
            information about on which address this type is stored
206
            (used only by HStruct)
207
        :param expandStructs: expand HStructTypes (used by HStruct and HArray)
208
        """
209
        constr = []
210
        if self.name is not None:
211
            constr.append(f'"{self.name:s}"')
212
        c = self.bit_length()
213

214
        if self.signed:
215
            sign = "i"
216
        elif self.signed is False:
217
            sign = "u"
218
        else:
219
            sign = "b"
220

221
        constr.append(f"{sign:s}{c:d}")
222
        if self.force_vector:
223
            constr.append("force_vector")
224

225
        if not self.strict_sign:
226
            constr.append("strict_sign=False")
227
        if not self.strict_width:
228
            constr.append("strict_width=False")
229

230
        return "<%s %s>" % (self.__class__.__name__,
231
                             ", ".join(constr))
232

233

234
class Bits3val():
1✔
235
    """
236
    Class for value of `Bits3t` type
237

238
    :ivar ~._dtype: reference on type of this value
239
    :ivar ~.val: always unsigned representation int value
240
    :ivar ~.vld_mask: always unsigned value of the mask, if bit in mask is '0'
241
            the corresponding bit in val is invalid
242
    """
243
    _BOOL = Bits3t(1)
1✔
244
    _SIGNED_FOR_SLICE_CONCAT_RESULT = False
1✔
245

246
    def __init__(self, t: Bits3t, val: int, vld_mask: int):
1✔
247
        if not isinstance(t, Bits3t):
1!
248
            raise TypeError(t)
×
249
        if type(val) != int:
1!
250
            raise TypeError(val)
×
251
        if type(vld_mask) != int:
1!
252
            raise TypeError(vld_mask)
×
253
        self._dtype = t
1✔
254
        self.val = val
1✔
255
        self.vld_mask = vld_mask
1✔
256

257
    def __copy__(self):
1✔
258
        return self.__class__(self._dtype, self.val, self.vld_mask)
1✔
259

260
    def to_py(self) -> int:
1✔
261
        return int(self)
×
262

263
    def _is_full_valid(self) -> bool:
1✔
264
        """
265
        :return: True if all bits in value are valid
266
        """
267
        return self.vld_mask == self._dtype.all_mask()
1✔
268

269
    def __int__(self) -> int:
1✔
270
        "int(self)"
271
        if not self._is_full_valid():
1✔
272
            raise ValidityError(self)
1✔
273

274
        return self.val
1✔
275

276
    def __bool__(self) -> bool:
1✔
277
        "bool(self)"
278
        return bool(self.__int__())
1✔
279

280
    def _auto_cast(self, dtype):
1✔
281
        """
282
        Cast value to a compatible type
283
        """
284
        return dtype.from_py(self.val, self.vld_mask)
×
285

286
    def cast_sign(self, signed: Optional[bool]) -> "Bits3val":
1✔
287
        """
288
        Cast signed-unsigned value
289
        """
290
        t = self._dtype
1✔
291
        if t.signed == signed:
1!
292
            return self
×
293
        selfSign = t.signed
1✔
294
        v = self.__copy__()
1✔
295
        m = t._all_mask
1✔
296
        _v = v.val
1✔
297

298
        if selfSign and not signed:
1✔
299
            if _v < 0:
1!
300
                v.val = m + _v + 1
1✔
301
        elif not selfSign and signed:
1!
302
            w = t.bit_length()
1✔
303
            v.val = to_signed(_v, w)
1✔
304

305
        v._dtype = v._dtype.__copy__()
1✔
306
        v._dtype = self._dtype.__copy__()
1✔
307
        v._dtype.signed = signed
1✔
308
        return v
1✔
309

310
    def cast(self, t: Bits3t) -> "Bits3val":
1✔
311
        """
312
        C++: static_cast<t>(self)
313

314
        :note: no sign extension
315
        """
316
        v = self.__copy__()
1✔
317
        v._dtype = t
1✔
318
        m = t.all_mask()
1✔
319
        v.val &= m
1✔
320
        v.vld_mask &= m
1✔
321
        if t.signed:
1✔
322
            v.val = to_signed(v.val, t.bit_length())
1✔
323
        return v
1✔
324

325
    def _concat(self, other: "Bits3val") -> "Bits3val":
1✔
326
        """
327
        Concatenate two bit vectors together (self will be at MSB side)
328
        Verilog: {self, other}, VHDL: self & other
329
        """
330
        if not isinstance(other, Bits3val):
1✔
331
            raise TypeError(other)
1✔
332
        w = self._dtype.bit_length()
1✔
333
        other_w = other._dtype.bit_length()
1✔
334
        resWidth = w + other_w
1✔
335
        resT = self._dtype.__class__(resWidth, signed=self._SIGNED_FOR_SLICE_CONCAT_RESULT)
1✔
336
        other_val = other.val
1✔
337
        if other_val < 0:
1!
338
            other_val = to_unsigned(other_val, other_w)
×
339
        v = self.__copy__()
1✔
340
        if v.val < 0:
1!
341
            v.val = to_unsigned(v.val, w)
×
342
        v.val = (v.val << other_w) | other_val
1✔
343
        v.vld_mask = (v.vld_mask << other_w) | other.vld_mask
1✔
344
        v._dtype = resT
1✔
345
        return v
1✔
346

347
    def __getitem__(self, key: Union[int, slice, "Bits3val"]) -> "Bits3val":
1✔
348
        "self[key]"
349
        if isinstance(key, slice):
1✔
350
            firstBitNo, size = normalize_slice(key, self._dtype.bit_length())
1✔
351
            val = get_bit_range(self.val, firstBitNo, size)
1✔
352
            vld = get_bit_range(self.vld_mask, firstBitNo, size)
1✔
353
        elif isinstance(key, (int, Bits3val)):
1✔
354
            size = 1
1✔
355
            try:
1✔
356
                _i = int(key)
1✔
357
            except ValidityError:
×
358
                _i = None
×
359

360
            if _i is None:
1!
361
                val = 0
×
362
                vld = 0
×
363
            else:
364
                if _i < 0 or _i >= self._dtype.bit_length():
1✔
365
                    raise IndexError("Index out of range", _i)
1✔
366

367
                val = get_bit(self.val, _i)
1✔
368
                vld = get_bit(self.vld_mask, _i)
1✔
369
        else:
370
            raise TypeError(key)
1✔
371

372
        new_t = self._dtype.__class__(size, signed=self._SIGNED_FOR_SLICE_CONCAT_RESULT)
1✔
373
        return new_t._from_py(val, vld)
1✔
374

375
    def __setitem__(self, index: Union[slice, int, "Bits3val"],
1✔
376
                    value: Union["Bits3val", int]):
377
        "An item assignment operator self[index] = value."
378
        if isinstance(index, slice):
1✔
379
            firstBitNo, size = normalize_slice(index, self._dtype.bit_length())
1✔
380
            if isinstance(value, Bits3val):
1!
381
                v = value.val
×
382
                m = value.vld_mask
×
383
            else:
384
                v = value
1✔
385
                m = mask(size)
1✔
386

387
            self.val = set_bit_range(self.val, firstBitNo, size, v)
1✔
388
            self.vld_mask = set_bit_range(
1✔
389
                self.vld_mask, firstBitNo, size, m)
390
        else:
391
            if index is None:
1✔
392
                raise TypeError(index)
1✔
393
            try:
1✔
394
                _i = int(index)
1✔
395
            except ValidityError:
×
396
                _i = None
×
397

398
            if _i is None:
1!
399
                self.val = 0
×
400
                self.vld_mask = 0
×
401
            else:
402
                if value is None:
1✔
403
                    v = 0
1✔
404
                    m = 0
1✔
405
                elif isinstance(value, Bits3val):
1!
406
                    v = value.val
×
407
                    m = value.vld_mask
×
408
                else:
409
                    v = value
1✔
410
                    m = 0b1
1✔
411
                try:
1✔
412
                    index = int(index)
1✔
413
                except ValidityError:
×
414
                    index = None
×
415
                if index is None:
1!
416
                    self.val = 0
×
417
                    self.vld_mask = 0
×
418
                else:
419
                    self.val = bit_set_to(self.val, index, v)
1✔
420
                    self.vld_mask = bit_set_to(self.vld_mask, index, m)
1✔
421

422
    def __invert__(self) -> "Bits3val":
1✔
423
        "Operator ~x."
424
        v = self.__copy__()
1✔
425
        v.val = ~v.val
1✔
426
        w = v._dtype.bit_length()
1✔
427
        v.val &= mask(w)
1✔
428
        if self._dtype.signed:
1✔
429
            v.val = to_signed(v.val, w)
1✔
430
        return v
1✔
431

432
    def __neg__(self):
1✔
433
        "Operator -x."
434
        if not self._dtype.signed:
1✔
435
            raise TypeError("- operator is defined only for signed")
1✔
436

437
        v = self.__copy__()
1✔
438
        _v = -v.val
1✔
439
        _max = self._dtype.all_mask() >> 1
1✔
440
        _min = -_max - 1
1✔
441
        if _v > _max:
1✔
442
            _v = _min + (_v - _max - 1)
1✔
443
        elif _v < _min:
1!
444
            _v = _max - (_v - _min + 1)
×
445
        v.val = _v
1✔
446
        return v
1✔
447

448
    def __hash__(self):
1✔
449
        return hash((self._dtype, self.val, self.vld_mask))
×
450

451
    def _is(self, other):
1✔
452
        """check if other is object with same values"""
453
        return isinstance(other, Bits3val)\
×
454
            and self._dtype == other._dtype\
455
            and self.val == other.val\
456
            and self.vld_mask == other.vld_mask
457

458
    def _eq(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
459
        """
460
        Operator self._eq(other) as self == other
461
        == is not overridden in order to prevent tricky behavior if hashing partially valid values
462
        """
463
        return bitsCmp__val(self, other, eq)
1✔
464

465
    def __req__(self, other: int) -> "Bits3val":
1✔
466
        "Operator ==."
467
        return bitsCmp__val(self._dtype.from_py(other), self, eq)
×
468

469
    def __ne__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
470
        "Operator !=."
471
        return bitsCmp__val(self, other, ne)
1✔
472

473
    def __rne__(self, other: int) -> "Bits3val":
1✔
474
        "Operator !=."
475
        return bitsCmp__val(self._dtype.from_py(other), self, ne)
×
476

477
    def __lt__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
478
        "Operator <."
479
        return bitsCmp__val(self, other, lt)
1✔
480

481
    def __rlt__(self, other: int) -> "Bits3val":
1✔
482
        "Operator <."
483
        return bitsCmp__val(self._dtype.from_py(other), self, lt)
×
484

485
    def __gt__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
486
        "Operator >."
487
        return bitsCmp__val(self, other, gt)
1✔
488

489
    def __rgt__(self, other: int) -> "Bits3val":
1✔
490
        "Operator >."
491
        return bitsCmp__val(self._dtype.from_py(other), self, gt)
×
492

493
    def __ge__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
494
        "Operator >=."
495
        return bitsCmp__val(self, other, ge)
1✔
496

497
    def __rge__(self, other: int) -> "Bits3val":
1✔
498
        "Operator >=."
499
        return bitsCmp__val(self._dtype.from_py(other), self, ge)
×
500

501
    def __le__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
502
        "Operator <=."
503
        return bitsCmp__val(self, other, le)
1✔
504

505
    def __rle__(self, other: int) -> "Bits3val":
1✔
506
        "Operator <=."
507
        return bitsCmp__val(self._dtype.from_py(other), self, le)
×
508

509
    def __xor__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
510
        "Operator ^."
511
        return bitsBitOp__val(self, other, xor, vld_mask_for_xor)
1✔
512

513
    def __rxor__(self, other: int) -> "Bits3val":
1✔
514
        "Operator ^."
515
        return bitsBitOp__val(self._dtype.from_py(other), self, xor,
×
516
                              vld_mask_for_xor)
517

518
    def __and__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
519
        "Operator &."
520
        return bitsBitOp__val(self, other, and_, vld_mask_for_and)
1✔
521

522
    def __rand__(self, other: int) -> "Bits3val":
1✔
523
        "Operator &."
524
        return bitsBitOp__val(self._dtype.from_py(other), self, and_,
×
525
                              vld_mask_for_and)
526

527
    def __or__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
528
        "Operator |."
529
        return bitsBitOp__val(self, other, or_, vld_mask_for_or)
1✔
530

531
    def __ror__(self, other: int) -> "Bits3val":
1✔
532
        "Operator |."
533
        return bitsBitOp__val(self._dtype.from_py(other), self, or_,
×
534
                              vld_mask_for_or)
535

536
    def __sub__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
537
        "Operator -."
538
        return bitsArithOp__val(self, other, sub)
1✔
539

540
    def __rsub__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
541
        "Operator -."
542
        return bitsArithOp__val(self._dtype.from_py(other), self, sub)
×
543

544
    def __add__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
545
        "Operator +."
546
        return bitsArithOp__val(self, other, add)
1✔
547

548
    def __radd__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
549
        "Operator +."
550
        return bitsArithOp__val(self._dtype.from_py(other), self, add)
×
551

552
    def __rshift__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
553
        "Operator >> (arithmetic, shifts in MSB)."
554
        try:
1✔
555
            o = int(other)
1✔
556
        except ValidityError:
×
557
            o = None
×
558

559
        v = self.__copy__()
1✔
560
        if o is None:
1!
561
            v.vld_mask = 0
×
562
            v.val = 0
×
563
        elif o == 0:
1✔
564
            return v
1✔
565
        else:
566
            if o < 0:
1!
567
                raise ValueError("negative shift count")
×
568
            w = self._dtype.bit_length()
1✔
569
            if o < w:
1!
570
                v.vld_mask >>= o
1✔
571
                v.vld_mask |= bit_field(w - o, w)
1✔
572
                if v.val < 0:
1✔
573
                    assert self._dtype.signed
1✔
574
                    v.val = to_unsigned(v.val, w)
1✔
575
                v.val >>= o
1✔
576
            else:
577
                # completely shifted out
578
                v.val = 0
×
579
                v.vld_mask = mask(w)
×
580
        return v
1✔
581

582
    def __lshift__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
583
        "Operator <<. (shifts in 0)"
584
        try:
1✔
585
            o = int(other)
1✔
586
        except ValidityError:
×
587
            o = None
×
588

589
        v = self.__copy__()
1✔
590
        if o is None:
1!
591
            v.vld_mask = 0
×
592
            v.val = 0
×
593
        elif o == 0:
1✔
594
            return v
1✔
595
        else:
596
            if o < 0:
1!
597
                raise ValueError("negative shift count")
×
598
            t = self._dtype
1✔
599
            m = t.all_mask()
1✔
600
            v.vld_mask <<= o
1✔
601
            v.vld_mask |= mask(o)
1✔
602
            v.vld_mask &= m
1✔
603
            v.val <<= o
1✔
604
            v.val &= m
1✔
605
            if t.signed:
1✔
606
                v.val = to_signed(v.val, t.bit_length())
1✔
607
        return v
1✔
608

609
    def __floordiv__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
610
        "Operator //."
611
        other_is_int = isinstance(other, int)
1✔
612
        if other_is_int:
1✔
613
            v = self.val // other
1✔
614
            m = self._dtype.all_mask()
1✔
615
        else:
616
            if self._is_full_valid() and other._is_full_valid():
1✔
617
                v = self.val // other.val
1✔
618
                m = self._dtype.all_mask()
1✔
619
            else:
620
                v = 0
1✔
621
                m = 0
1✔
622
        return self._dtype._from_py(v, m)
1✔
623

624
    def __mul__(self, other: Union[int, "Bits3val"]) -> "Bits3val":
1✔
625
        "Operator *."
626
        # [TODO] resT should be wider
627
        resT = self._dtype
1✔
628
        other_is_int = isinstance(other, int)
1✔
629
        if other_is_int:
1!
630
            v = self.val * other
×
631
        elif isinstance(other, Bits3val):
1✔
632
            v = self.val * other.val
1✔
633
        else:
634
            raise TypeError(other)
1✔
635

636
        v &= resT.all_mask()
1✔
637
        if resT.signed:
1✔
638
            v = to_signed(v, resT.bit_length())
1✔
639

640
        if self._is_full_valid() and (other_is_int
1✔
641
                                      or other._is_full_valid()):
642
            vld_mask = resT._all_mask
1✔
643
        else:
644
            vld_mask = 0
1✔
645

646
        return resT._from_py(v, vld_mask)
1✔
647

648
    def _ternary(self, a, b):
1✔
649
        """
650
        Ternary operator (a if self else b).
651
        """
652
        try:
1✔
653
            if self:
1✔
654
                return a
1✔
655
            else:
656
                return b
1✔
657
        except ValidityError:
×
658
            pass
×
659
        res = copy(a)
×
660
        res.vld_mask = 0
×
661
        return res
×
662

663
    def __repr__(self):
664
        t = self._dtype
665
        if self.vld_mask != t.all_mask():
666
            m = ", mask {0:x}".format(self.vld_mask)
667
        else:
668
            m = ""
669
        typeDescrChar = 'b' if t.signed is None else 'i' if t.signed else 'u'
670
        return f"<{self.__class__.__name__:s} {typeDescrChar:s}{t.bit_length():d} {repr(self.val):s}{m:s}>"
671

672

673
def bitsBitOp__lshr(self: Bits3val, other: Union[Bits3val, int]):
1✔
674
    t = self._dtype
×
675
    width = t.bit_length()
×
676
    try:
×
677
        other = int(other)
×
678
    except ValidityError:
×
679
        return t.from_py(None)
×
680
    assert other >= 0
×
681

682
    if t.signed:
×
683
        v = to_unsigned(self.val, width)
×
684
        v >>= other
×
685
        v = to_signed(v, width)
×
686

687
    return t.from_py(v, self.vld_mask >> other)
×
688

689

690
def bitsBitOp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
691
                   evalFn, getVldFn) -> "Bits3val":
692
    """
693
    Apply bitwise operator
694
    """
695
    res_t = self._dtype
1✔
696
    if isinstance(other, int):
1✔
697
        other = res_t.from_py(other)
1✔
698
    w = res_t.bit_length()
1✔
699
    assert w == other._dtype.bit_length(), (res_t, other._dtype)
1✔
700
    vld = getVldFn(self, other)
1✔
701
    res = evalFn(self.val, other.val) & vld
1✔
702
    if res_t.signed:
1✔
703
        res = to_signed(res, w)
1✔
704

705
    return res_t._from_py(res, vld)
1✔
706

707

708
def bitsCmp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
709
                 evalFn) -> "Bits3val":
710
    """
711
    Apply comparative operator
712
    """
713
    t = self._dtype
1✔
714
    if isinstance(other, int):
1✔
715
        other = t.from_py(other)
1✔
716
        ot = other._dtype
1✔
717
        w = t.bit_length()
1✔
718
    else:
719
        ot = other._dtype
1✔
720
        w = t.bit_length()
1✔
721
        if bool(t.signed) != bool(ot.signed) or w != ot.bit_length():
1✔
722
            raise TypeError("Value compare supports only same width and sign type", t, ot)
1✔
723

724
    vld = self.vld_mask & other.vld_mask
1✔
725
    _vld = int(vld == t._all_mask)
1✔
726
    res = evalFn(self.val, other.val) & _vld
1✔
727

728
    return self._BOOL._from_py(int(res), int(_vld))
1✔
729

730

731
def bitsArithOp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
732
                     evalFn) -> "Bits3val":
733
    """
734
    Apply arithmetic operator
735
    """
736
    if isinstance(other, int):
1!
737
        other = self._dtype.from_py(other)
1✔
738
    v = self.__copy__()
1✔
739
    self_vld = self._is_full_valid()
1✔
740
    other_vld = other._is_full_valid()
1✔
741

742
    v.val = evalFn(self.val, other.val)
1✔
743

744
    w = v._dtype.bit_length()
1✔
745
    if self._dtype.signed:
1✔
746
        _v = v.val
1✔
747
        _max = mask(w - 1)
1✔
748
        _min = -_max - 1
1✔
749
        if _v > _max:
1✔
750
            _v = _min + (_v - _max - 1)
1✔
751
        elif _v < _min:
1✔
752
            _v = _max - (_v - _min + 1)
1✔
753

754
        v.val = _v
1✔
755
    else:
756
        v.val &= mask(w)
1✔
757

758
    if self_vld and other_vld:
1!
759
        v.vld_mask = mask(w)
1✔
760
    else:
761
        v.vld_mask = 0
×
762

763
    return v
1✔
764

STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc