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

Nic30 / pyMathBitPrecise / 5ccf2d88-775c-43a4-a218-d70432c8300b

10 Oct 2025 05:37PM UTC coverage: 66.688%. Remained the same
5ccf2d88-775c-43a4-a218-d70432c8300b

push

circleci

Nic30
style: typing

213 of 368 branches covered (57.88%)

Branch coverage included in aggregate %.

2 of 2 new or added lines in 1 file covered. (100.0%)

90 existing lines in 1 file now uncovered.

838 of 1208 relevant lines covered (69.37%)

0.69 hits per line

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

73.65
/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, Callable, Self, Literal
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, rotate_right, rotate_left
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 _NOT_SPECIFIED:
1✔
19

20
    def __init__(self):
1✔
21
        raise AssertionError("This class should be used as a constant")
22

23

24
class Bits3t():
1✔
25
    """
26
    Meta type for integer of specified size where
27
    each bit can be '1', '0' or 'X' for undefined value.
28

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

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

60
    def _createMutated(self,
1✔
61
            bit_length: int=_NOT_SPECIFIED,
62
            signed:Optional[bool]=_NOT_SPECIFIED, name: Optional[str]=_NOT_SPECIFIED,
63
            force_vector=_NOT_SPECIFIED,
64
            strict_sign=_NOT_SPECIFIED,
65
            strict_width=_NOT_SPECIFIED) -> Self:
66
        if bit_length is _NOT_SPECIFIED:
1✔
67
            bit_length = self._bit_length
1✔
68
        if signed is  _NOT_SPECIFIED:
1✔
69
            signed = self.signed
1✔
70
        if name  is _NOT_SPECIFIED:
1!
71
            name = self.name
1✔
72
        if force_vector is _NOT_SPECIFIED:
1!
73
            force_vector = self.force_vector
1✔
74
        if strict_sign is _NOT_SPECIFIED:
1!
75
            strict_sign = self.strict_sign
1✔
76
        if strict_width is _NOT_SPECIFIED:
1!
77
            strict_width = self.strict_width
1✔
78
        return self.__class__(bit_length, signed=signed, name=name, force_vector=force_vector, strict_sign=strict_sign, strict_width=strict_width)
1✔
79

80
    def __copy__(self) -> Self:
1✔
UNCOV
81
        t = self.__class__(self._bit_length, signed=self.signed,
×
82
                           name=self.name,
83
                           force_vector=self.force_vector,
84
                           strict_sign=self.strict_sign,
85
                           strict_width=self.strict_width)
UNCOV
86
        return t
×
87

88
    def all_mask(self) -> int:
1✔
89
        """
90
        :return: mask for bites of this type ( 0b111 for Bits(3) )
91
        """
92
        return self._all_mask
1✔
93

94
    def get_domain_range(self):
1✔
95
        """
96
        equvalent of (get_min_value(), get_max_value())
97
        :note: as an independent function from performace reasons
98
        """
99
        m = self._all_mask
1✔
100
        if self.signed:
1✔
101
            intMin = -(m // 2) - 1
1✔
102
            intMax = m // 2
1✔
103
        else:
104
            intMin = 0
1✔
105
            intMax = m
1✔
106

107
        return (intMin, intMax)
1✔
108

109
    def get_min_value(self):
1✔
110
        m = self._all_mask
×
111
        if self.signed:
×
112
            intMin = -(m // 2) - 1
×
113
        else:
114
            intMin = 0
×
115
        return intMin
×
116

117
    def get_max_value(self):
1✔
118
        m = self._all_mask
×
119
        if self.signed:
×
120
            intMax = m // 2
×
121
        else:
122
            intMax = m
×
123
        return intMax
×
124

125
    def bit_length(self) -> int:
1✔
126
        """
127
        :return: number of bits required for representation
128
            of value of this type
129
        """
130
        return self._bit_length
1✔
131

132
    def __eq__(self, other) -> bool:
1✔
133
        return (self is other
×
134
                or (isinstance(other, Bits3t)
135
                    and self._bit_length == other._bit_length
136
                    and self.name == other.name
137
                    and self.force_vector == other.force_vector
138
                    and self.strict_sign == other.strict_sign
139
                    and self.strict_width == other.strict_width
140
                    and self.signed == other.signed
141
                    )
142
                )
143

144
    def _normalize_val_and_mask(self, val: Optional[int], vld_mask: Optional[int]) -> tuple[int, int]:
1✔
145
        if val is None:
1✔
146
            vld = 0
1✔
147
            val = 0
1✔
148
            assert vld_mask is None or vld_mask == 0
1✔
149
        else:
150
            all_mask = self.all_mask()
1✔
151
            w = self._bit_length
1✔
152
            if isinstance(val, int):
1✔
153
                pass
1✔
154
            elif isinstance(val, bytes):
1!
155
                val = int.from_bytes(
×
156
                    val, byteorder="little", signed=bool(self.signed))
157
            elif isinstance(val, str):
1✔
158
                if not (val.startswith("0") and len(val) > 2):
1!
159
                    raise ValueError(val)
×
160

161
                base = INT_BASES[val[1]]
1✔
162
                try:
1✔
163
                    _val = int(val[2:], base)
1✔
164
                except ValueError:
1✔
165
                    _val = None
1✔
166

167
                if _val is None:
1!
168
                    assert vld_mask is None
1✔
169
                    val = val.lower()
1✔
170
                    if base == 10 and "x" in val:
1✔
171
                        raise NotImplementedError()
172
                    v = 0
1✔
173
                    m = 0
1✔
174
                    bits_per_char = ceil(log2(base))
1✔
175
                    char_mask = mask(bits_per_char)
1✔
176
                    for digit in val[2:]:
1✔
177
                        v <<= bits_per_char
1✔
178
                        m <<= bits_per_char
1✔
179
                        if digit == "x":
1✔
180
                            pass
1✔
181
                        else:
182
                            m |= char_mask
1✔
183
                            v |= int(digit, base)
1✔
184
                    val = v
1✔
185
                    vld_mask = m
1✔
186
                else:
187
                    val = _val
×
188
            else:
189
                try:
1✔
190
                    val = int(val)
1✔
191
                except TypeError as e:
1✔
192
                    if isinstance(val, Enum):
1!
193
                        val = int(val.value)
×
194
                    else:
195
                        raise e
1✔
196

197
            if vld_mask is None:
1✔
198
                vld = all_mask
1✔
199
            else:
200
                if vld_mask > all_mask or vld_mask < 0:
1!
201
                    raise ValueError("Mask in incorrect format", vld_mask, w, all_mask)
×
202
                vld = vld_mask
1✔
203

204
            if val < 0:
1✔
205
                if not self.signed:
1✔
206
                    raise ValueError("Negative value for unsigned int")
1✔
207
                _val = to_signed(val & all_mask, w)
1✔
208
                if _val != val:
1✔
209
                    raise ValueError("Too large value", val, _val)
1✔
210
                val = to_unsigned(_val, w)
1✔
211
            else:
212
                if self.signed:
1✔
213
                    msb = 1 << (w - 1)
1✔
214
                    if msb & val:
1✔
215
                        if val > 0:
1!
216
                            raise ValueError(
1✔
217
                                "Value too large to fit in this type", val)
218

219
                if val & all_mask != val:
1✔
220
                    raise ValueError(
1✔
221
                        "Not enough bits to represent value",
222
                        val, "on", w, "bit" if w == 1 else "bits", val & all_mask)
223
                val = val & vld
1✔
224
        return val, vld
1✔
225

226
    def _from_py(self, val: int, vld_mask: int) -> "Bits3val":
1✔
227
        """
228
        from_py without normalization
229
        """
230
        return Bits3val(self, val, vld_mask)
1✔
231

232
    def from_py(self, val: Union[int, bytes, str, Enum],
1✔
233
                vld_mask: Optional[int]=None) -> "Bits3val":
234
        """
235
        Construct value from pythonic value
236
        :note: str value has to start with base specifier (0b, 0h)
237
            and is much slower than the value specified
238
            by 'val' and 'vld_mask'. Does support x.
239
        """
240
        val, vld_mask = self._normalize_val_and_mask(val, vld_mask)
1✔
241
        return Bits3val(self, val, vld_mask)
1✔
242

243
    def __getitem__(self, i):
1✔
244
        ":return: an item from this array"
245
        return Array3t(self, i)
1✔
246

247
    def __hash__(self):
1✔
248
        return hash((
×
249
            self._bit_length,
250
            self.signed,
251
            self._all_mask,
252
            self.name,
253
            self.force_vector,
254
            self.strict_sign,
255
            self.strict_width
256
        ))
257

258
    def __repr__(self):
259
        """
260
        :param indent: number of indentation
261
        :param withAddr: if is not None is used as a additional
262
            information about on which address this type is stored
263
            (used only by HStruct)
264
        :param expandStructs: expand HStructTypes (used by HStruct and HArray)
265
        """
266
        constr = []
267
        if self.name is not None:
268
            constr.append(f'"{self.name:s}"')
269
        c = self.bit_length()
270

271
        if self.signed:
272
            sign = "i"
273
        elif self.signed is False:
274
            sign = "u"
275
        else:
276
            sign = "b"
277

278
        constr.append(f"{sign:s}{c:d}")
279
        if self.force_vector:
280
            constr.append("force_vector")
281

282
        if not self.strict_sign:
283
            constr.append("strict_sign=False")
284
        if not self.strict_width:
285
            constr.append("strict_width=False")
286

287
        return "<%s %s>" % (self.__class__.__name__,
288
                             ", ".join(constr))
289

290

291
class Bits3val():
1✔
292
    """
293
    Class for value of `Bits3t` type
294

295
    :ivar ~._dtype: reference on type of this value
296
    :ivar ~.val: always unsigned representation int value
297
    :note: the reason why the unsigned is always used is that
298
        the signed variant would require cast to unsigned on every bitwise operation
299
    :ivar ~.vld_mask: always unsigned value of the mask, if bit in mask is '0'
300
            the corresponding bit in val is invalid
301
    """
302
    _BOOL = Bits3t(1)
1✔
303
    _SIGNED_FOR_SLICE_RESULT = False
1✔
304
    _SIGNED_FOR_CONCAT_RESULT = False
1✔
305

306
    def __init__(self, t: Bits3t, val: int, vld_mask: int):
1✔
307
        if not isinstance(t, Bits3t):
1!
308
            raise TypeError(t)
×
309
        if type(val) != int:
1!
310
            raise TypeError(val)
×
311
        if type(vld_mask) != int:
1!
312
            raise TypeError(vld_mask)
×
313
        self._dtype = t
1✔
314
        self.val = val
1✔
315
        self.vld_mask = vld_mask
1✔
316

317
    def __copy__(self) -> Self:
1✔
318
        return self.__class__(self._dtype, self.val, self.vld_mask)
1✔
319

320
    def to_py(self) -> int:
1✔
321
        return int(self)
×
322

323
    def _is_full_valid(self) -> bool:
1✔
324
        """
325
        :return: True if all bits in value are valid
326
        """
327
        return self.vld_mask == self._dtype.all_mask()
1✔
328

329
    def __int__(self) -> int:
1✔
330
        "int(self)"
331
        if not self._is_full_valid():
1✔
332
            raise ValidityError(self)
1✔
333
        if self._dtype.signed:
1✔
334
            return to_signed(self.val, self._dtype.bit_length())
1✔
335
        else:
336
            return self.val
1✔
337

338
    def __bool__(self) -> bool:
1✔
339
        "bool(self)"
340
        return bool(self.__int__())
1✔
341

342
    def _auto_cast(self, dtype):
1✔
343
        """
344
        Cast value to a compatible type
345
        """
346
        return dtype.from_py(self.val, self.vld_mask)
×
347

348
    def _cast_sign(self, signed: Optional[bool], **typeMutateKwArgs) -> Self:
1✔
349
        """
350
        Cast signed-unsigned value
351
        """
352
        t = self._dtype
1✔
353
        if t.signed == signed:
1!
354
            return self
×
355
        v = self.__copy__()
1✔
356
        v._dtype = v._dtype._createMutated(signed=signed, **typeMutateKwArgs)
1✔
357
        return v
1✔
358

359
    def _concat(self, other: "Bits3val") -> Self:
1✔
360
        """
361
        Concatenate two bit vectors together (self will be at MSB side)
362
        Verilog: {self, other}, VHDL: self & other
363
        """
364
        if not isinstance(other, Bits3val):
1✔
365
            raise TypeError(other)
1✔
366
        w = self._dtype.bit_length()
1✔
367
        other_w = other._dtype.bit_length()
1✔
368
        resWidth = w + other_w
1✔
369
        resT = self._dtype.__class__(resWidth, signed=self._SIGNED_FOR_CONCAT_RESULT)
1✔
370
        other_val = other.val
1✔
371
        assert other_val >= 0, other_val
1✔
372
        v = self.__copy__()
1✔
373
        assert v.val >= 0, v
1✔
374
        v.val = (v.val << other_w) | other_val
1✔
375
        v.vld_mask = (v.vld_mask << other_w) | other.vld_mask
1✔
376
        v._dtype = resT
1✔
377
        return v
1✔
378

379
    def _ext(self, newWidth: Union[int, Self], signed: Union[bool, Literal[_NOT_SPECIFIED]]=_NOT_SPECIFIED) -> Self:
1✔
380
        """
381
        :note: preserves sign of type
382
        """
UNCOV
383
        if signed is _NOT_SPECIFIED:
×
UNCOV
384
            signed = self._dtype.signed
×
385
        if signed:
×
UNCOV
386
            return self._sext(newWidth)
×
387
        else:
UNCOV
388
            return self._zext(newWidth)
×
389

390
    def _sext(self, newWidth: Union[int, Self]) -> Self:
1✔
391
        """
392
        signed extension, pad with MSB bit on MSB side to newWidth result width
393
        :see: :meth:`Bits3val._ext`
394
        """
395
        t = self._dtype
1✔
396
        w = t.bit_length()
1✔
397
        if newWidth == w:
1✔
398
            return self
1✔
399
        assert newWidth > w, (newWidth, w)
1✔
400
        resTy = t._createMutated(newWidth)
1✔
401
        val = self.val
1✔
402
        newBitsMask = bit_field(w, newWidth)
1✔
403
        if get_bit(val, w - 1):
1✔
404
            val |= newBitsMask
1✔
405
        vldMask = self.vld_mask
1✔
406
        if get_bit(vldMask, w - 1):
1!
407
            vldMask |= newBitsMask
1✔
408

409
        return resTy._from_py(val, vldMask)
1✔
410
        # alfternatively:
411
        # sign_bit = 1 << (bits - 1)
412
        # return (value & (sign_bit - 1)) - (value & sign_bit)
413

414
    def _zext(self, newWidth: Union[int, Self]) -> Self:
1✔
415
        """
416
        zero extension, pad with 0 on msb side to newWidth result width
417
        :see: :meth:`Bits3val._ext`
418
        """
419

420
        t = self._dtype
1✔
421
        w = t.bit_length()
1✔
422
        if newWidth == w:
1✔
423
            return self
1✔
424
        assert newWidth > w, (newWidth, w)
1✔
425
        resTy = t._createMutated(newWidth)
1✔
426
        return resTy.from_py(self.val, vld_mask=self.vld_mask | bit_field(w, newWidth))
1✔
427

428
    def _trunc(self, newWidth: Union[int, Self]) -> Self:
1✔
429
        assert newWidth > 0, newWidth
1✔
430
        w = self._dtype.bit_length()
1✔
431
        assert newWidth <= w, newWidth
1✔
432
        resTy = self._dtype._createMutated(newWidth)
1✔
433
        resMask = mask(newWidth)
1✔
434
        return resTy._from_py(self.val & resMask, self.vld_mask & resMask)
1✔
435

436
    def _extOrTrunc(self, newWidth: int, signed: Union[bool, Literal[_NOT_SPECIFIED]]=_NOT_SPECIFIED) -> Self:
1✔
UNCOV
437
        w = self._dtype.bit_length()
×
UNCOV
438
        if w < newWidth:
×
UNCOV
439
            return self._ext(newWidth, signed)
×
UNCOV
440
        elif w > newWidth:
×
UNCOV
441
            return self._trunc(newWidth)
×
442
        else:
UNCOV
443
            return self
×
444

445
    def __getitem__(self, key: Union[int, slice, Self]) -> Self:
1✔
446
        "self[key]"
447
        if isinstance(key, slice):
1✔
448
            firstBitNo, size = normalize_slice(key, self._dtype.bit_length())
1✔
449
            val = get_bit_range(self.val, firstBitNo, size)
1✔
450
            vld = get_bit_range(self.vld_mask, firstBitNo, size)
1✔
451
        elif isinstance(key, (int, Bits3val)):
1✔
452
            size = 1
1✔
453
            try:
1✔
454
                _i = int(key)
1✔
455
            except ValidityError:
×
UNCOV
456
                _i = None
×
457

458
            if _i is None:
1!
UNCOV
459
                val = 0
×
UNCOV
460
                vld = 0
×
461
            else:
462
                if _i < 0 or _i >= self._dtype.bit_length():
1✔
463
                    raise IndexError("Index out of range", _i)
1✔
464

465
                val = get_bit(self.val, _i)
1✔
466
                vld = get_bit(self.vld_mask, _i)
1✔
467
        else:
468
            raise TypeError(key)
1✔
469

470
        new_t = self._dtype._createMutated(size, signed=self._SIGNED_FOR_SLICE_RESULT)
1✔
471
        return new_t._from_py(val, vld)
1✔
472

473
    def __setitem__(self, index: Union[slice, int, Self],
1✔
474
                    value: Union[int, Self]):
475
        "An item assignment operator self[index] = value."
476
        if isinstance(index, slice):
1✔
477
            firstBitNo, size = normalize_slice(index, self._dtype.bit_length())
1✔
478
            if isinstance(value, Bits3val):
1!
UNCOV
479
                v = value.val
×
UNCOV
480
                m = value.vld_mask
×
481
            else:
482
                v = value
1✔
483
                m = mask(size)
1✔
484

485
            self.val = set_bit_range(self.val, firstBitNo, size, v)
1✔
486
            self.vld_mask = set_bit_range(
1✔
487
                self.vld_mask, firstBitNo, size, m)
488
        else:
489
            if index is None:
1✔
490
                raise TypeError(index)
1✔
491
            try:
1✔
492
                _i = int(index)
1✔
UNCOV
493
            except ValidityError:
×
UNCOV
494
                _i = None
×
495

496
            if _i is None:
1!
UNCOV
497
                self.val = 0
×
UNCOV
498
                self.vld_mask = 0
×
499
            else:
500
                if value is None:
1✔
501
                    v = 0
1✔
502
                    m = 0
1✔
503
                elif isinstance(value, Bits3val):
1!
UNCOV
504
                    v = value.val
×
505
                    m = value.vld_mask
×
506
                else:
507
                    v = value
1✔
508
                    m = 0b1
1✔
509
                try:
1✔
510
                    index = int(index)
1✔
UNCOV
511
                except ValidityError:
×
UNCOV
512
                    index = None
×
513
                if index is None:
1!
UNCOV
514
                    self.val = 0
×
UNCOV
515
                    self.vld_mask = 0
×
516
                else:
517
                    self.val = bit_set_to(self.val, index, v)
1✔
518
                    self.vld_mask = bit_set_to(self.vld_mask, index, m)
1✔
519

520
    def __invert__(self) -> Self:
1✔
521
        "Operator ~x."
522
        v = self.__copy__()
1✔
523
        v.val = ~v.val
1✔
524
        w = v._dtype.bit_length()
1✔
525
        v.val &= mask(w)
1✔
526
        if v.val < 0:
1!
527
            v.val = to_unsigned(v.val, w)
×
528

529
        return v
1✔
530

531
    def __neg__(self) -> Self:
1✔
532
        "Operator -x."
533
        v = self.__copy__()
1✔
534
        width = self._dtype.bit_length()
1✔
535
        _v = -to_signed(v.val, width)
1✔
536
        v.val = to_unsigned(_v, width)
1✔
537
        return v
1✔
538

539
    def __hash__(self) -> int:
1✔
UNCOV
540
        return hash((self._dtype, self.val, self.vld_mask))
×
541

542
    def _is(self, other) -> bool:
1✔
543
        """check if other is object with same values"""
UNCOV
544
        return isinstance(other, Bits3val)\
×
545
            and self._dtype == other._dtype\
546
            and self.val == other.val\
547
            and self.vld_mask == other.vld_mask
548

549
    def _eq(self, other: Union[int, Self]) -> Self:
1✔
550
        """
551
        Operator self._eq(other) as self == other
552
        == is not overridden in order to prevent tricky behavior if hashing partially valid values
553
        """
554
        return bitsCmp__val(self, other, eq)
1✔
555

556
    def __req__(self, other: int) -> Self:
1✔
557
        "Operator ==."
UNCOV
558
        return bitsCmp__val(self._dtype.from_py(other), self, eq)
×
559

560
    def __ne__(self, other: Union[int, Self]) -> Self:
1✔
561
        "Operator !=."
562
        return bitsCmp__val(self, other, ne)
1✔
563

564
    def __rne__(self, other: int) -> Self:
1✔
565
        "Operator !=."
UNCOV
566
        return bitsCmp__val(self._dtype.from_py(other), self, ne)
×
567

568
    def __lt__(self, other: Union[int, Self]) -> Self:
1✔
569
        "Operator <."
570
        return bitsCmp__val(self, other, lt)
1✔
571

572
    def __rlt__(self, other: int) -> Self:
1✔
573
        "Operator <."
UNCOV
574
        return bitsCmp__val(self._dtype.from_py(other), self, lt)
×
575

576
    def __gt__(self, other: Union[int, Self]) -> Self:
1✔
577
        "Operator >."
578
        return bitsCmp__val(self, other, gt)
1✔
579

580
    def __rgt__(self, other: int) -> Self:
1✔
581
        "Operator >."
UNCOV
582
        return bitsCmp__val(self._dtype.from_py(other), self, gt)
×
583

584
    def __ge__(self, other: Union[int, Self]) -> Self:
1✔
585
        "Operator >=."
586
        return bitsCmp__val(self, other, ge)
1✔
587

588
    def __rge__(self, other: int) -> Self:
1✔
589
        "Operator >=."
UNCOV
590
        return bitsCmp__val(self._dtype.from_py(other), self, ge)
×
591

592
    def __le__(self, other: Union[int, Self]) -> Self:
1✔
593
        "Operator <=."
594
        return bitsCmp__val(self, other, le)
1✔
595

596
    def __rle__(self, other: int) -> Self:
1✔
597
        "Operator <=."
UNCOV
598
        return bitsCmp__val(self._dtype.from_py(other), self, le)
×
599

600
    def __xor__(self, other: Union[int, Self]) -> Self:
1✔
601
        "Operator ^."
602
        return bitsBitOp__val(self, other, xor, vld_mask_for_xor)
1✔
603

604
    def __rxor__(self, other: int) -> Self:
1✔
605
        "Operator ^."
UNCOV
606
        return bitsBitOp__val(self._dtype.from_py(other), self, xor,
×
607
                              vld_mask_for_xor)
608

609
    def __and__(self, other: Union[int, Self]) -> Self:
1✔
610
        "Operator &."
611
        return bitsBitOp__val(self, other, and_, vld_mask_for_and)
1✔
612

613
    def __rand__(self, other: int) -> Self:
1✔
614
        "Operator &."
UNCOV
615
        return bitsBitOp__val(self._dtype.from_py(other), self, and_,
×
616
                              vld_mask_for_and)
617

618
    def __or__(self, other: Union[int, Self]) -> Self:
1✔
619
        "Operator |."
620
        return bitsBitOp__val(self, other, or_, vld_mask_for_or)
1✔
621

622
    def __ror__(self, other: int) -> Self:
1✔
623
        "Operator |."
UNCOV
624
        return bitsBitOp__val(self._dtype.from_py(other), self, or_,
×
625
                              vld_mask_for_or)
626

627
    def __sub__(self, other: Union[int, Self]) -> Self:
1✔
628
        "Operator -."
629
        return bitsArithOp__val(self, other, sub)
1✔
630

631
    def __rsub__(self, other: Union[int, Self]) -> Self:
1✔
632
        "Operator -."
UNCOV
633
        return bitsArithOp__val(self._dtype.from_py(other), self, sub)
×
634

635
    def __add__(self, other: Union[int, Self]) -> Self:
1✔
636
        "Operator +."
637
        return bitsArithOp__val(self, other, add)
1✔
638

639
    def __radd__(self, other: Union[int, Self]) -> Self:
1✔
640
        "Operator +."
UNCOV
641
        return bitsArithOp__val(self._dtype.from_py(other), self, add)
×
642

643
    def __rshift__(self, other: Union[int, Self]) -> Self:
1✔
644
        "Operator >>."
645
        if self._dtype.signed:
1✔
646
            return bitsBitOp__ashr(self, other)
1✔
647
        else:
648
            return bitsBitOp__lshr(self, other)
1✔
649

650
    def __lshift__(self, other: Union[int, Self]) -> Self:
1✔
651
        "Operator <<. (shifts in 0)"
652
        try:
1✔
653
            o = int(other)
1✔
UNCOV
654
        except ValidityError:
×
UNCOV
655
            o = None
×
656

657
        v = self.__copy__()
1✔
658
        if o is None:
1!
UNCOV
659
            v.vld_mask = 0
×
UNCOV
660
            v.val = 0
×
661
        elif o == 0:
1✔
662
            return v
1✔
663
        else:
664
            if o < 0:
1!
UNCOV
665
                raise ValueError("negative shift count")
×
666
            t = self._dtype
1✔
667
            m = t.all_mask()
1✔
668
            v.vld_mask <<= o
1✔
669
            v.vld_mask |= mask(o)
1✔
670
            v.vld_mask &= m
1✔
671
            v.val <<= o
1✔
672
            v.val &= m
1✔
673
            assert v.val >= 0, v.val
1✔
674
        return v
1✔
675

676
    def __floordiv__(self, other: Union[int, Self]) -> Self:
1✔
677
        "Operator //."
678
        other_is_int = isinstance(other, int)
1✔
679
        t = self._dtype
1✔
680
        if other_is_int:
1✔
681
            v0 = self.val
1✔
682
            if t.signed:
1✔
683
                w = t.bit_length()
1✔
684
                v0 = to_signed(v0, w)
1✔
685
            v = v0 // other
1✔
686
            m = self._dtype.all_mask()
1✔
687
        else:
688
            if self._is_full_valid() and other._is_full_valid():
1✔
689
                v0 = self.val
1✔
690
                v1 = other.val
1✔
691
                if t.signed:
1✔
692
                    w = t.bit_length()
1✔
693
                    v0 = to_signed(v0, w)
1✔
694
                    v1 = to_signed(v1, w)
1✔
695
                v = v0 // v1
1✔
696
                m = self._dtype.all_mask()
1✔
697
            else:
698
                v = 0
1✔
699
                m = 0
1✔
700
        return self._dtype._from_py(v, m)
1✔
701

702
    def __mul__(self, other: Union[int, Self]) -> Self:
1✔
703
        "Operator *."
704
        resT = self._dtype
1✔
705
        other_is_int = isinstance(other, int)
1✔
706
        if other_is_int:
1!
UNCOV
707
            v0 = self.val
×
UNCOV
708
            if resT.signed:
×
UNCOV
709
                w = resT.bit_length()
×
UNCOV
710
                v0 = to_signed(v0, w)
×
711

UNCOV
712
            v = v0 * other
×
713
        elif isinstance(other, Bits3val):
1✔
714
            v0 = self.val
1✔
715
            v1 = other.val
1✔
716
            if resT.signed:
1✔
717
                w = resT.bit_length()
1✔
718
                v0 = to_signed(v0, w)
1✔
719
                v1 = to_signed(v1, w)
1✔
720

721
            v = v0 * v1
1✔
722
        else:
723
            raise TypeError(other)
1✔
724

725
        v &= resT.all_mask()
1✔
726
        if resT.signed:
1✔
727
            v = to_signed(v, resT.bit_length())
1✔
728

729
        if self._is_full_valid() and (other_is_int
1✔
730
                                      or other._is_full_valid()):
731
            vld_mask = resT._all_mask
1✔
732
        else:
733
            vld_mask = 0
1✔
734

735
        return resT._from_py(v, vld_mask)
1✔
736

737
    def __mod__(self, other: Union[int, Self]) -> Self:
1✔
738
        "Operator %."
UNCOV
739
        resT = self._dtype
×
UNCOV
740
        other_is_int = isinstance(other, int)
×
UNCOV
741
        if other_is_int:
×
UNCOV
742
            v0 = self.val
×
UNCOV
743
            if resT.signed:
×
UNCOV
744
                w = resT.bit_length()
×
UNCOV
745
                v0 = to_signed(v0, w)
×
746

UNCOV
747
            v = v0 % other
×
UNCOV
748
        elif isinstance(other, Bits3val):
×
UNCOV
749
            v0 = self.val
×
UNCOV
750
            v1 = other.val
×
751
            if resT.signed:
×
752
                w = resT.bit_length()
×
753
                v0 = to_signed(v0, w)
×
754
                v1 = to_signed(v1, w)
×
755

756
            v = v0 % v1
×
757
        else:
UNCOV
758
            raise TypeError(other)
×
759

760
        v &= resT.all_mask()
×
761
        if resT.signed:
×
762
            v = to_signed(v, resT.bit_length())
×
763

764
        if self._is_full_valid() and (other_is_int
×
765
                                      or other._is_full_valid()):
766
            vld_mask = resT._all_mask
×
767
        else:
768
            vld_mask = 0
×
769

770
        return resT._from_py(v, vld_mask)
×
771

772
    def _ternary(self, a, b):
1✔
773
        """
774
        Ternary operator (a if self else b).
775
        """
776
        try:
1✔
777
            if self:
1✔
778
                return a
1✔
779
            else:
780
                return b
1✔
UNCOV
781
        except ValidityError:
×
782
            pass
×
UNCOV
783
        res = copy(a)
×
UNCOV
784
        res.vld_mask = 0
×
UNCOV
785
        return res
×
786

787
    def __repr__(self):
788
        t = self._dtype
789
        if self.vld_mask != t.all_mask():
790
            m = ", mask {0:x}".format(self.vld_mask)
791
        else:
792
            m = ""
793
        typeDescrChar = 'b' if t.signed is None else 'i' if t.signed else 'u'
794
        if t.bit_length() == 1 and t.force_vector:
795
            vecSpec = "vec"
796
        else:
797
            vecSpec = ""
798
        return (f"<{self.__class__.__name__:s} {typeDescrChar:s}{t.bit_length():d}{vecSpec:s}"
799
                f" {to_signed(self.val, t.bit_length()) if t.signed else self.val:d}{m:s}>")
800

801

802
def bitsBitOp__ror(self: Bits3val, shAmount: Union[Bits3val, int]):
1✔
803
    """
804
    rotate right by specified amount
805
    """
UNCOV
806
    t = self._dtype
×
UNCOV
807
    width = t.bit_length()
×
UNCOV
808
    try:
×
UNCOV
809
        shAmount = int(shAmount)
×
UNCOV
810
    except ValidityError:
×
UNCOV
811
        return t.from_py(None)
×
UNCOV
812
    assert shAmount >= 0
×
813

UNCOV
814
    v = rotate_right(self.val, width, shAmount)
×
UNCOV
815
    if t.signed:
×
UNCOV
816
        v = to_signed(v, width)
×
UNCOV
817
    return t.from_py(v, rotate_right(self.vld_mask, width, shAmount))
×
818

819

820
def bitsBitOp__rol(self: Bits3val, shAmount: Union[Bits3val, int]):
1✔
821
    """
822
    rotate left by specified amount
823
    """
824
    t = self._dtype
×
UNCOV
825
    width = t.bit_length()
×
826
    try:
×
827
        shAmount = int(shAmount)
×
828
    except ValidityError:
×
829
        return t.from_py(None)
×
UNCOV
830
    assert shAmount >= 0
×
UNCOV
831
    v = rotate_left(self.val, width, shAmount)
×
UNCOV
832
    if t.signed:
×
UNCOV
833
        v = to_signed(v, width)
×
UNCOV
834
    return t.from_py(v, rotate_left(self.vld_mask, width, shAmount))
×
835

836

837
def bitsBitOp__lshr(self: Bits3val, shAmount: Union[Bits3val, int]) -> Bits3val:
1✔
838
    """
839
    logical shift right (shifts in 0)
840
    """
841
    t = self._dtype
1✔
842
    width = t.bit_length()
1✔
843
    try:
1✔
844
        sh = int(shAmount)
1✔
845
    except ValidityError:
×
846
        return t.from_py(None)
×
847
    assert sh >= 0, sh
1✔
848

849
    if sh >= width:
1!
850
        # all bits are shifted out
UNCOV
851
        return t.from_py(0, mask(width))
×
852

853
    v = self.val >> sh
1✔
854
    if t.signed:
1✔
855
        v = to_signed(v, width)
1✔
856
    newBitsMask = bit_field(width - sh, width)
1✔
857
    return t.from_py(v, (self.vld_mask >> sh) | newBitsMask)
1✔
858

859

860
def bitsBitOp__ashr(self: Bits3val, shAmount: Union[Bits3val, int]) -> Bits3val:
1✔
861
    """
862
    arithmetic shift right (shifts in MSB)
863
    """
864
    try:
1✔
865
        sh = int(shAmount)
1✔
UNCOV
866
    except ValidityError:
×
UNCOV
867
        sh = None
×
868

869
    v = self.__copy__()
1✔
870
    if sh is None:
1!
UNCOV
871
        v.vld_mask = 0
×
UNCOV
872
        v.val = 0
×
873
    elif sh == 0:
1✔
874
        pass
1✔
875
    else:
876
        if shAmount < 0:
1!
UNCOV
877
            raise ValueError("negative shift count")
×
878
        w = self._dtype.bit_length()
1✔
879
        if sh < w:
1!
880
            msb = v.val >> (w - 1)
1✔
881
            newBitsMask = bit_field(w - sh, w)
1✔
882
            v.vld_mask >>= sh
1✔
883
            v.vld_mask |= newBitsMask  # set newly shifted-in bits to defined
1✔
884
            v.val >>= sh
1✔
885
            if msb:
1✔
886
                v.val |= newBitsMask
1✔
887
        else:
888
            # completely shifted out
889
            v.val = 0
×
UNCOV
890
            v.vld_mask = mask(w)
×
891
    return v
1✔
892

893

894
def bitsBitOp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
895
                   evalFn, getVldFn) -> "Bits3val":
896
    """
897
    Apply bitwise operator
898
    """
899
    res_t = self._dtype
1✔
900
    if isinstance(other, int):
1✔
901
        other = res_t.from_py(other)
1✔
902
    w = res_t.bit_length()
1✔
903
    assert w == other._dtype.bit_length(), (res_t, other._dtype)
1✔
904
    vld = getVldFn(self, other)
1✔
905
    res = evalFn(self.val, other.val) & vld
1✔
906
    assert res >= 0, res
1✔
907

908
    return res_t._from_py(res, vld)
1✔
909

910

911
def bitsCmp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
912
                 evalFn: Callable[[int, int], bool]) -> "Bits3val":
913
    """
914
    Apply comparative operator
915
    """
916
    t = self._dtype
1✔
917
    w = t.bit_length()
1✔
918
    if isinstance(other, int):
1✔
919
        other = t.from_py(other)
1✔
920
        ot = other._dtype
1✔
921
    else:
922
        ot = other._dtype
1✔
923
        if bool(t.signed) != bool(ot.signed) or w != ot.bit_length():
1✔
924
            raise TypeError("Value compare supports only same width and sign type", t, ot)
1✔
925

926
    v0 = self.val
1✔
927
    v1 = other.val
1✔
928
    if t.signed:
1✔
929
        v0 = to_signed(v0, w)
1✔
930
        v1 = to_signed(v1, w)
1✔
931

932
    vld = self.vld_mask & other.vld_mask
1✔
933
    _vld = int(vld == t._all_mask)
1✔
934
    res = evalFn(v0, v1) & _vld
1✔
935

936
    return self._BOOL._from_py(int(res), int(_vld))
1✔
937

938

939
def bitsArithOp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
940
                     evalFn: Callable[[int, int], int]) -> "Bits3val":
941
    """
942
    Apply arithmetic operator
943
    """
944
    if isinstance(other, int):
1!
945
        other = self._dtype.from_py(other)
1✔
946
    v = self.__copy__()
1✔
947
    self_vld = self._is_full_valid()
1✔
948
    other_vld = other._is_full_valid()
1✔
949
    v0 = self.val
1✔
950
    v1 = other.val
1✔
951
    w = v._dtype.bit_length()
1✔
952
    t = self._dtype
1✔
953
    if t.signed:
1✔
954
        v0 = to_signed(v0, w)
1✔
955
        v1 = to_signed(v1, w)
1✔
956

957
    _v = evalFn(v0, v1)
1✔
958

959
    if t.signed:
1✔
960
        _v = to_unsigned(_v, w)
1✔
961
    else:
962
        _v &= mask(w)
1✔
963

964
    v.val = _v
1✔
965
    if self_vld and other_vld:
1!
966
        v.vld_mask = mask(w)
1✔
967
    else:
UNCOV
968
        v.vld_mask = 0
×
969

970
    return v
1✔
971

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