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

Nic30 / pyMathBitPrecise / 4e5ee2a0-0184-47d1-8b78-cadbbbb82e54

10 Jun 2025 12:17PM UTC coverage: 66.947% (-6.4%) from 73.307%
4e5ee2a0-0184-47d1-8b78-cadbbbb82e54

push

circleci

Nic30
build: fix indents

215 of 368 branches covered (58.42%)

Branch coverage included in aggregate %.

820 of 1178 relevant lines covered (69.61%)

0.7 hits per line

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

74.43
/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
×
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✔
81
        t = self.__class__(self._bit_length, signed=self.signed,
1✔
82
                           name=self.name,
83
                           force_vector=self.force_vector,
84
                           strict_sign=self.strict_sign,
85
                           strict_width=self.strict_width)
86
        return t
1✔
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 bit_length(self) -> int:
1✔
95
        """
96
        :return: number of bits required for representation
97
            of value of this type
98
        """
99
        return self._bit_length
1✔
100

101
    def __eq__(self, other) -> bool:
1✔
102
        return (self is other
×
103
                or (isinstance(other, Bits3t)
104
                    and self._bit_length == other._bit_length
105
                    and self.name == other.name
106
                    and self.force_vector == other.force_vector
107
                    and self.strict_sign == other.strict_sign
108
                    and self.strict_width == other.strict_width
109
                    and self.signed == other.signed
110
                    )
111
                )
112

113
    def _normalize_val_and_mask(self, val: Optional[int], vld_mask: Optional[int]) -> tuple[int, int]:
1✔
114
        if val is None:
1✔
115
            vld = 0
1✔
116
            val = 0
1✔
117
            assert vld_mask is None or vld_mask == 0
1✔
118
        else:
119
            all_mask = self.all_mask()
1✔
120
            w = self._bit_length
1✔
121
            if isinstance(val, int):
1✔
122
                pass
1✔
123
            elif isinstance(val, bytes):
1!
124
                val = int.from_bytes(
×
125
                    val, byteorder="little", signed=bool(self.signed))
126
            elif isinstance(val, str):
1✔
127
                if not (val.startswith("0") and len(val) > 2):
1!
128
                    raise ValueError(val)
×
129

130
                base = INT_BASES[val[1]]
1✔
131
                try:
1✔
132
                    _val = int(val[2:], base)
1✔
133
                except ValueError:
1✔
134
                    _val = None
1✔
135

136
                if _val is None:
1!
137
                    assert vld_mask is None
1✔
138
                    val = val.lower()
1✔
139
                    if base == 10 and "x" in val:
1✔
140
                        raise NotImplementedError()
141
                    v = 0
1✔
142
                    m = 0
1✔
143
                    bits_per_char = ceil(log2(base))
1✔
144
                    char_mask = mask(bits_per_char)
1✔
145
                    for digit in val[2:]:
1✔
146
                        v <<= bits_per_char
1✔
147
                        m <<= bits_per_char
1✔
148
                        if digit == "x":
1✔
149
                            pass
1✔
150
                        else:
151
                            m |= char_mask
1✔
152
                            v |= int(digit, base)
1✔
153
                    val = v
1✔
154
                    vld_mask = m
1✔
155
                else:
156
                    val = _val
×
157
            else:
158
                try:
1✔
159
                    val = int(val)
1✔
160
                except TypeError as e:
1✔
161
                    if isinstance(val, Enum):
1!
162
                        val = int(val.value)
×
163
                    else:
164
                        raise e
1✔
165

166
            if vld_mask is None:
1✔
167
                vld = all_mask
1✔
168
            else:
169
                if vld_mask > all_mask or vld_mask < 0:
1!
170
                    raise ValueError("Mask in incorrect format", vld_mask, w, all_mask)
×
171
                vld = vld_mask
1✔
172

173
            if val < 0:
1✔
174
                if not self.signed:
1✔
175
                    raise ValueError("Negative value for unsigned int")
1✔
176
                _val = to_signed(val & all_mask, w)
1✔
177
                if _val != val:
1✔
178
                    raise ValueError("Too large value", val, _val)
1✔
179
                val = to_unsigned(_val, w)
1✔
180
            else:
181
                if self.signed:
1✔
182
                    msb = 1 << (w - 1)
1✔
183
                    if msb & val:
1✔
184
                        if val > 0:
1!
185
                            raise ValueError(
1✔
186
                                "Value too large to fit in this type", val)
187

188
                if val & all_mask != val:
1✔
189
                    raise ValueError(
1✔
190
                        "Not enough bits to represent value",
191
                        val, "on", w, "bit" if w == 1 else "bits", val & all_mask)
192
                val = val & vld
1✔
193
        return val, vld
1✔
194

195
    def _from_py(self, val: int, vld_mask: int) -> "Bits3val":
1✔
196
        """
197
        from_py without normalization
198
        """
199
        return Bits3val(self, val, vld_mask)
1✔
200

201
    def from_py(self, val: Union[int, bytes, str, Enum],
1✔
202
                vld_mask: Optional[int]=None) -> "Bits3val":
203
        """
204
        Construct value from pythonic value
205
        :note: str value has to start with base specifier (0b, 0h)
206
            and is much slower than the value specified
207
            by 'val' and 'vld_mask'. Does support x.
208
        """
209
        val, vld_mask = self._normalize_val_and_mask(val, vld_mask)
1✔
210
        return Bits3val(self, val, vld_mask)
1✔
211

212
    def __getitem__(self, i):
1✔
213
        ":return: an item from this array"
214
        return Array3t(self, i)
1✔
215

216
    def __hash__(self):
1✔
217
        return hash((
×
218
            self._bit_length,
219
            self.signed,
220
            self._all_mask,
221
            self.name,
222
            self.force_vector,
223
            self.strict_sign,
224
            self.strict_width
225
        ))
226

227
    def __repr__(self):
228
        """
229
        :param indent: number of indentation
230
        :param withAddr: if is not None is used as a additional
231
            information about on which address this type is stored
232
            (used only by HStruct)
233
        :param expandStructs: expand HStructTypes (used by HStruct and HArray)
234
        """
235
        constr = []
236
        if self.name is not None:
237
            constr.append(f'"{self.name:s}"')
238
        c = self.bit_length()
239

240
        if self.signed:
241
            sign = "i"
242
        elif self.signed is False:
243
            sign = "u"
244
        else:
245
            sign = "b"
246

247
        constr.append(f"{sign:s}{c:d}")
248
        if self.force_vector:
249
            constr.append("force_vector")
250

251
        if not self.strict_sign:
252
            constr.append("strict_sign=False")
253
        if not self.strict_width:
254
            constr.append("strict_width=False")
255

256
        return "<%s %s>" % (self.__class__.__name__,
257
                             ", ".join(constr))
258

259

260
class Bits3val():
1✔
261
    """
262
    Class for value of `Bits3t` type
263

264
    :ivar ~._dtype: reference on type of this value
265
    :ivar ~.val: always unsigned representation int value
266
    :note: the reason why the unsigned is always used is that
267
        the signed variant would require cast to unsigned on every bitwise operation
268
    :ivar ~.vld_mask: always unsigned value of the mask, if bit in mask is '0'
269
            the corresponding bit in val is invalid
270
    """
271
    _BOOL = Bits3t(1)
1✔
272
    _SIGNED_FOR_SLICE_RESULT = False
1✔
273
    _SIGNED_FOR_CONCAT_RESULT = False
1✔
274

275
    def __init__(self, t: Bits3t, val: int, vld_mask: int):
1✔
276
        if not isinstance(t, Bits3t):
1!
277
            raise TypeError(t)
×
278
        if type(val) != int:
1!
279
            raise TypeError(val)
×
280
        if type(vld_mask) != int:
1!
281
            raise TypeError(vld_mask)
×
282
        self._dtype = t
1✔
283
        self.val = val
1✔
284
        self.vld_mask = vld_mask
1✔
285

286
    def __copy__(self) -> Self:
1✔
287
        return self.__class__(self._dtype, self.val, self.vld_mask)
1✔
288

289
    def to_py(self) -> int:
1✔
290
        return int(self)
×
291

292
    def _is_full_valid(self) -> bool:
1✔
293
        """
294
        :return: True if all bits in value are valid
295
        """
296
        return self.vld_mask == self._dtype.all_mask()
1✔
297

298
    def __int__(self) -> int:
1✔
299
        "int(self)"
300
        if not self._is_full_valid():
1✔
301
            raise ValidityError(self)
1✔
302
        if self._dtype.signed:
1✔
303
            return to_signed(self.val, self._dtype.bit_length())
1✔
304
        else:
305
            return self.val
1✔
306

307
    def __bool__(self) -> bool:
1✔
308
        "bool(self)"
309
        return bool(self.__int__())
1✔
310

311
    def _auto_cast(self, dtype):
1✔
312
        """
313
        Cast value to a compatible type
314
        """
315
        return dtype.from_py(self.val, self.vld_mask)
×
316

317
    def _cast_sign(self, signed: Optional[bool]) -> Self:
1✔
318
        """
319
        Cast signed-unsigned value
320
        """
321
        t = self._dtype
1✔
322
        if t.signed == signed:
1!
323
            return self
×
324
        selfSign = t.signed
1✔
325
        v = self.__copy__()
1✔
326
        m = t._all_mask
1✔
327
        _v = v.val
1✔
328

329
        if selfSign and not signed:
1✔
330
            if _v < 0:
1!
331
                v.val = m + _v + 1
×
332

333
        v._dtype = v._dtype.__copy__()
1✔
334
        v._dtype = self._dtype.__copy__()
1✔
335
        v._dtype.signed = signed
1✔
336
        return v
1✔
337

338
    def _concat(self, other: "Bits3val") -> Self:
1✔
339
        """
340
        Concatenate two bit vectors together (self will be at MSB side)
341
        Verilog: {self, other}, VHDL: self & other
342
        """
343
        if not isinstance(other, Bits3val):
1✔
344
            raise TypeError(other)
1✔
345
        w = self._dtype.bit_length()
1✔
346
        other_w = other._dtype.bit_length()
1✔
347
        resWidth = w + other_w
1✔
348
        resT = self._dtype.__class__(resWidth, signed=self._SIGNED_FOR_CONCAT_RESULT)
1✔
349
        other_val = other.val
1✔
350
        if other_val < 0:
1!
351
            other_val = to_unsigned(other_val, other_w)
×
352
        v = self.__copy__()
1✔
353
        if v.val < 0:
1!
354
            v.val = to_unsigned(v.val, w)
×
355
        v.val = (v.val << other_w) | other_val
1✔
356
        v.vld_mask = (v.vld_mask << other_w) | other.vld_mask
1✔
357
        v._dtype = resT
1✔
358
        return v
1✔
359

360
    def _ext(self, newWidth: Union[int, Self], signed: Union[bool, Literal[_NOT_SPECIFIED]]=_NOT_SPECIFIED) -> Self:
1✔
361
        """
362
        :note: preserves sign of type
363
        """
364
        if signed is _NOT_SPECIFIED:
×
365
            signed = self._dtype.signed
×
366
        if signed:
×
367
            return self._sext(newWidth)
×
368
        else:
369
            return self._zext(newWidth)
×
370

371
    def _sext(self, newWidth: Union[int, Self]) -> Self:
1✔
372
        """
373
        signed extension, pad with MSB bit on MSB side to newWidth result width
374
        :see: :meth:`Bits3val._ext`
375
        """
376
        t = self._dtype
1✔
377
        w = t.bit_length()
1✔
378
        if newWidth == w:
1✔
379
            return self
1✔
380
        assert newWidth > w, (newWidth, w)
1✔
381
        resTy = t._createMutated(newWidth)
1✔
382
        val = self.val
1✔
383
        newBitsMask = bit_field(w, newWidth)
1✔
384
        if get_bit(val, w - 1):
1✔
385
            val |= newBitsMask
1✔
386
        vldMask = self.vld_mask
1✔
387
        if get_bit(vldMask, w - 1):
1!
388
            vldMask |= newBitsMask
1✔
389

390
        return resTy._from_py(val, vldMask)
1✔
391
        # alfternatively:
392
        # sign_bit = 1 << (bits - 1)
393
        # return (value & (sign_bit - 1)) - (value & sign_bit)
394

395

396
    def _zext(self, newWidth: Union[int, Self]) -> Self:
1✔
397
        """
398
        zero extension, pad with 0 on msb side to newWidth result width
399
        :see: :meth:`Bits3val._ext`
400
        """
401

402
        t = self._dtype
1✔
403
        w = t.bit_length()
1✔
404
        if newWidth == w:
1✔
405
            return self
1✔
406
        assert newWidth > w, (newWidth, w)
1✔
407
        resTy = t._createMutated(newWidth)
1✔
408
        return resTy.from_py(self.val, vld_mask=self.vld_mask | bit_field(w, newWidth))
1✔
409

410
    def _trunc(self, newWidth: Union[int, Self]) -> Self:
1✔
411
        assert newWidth > 0, newWidth
1✔
412
        w = self._dtype.bit_length()
1✔
413
        assert newWidth <= w, newWidth
1✔
414
        resTy = self._dtype._createMutated(newWidth)
1✔
415
        resMask = mask(newWidth)
1✔
416
        return resTy._from_py(self.val & resMask, self.vld_mask & resMask)
1✔
417

418
    def _extOrTrunc(self, newWidth: int, signed: Union[bool, Literal[_NOT_SPECIFIED]]=_NOT_SPECIFIED) -> Self:
1✔
419
        w = self._dtype.bit_length()
×
420
        if w < newWidth:
×
421
            return self._ext(newWidth, signed)
×
422
        elif w > newWidth:
×
423
            return self._trunc(newWidth)
×
424
        else:
425
            return self
×
426

427
    def __getitem__(self, key: Union[int, slice, Self]) -> Self:
1✔
428
        "self[key]"
429
        if isinstance(key, slice):
1✔
430
            firstBitNo, size = normalize_slice(key, self._dtype.bit_length())
1✔
431
            val = get_bit_range(self.val, firstBitNo, size)
1✔
432
            vld = get_bit_range(self.vld_mask, firstBitNo, size)
1✔
433
        elif isinstance(key, (int, Bits3val)):
1✔
434
            size = 1
1✔
435
            try:
1✔
436
                _i = int(key)
1✔
437
            except ValidityError:
×
438
                _i = None
×
439

440
            if _i is None:
1!
441
                val = 0
×
442
                vld = 0
×
443
            else:
444
                if _i < 0 or _i >= self._dtype.bit_length():
1✔
445
                    raise IndexError("Index out of range", _i)
1✔
446

447
                val = get_bit(self.val, _i)
1✔
448
                vld = get_bit(self.vld_mask, _i)
1✔
449
        else:
450
            raise TypeError(key)
1✔
451

452
        new_t = self._dtype._createMutated(size, signed=self._SIGNED_FOR_SLICE_RESULT)
1✔
453
        return new_t._from_py(val, vld)
1✔
454

455
    def __setitem__(self, index: Union[slice, int, Self],
1✔
456
                    value: Union[int, Self]):
457
        "An item assignment operator self[index] = value."
458
        if isinstance(index, slice):
1✔
459
            firstBitNo, size = normalize_slice(index, self._dtype.bit_length())
1✔
460
            if isinstance(value, Bits3val):
1!
461
                v = value.val
×
462
                m = value.vld_mask
×
463
            else:
464
                v = value
1✔
465
                m = mask(size)
1✔
466

467
            self.val = set_bit_range(self.val, firstBitNo, size, v)
1✔
468
            self.vld_mask = set_bit_range(
1✔
469
                self.vld_mask, firstBitNo, size, m)
470
        else:
471
            if index is None:
1✔
472
                raise TypeError(index)
1✔
473
            try:
1✔
474
                _i = int(index)
1✔
475
            except ValidityError:
×
476
                _i = None
×
477

478
            if _i is None:
1!
479
                self.val = 0
×
480
                self.vld_mask = 0
×
481
            else:
482
                if value is None:
1✔
483
                    v = 0
1✔
484
                    m = 0
1✔
485
                elif isinstance(value, Bits3val):
1!
486
                    v = value.val
×
487
                    m = value.vld_mask
×
488
                else:
489
                    v = value
1✔
490
                    m = 0b1
1✔
491
                try:
1✔
492
                    index = int(index)
1✔
493
                except ValidityError:
×
494
                    index = None
×
495
                if index is None:
1!
496
                    self.val = 0
×
497
                    self.vld_mask = 0
×
498
                else:
499
                    self.val = bit_set_to(self.val, index, v)
1✔
500
                    self.vld_mask = bit_set_to(self.vld_mask, index, m)
1✔
501

502
    def __invert__(self) -> Self:
1✔
503
        "Operator ~x."
504
        v = self.__copy__()
1✔
505
        v.val = ~v.val
1✔
506
        w = v._dtype.bit_length()
1✔
507
        v.val &= mask(w)
1✔
508
        if v.val < 0:
1!
509
            v.val = to_unsigned(v.val, w)
×
510

511
        return v
1✔
512

513
    def __neg__(self) -> Self:
1✔
514
        "Operator -x."
515
        v = self.__copy__()
1✔
516
        width = self._dtype.bit_length()
1✔
517
        _v = -to_signed(v.val, width)
1✔
518
        v.val = to_unsigned(_v, width)
1✔
519
        return v
1✔
520

521
    def __hash__(self) -> int:
1✔
522
        return hash((self._dtype, self.val, self.vld_mask))
×
523

524
    def _is(self, other) -> bool:
1✔
525
        """check if other is object with same values"""
526
        return isinstance(other, Bits3val)\
×
527
            and self._dtype == other._dtype\
528
            and self.val == other.val\
529
            and self.vld_mask == other.vld_mask
530

531
    def _eq(self, other: Union[int, Self]) -> Self:
1✔
532
        """
533
        Operator self._eq(other) as self == other
534
        == is not overridden in order to prevent tricky behavior if hashing partially valid values
535
        """
536
        return bitsCmp__val(self, other, eq)
1✔
537

538
    def __req__(self, other: int) -> Self:
1✔
539
        "Operator ==."
540
        return bitsCmp__val(self._dtype.from_py(other), self, eq)
×
541

542
    def __ne__(self, other: Union[int, Self]) -> Self:
1✔
543
        "Operator !=."
544
        return bitsCmp__val(self, other, ne)
1✔
545

546
    def __rne__(self, other: int) -> Self:
1✔
547
        "Operator !=."
548
        return bitsCmp__val(self._dtype.from_py(other), self, ne)
×
549

550
    def __lt__(self, other: Union[int, Self]) -> Self:
1✔
551
        "Operator <."
552
        return bitsCmp__val(self, other, lt)
1✔
553

554
    def __rlt__(self, other: int) -> Self:
1✔
555
        "Operator <."
556
        return bitsCmp__val(self._dtype.from_py(other), self, lt)
×
557

558
    def __gt__(self, other: Union[int, Self]) -> Self:
1✔
559
        "Operator >."
560
        return bitsCmp__val(self, other, gt)
1✔
561

562
    def __rgt__(self, other: int) -> Self:
1✔
563
        "Operator >."
564
        return bitsCmp__val(self._dtype.from_py(other), self, gt)
×
565

566
    def __ge__(self, other: Union[int, Self]) -> Self:
1✔
567
        "Operator >=."
568
        return bitsCmp__val(self, other, ge)
1✔
569

570
    def __rge__(self, other: int) -> Self:
1✔
571
        "Operator >=."
572
        return bitsCmp__val(self._dtype.from_py(other), self, ge)
×
573

574
    def __le__(self, other: Union[int, Self]) -> Self:
1✔
575
        "Operator <=."
576
        return bitsCmp__val(self, other, le)
1✔
577

578
    def __rle__(self, other: int) -> Self:
1✔
579
        "Operator <=."
580
        return bitsCmp__val(self._dtype.from_py(other), self, le)
×
581

582
    def __xor__(self, other: Union[int, Self]) -> Self:
1✔
583
        "Operator ^."
584
        return bitsBitOp__val(self, other, xor, vld_mask_for_xor)
1✔
585

586
    def __rxor__(self, other: int) -> Self:
1✔
587
        "Operator ^."
588
        return bitsBitOp__val(self._dtype.from_py(other), self, xor,
×
589
                              vld_mask_for_xor)
590

591
    def __and__(self, other: Union[int, Self]) -> Self:
1✔
592
        "Operator &."
593
        return bitsBitOp__val(self, other, and_, vld_mask_for_and)
1✔
594

595
    def __rand__(self, other: int) -> Self:
1✔
596
        "Operator &."
597
        return bitsBitOp__val(self._dtype.from_py(other), self, and_,
×
598
                              vld_mask_for_and)
599

600
    def __or__(self, other: Union[int, Self]) -> Self:
1✔
601
        "Operator |."
602
        return bitsBitOp__val(self, other, or_, vld_mask_for_or)
1✔
603

604
    def __ror__(self, other: int) -> Self:
1✔
605
        "Operator |."
606
        return bitsBitOp__val(self._dtype.from_py(other), self, or_,
×
607
                              vld_mask_for_or)
608

609
    def __sub__(self, other: Union[int, Self]) -> Self:
1✔
610
        "Operator -."
611
        return bitsArithOp__val(self, other, sub)
1✔
612

613
    def __rsub__(self, other: Union[int, Self]) -> Self:
1✔
614
        "Operator -."
615
        return bitsArithOp__val(self._dtype.from_py(other), self, sub)
×
616

617
    def __add__(self, other: Union[int, Self]) -> Self:
1✔
618
        "Operator +."
619
        return bitsArithOp__val(self, other, add)
1✔
620

621
    def __radd__(self, other: Union[int, Self]) -> Self:
1✔
622
        "Operator +."
623
        return bitsArithOp__val(self._dtype.from_py(other), self, add)
×
624

625
    def __rshift__(self, other: Union[int, Self]) -> Self:
1✔
626
        "Operator >>."
627
        if self._dtype.signed:
1✔
628
            return bitsBitOp__ashr(self, other)
1✔
629
        else:
630
            return bitsBitOp__lshr(self, other)
1✔
631

632
    def __lshift__(self, other: Union[int, Self]) -> Self:
1✔
633
        "Operator <<. (shifts in 0)"
634
        try:
1✔
635
            o = int(other)
1✔
636
        except ValidityError:
×
637
            o = None
×
638

639
        v = self.__copy__()
1✔
640
        if o is None:
1!
641
            v.vld_mask = 0
×
642
            v.val = 0
×
643
        elif o == 0:
1✔
644
            return v
1✔
645
        else:
646
            if o < 0:
1!
647
                raise ValueError("negative shift count")
×
648
            t = self._dtype
1✔
649
            m = t.all_mask()
1✔
650
            v.vld_mask <<= o
1✔
651
            v.vld_mask |= mask(o)
1✔
652
            v.vld_mask &= m
1✔
653
            v.val <<= o
1✔
654
            v.val &= m
1✔
655
            assert v.val >= 0, v.val
1✔
656
        return v
1✔
657

658
    def __floordiv__(self, other: Union[int, Self]) -> Self:
1✔
659
        "Operator //."
660
        other_is_int = isinstance(other, int)
1✔
661
        t = self._dtype
1✔
662
        if other_is_int:
1✔
663
            v0 = self.val
1✔
664
            if t.signed:
1✔
665
                w = t.bit_length()
1✔
666
                v0 = to_signed(v0, w)
1✔
667
            v = v0 // other
1✔
668
            m = self._dtype.all_mask()
1✔
669
        else:
670
            if self._is_full_valid() and other._is_full_valid():
1✔
671
                v0 = self.val
1✔
672
                v1 = other.val
1✔
673
                if t.signed:
1✔
674
                    w = t.bit_length()
1✔
675
                    v0 = to_signed(v0, w)
1✔
676
                    v1 = to_signed(v1, w)
1✔
677
                v = v0 // v1
1✔
678
                m = self._dtype.all_mask()
1✔
679
            else:
680
                v = 0
1✔
681
                m = 0
1✔
682
        return self._dtype._from_py(v, m)
1✔
683

684
    def __mul__(self, other: Union[int, Self]) -> Self:
1✔
685
        "Operator *."
686
        resT = self._dtype
1✔
687
        other_is_int = isinstance(other, int)
1✔
688
        if other_is_int:
1!
689
            v0 = self.val
×
690
            if resT.signed:
×
691
                w = resT.bit_length()
×
692
                v0 = to_signed(v0, w)
×
693

694
            v = v0 * other
×
695
        elif isinstance(other, Bits3val):
1✔
696
            v0 = self.val
1✔
697
            v1 = other.val
1✔
698
            if resT.signed:
1✔
699
                w = resT.bit_length()
1✔
700
                v0 = to_signed(v0, w)
1✔
701
                v1 = to_signed(v1, w)
1✔
702

703
            v = v0 * v1
1✔
704
        else:
705
            raise TypeError(other)
1✔
706

707
        v &= resT.all_mask()
1✔
708
        if resT.signed:
1✔
709
            v = to_signed(v, resT.bit_length())
1✔
710

711
        if self._is_full_valid() and (other_is_int
1✔
712
                                      or other._is_full_valid()):
713
            vld_mask = resT._all_mask
1✔
714
        else:
715
            vld_mask = 0
1✔
716

717
        return resT._from_py(v, vld_mask)
1✔
718

719
    def __mod__(self, other: Union[int, Self]) -> Self:
1✔
720
        "Operator %."
721
        resT = self._dtype
×
722
        other_is_int = isinstance(other, int)
×
723
        if other_is_int:
×
724
            v0 = self.val
×
725
            if resT.signed:
×
726
                w = resT.bit_length()
×
727
                v0 = to_signed(v0, w)
×
728

729
            v = v0 % other
×
730
        elif isinstance(other, Bits3val):
×
731
            v0 = self.val
×
732
            v1 = other.val
×
733
            if resT.signed:
×
734
                w = resT.bit_length()
×
735
                v0 = to_signed(v0, w)
×
736
                v1 = to_signed(v1, w)
×
737

738
            v = v0 % v1
×
739
        else:
740
            raise TypeError(other)
×
741

742
        v &= resT.all_mask()
×
743
        if resT.signed:
×
744
            v = to_signed(v, resT.bit_length())
×
745

746
        if self._is_full_valid() and (other_is_int
×
747
                                      or other._is_full_valid()):
748
            vld_mask = resT._all_mask
×
749
        else:
750
            vld_mask = 0
×
751

752
        return resT._from_py(v, vld_mask)
×
753

754
    def _ternary(self, a, b):
1✔
755
        """
756
        Ternary operator (a if self else b).
757
        """
758
        try:
1✔
759
            if self:
1✔
760
                return a
1✔
761
            else:
762
                return b
1✔
763
        except ValidityError:
×
764
            pass
×
765
        res = copy(a)
×
766
        res.vld_mask = 0
×
767
        return res
×
768

769
    def __repr__(self):
770
        t = self._dtype
771
        if self.vld_mask != t.all_mask():
772
            m = ", mask {0:x}".format(self.vld_mask)
773
        else:
774
            m = ""
775
        typeDescrChar = 'b' if t.signed is None else 'i' if t.signed else 'u'
776
        if t.bit_length() == 1 and t.force_vector:
777
            vecSpec = "vec"
778
        else:
779
            vecSpec = ""
780
        return (f"<{self.__class__.__name__:s} {typeDescrChar:s}{t.bit_length():d}{vecSpec:s}"
781
                f" {to_signed(self.val, t.bit_length()) if t.signed else self.val:d}{m:s}>")
782

783

784
def bitsBitOp__ror(self: Bits3val, shAmount: Union[Bits3val, int]):
1✔
785
    """
786
    rotate right by specified amount
787
    """
788
    t = self._dtype
×
789
    width = t.bit_length()
×
790
    try:
×
791
        shAmount = int(shAmount)
×
792
    except ValidityError:
×
793
        return t.from_py(None)
×
794
    assert shAmount >= 0
×
795

796
    v = rotate_right(self.val, width, shAmount)
×
797
    if t.signed:
×
798
        v = to_signed(v, width)
×
799
    return t.from_py(v, rotate_right(self.vld_mask, width, shAmount))
×
800

801

802
def bitsBitOp__rol(self: Bits3val, shAmount: Union[Bits3val, int]):
1✔
803
    """
804
    rotate left by specified amount
805
    """
806
    t = self._dtype
×
807
    width = t.bit_length()
×
808
    try:
×
809
        shAmount = int(shAmount)
×
810
    except ValidityError:
×
811
        return t.from_py(None)
×
812
    assert shAmount >= 0
×
813
    v = rotate_left(self.val, width, shAmount)
×
814
    if t.signed:
×
815
        v = to_signed(v, width)
×
816
    return t.from_py(v, rotate_left(self.vld_mask, width, shAmount))
×
817

818

819
def bitsBitOp__lshr(self: Bits3val, shAmount: Union[Bits3val, int]) -> Bits3val:
1✔
820
    """
821
    logical shift right (shifts in 0)
822
    """
823
    t = self._dtype
1✔
824
    width = t.bit_length()
1✔
825
    try:
1✔
826
        sh = int(shAmount)
1✔
827
    except ValidityError:
×
828
        return t.from_py(None)
×
829
    assert sh >= 0, sh
1✔
830

831
    if sh >= width:
1!
832
        # all bits are shifted out
833
        return t.from_py(0, mask(width))
×
834

835
    v = self.val >> sh
1✔
836
    if t.signed:
1✔
837
        v = to_signed(v, width)
1✔
838
    newBitsMask = bit_field(width - sh, width)
1✔
839
    return t.from_py(v, (self.vld_mask >> sh) | newBitsMask)
1✔
840

841

842
def bitsBitOp__ashr(self: Bits3val, shAmount: Union[Bits3val, int]) -> Bits3val:
1✔
843
    """
844
    arithmetic shift right (shifts in MSB)
845
    """
846
    try:
1✔
847
        sh = int(shAmount)
1✔
848
    except ValidityError:
×
849
        sh = None
×
850

851
    v = self.__copy__()
1✔
852
    if sh is None:
1!
853
        v.vld_mask = 0
×
854
        v.val = 0
×
855
    elif sh == 0:
1✔
856
        pass
1✔
857
    else:
858
        if shAmount < 0:
1!
859
            raise ValueError("negative shift count")
×
860
        w = self._dtype.bit_length()
1✔
861
        if sh < w:
1!
862
            msb = v.val >> (w - 1)
1✔
863
            newBitsMask = bit_field(w - sh, w)
1✔
864
            v.vld_mask >>= sh
1✔
865
            v.vld_mask |= newBitsMask  # set newly shifted-in bits to defined
1✔
866
            v.val >>= sh
1✔
867
            if msb:
1✔
868
                v.val |= newBitsMask
1✔
869
        else:
870
            # completely shifted out
871
            v.val = 0
×
872
            v.vld_mask = mask(w)
×
873
    return v
1✔
874

875

876
def bitsBitOp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
877
                   evalFn, getVldFn) -> "Bits3val":
878
    """
879
    Apply bitwise operator
880
    """
881
    res_t = self._dtype
1✔
882
    if isinstance(other, int):
1✔
883
        other = res_t.from_py(other)
1✔
884
    w = res_t.bit_length()
1✔
885
    assert w == other._dtype.bit_length(), (res_t, other._dtype)
1✔
886
    vld = getVldFn(self, other)
1✔
887
    res = evalFn(self.val, other.val) & vld
1✔
888
    assert res >= 0, res
1✔
889

890
    return res_t._from_py(res, vld)
1✔
891

892

893
def bitsCmp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
894
                 evalFn: Callable[[int, int], bool]) -> "Bits3val":
895
    """
896
    Apply comparative operator
897
    """
898
    t = self._dtype
1✔
899
    w = t.bit_length()
1✔
900
    if isinstance(other, int):
1✔
901
        other = t.from_py(other)
1✔
902
        ot = other._dtype
1✔
903
    else:
904
        ot = other._dtype
1✔
905
        if bool(t.signed) != bool(ot.signed) or w != ot.bit_length():
1✔
906
            raise TypeError("Value compare supports only same width and sign type", t, ot)
1✔
907

908
    v0 = self.val
1✔
909
    v1 = other.val
1✔
910
    if t.signed:
1✔
911
        v0 = to_signed(v0, w)
1✔
912
        v1 = to_signed(v1, w)
1✔
913

914
    vld = self.vld_mask & other.vld_mask
1✔
915
    _vld = int(vld == t._all_mask)
1✔
916
    res = evalFn(v0, v1) & _vld
1✔
917

918
    return self._BOOL._from_py(int(res), int(_vld))
1✔
919

920

921
def bitsArithOp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
922
                     evalFn: Callable[[int, int], int]) -> "Bits3val":
923
    """
924
    Apply arithmetic operator
925
    """
926
    if isinstance(other, int):
1!
927
        other = self._dtype.from_py(other)
1✔
928
    v = self.__copy__()
1✔
929
    self_vld = self._is_full_valid()
1✔
930
    other_vld = other._is_full_valid()
1✔
931
    v0 = self.val
1✔
932
    v1 = other.val
1✔
933
    w = v._dtype.bit_length()
1✔
934
    t = self._dtype
1✔
935
    if t.signed:
1✔
936
        v0 = to_signed(v0, w)
1✔
937
        v1 = to_signed(v1, w)
1✔
938

939
    _v = evalFn(v0, v1)
1✔
940

941
    if t.signed:
1✔
942
        _v = to_unsigned(_v, w)
1✔
943
    else:
944
        _v &= mask(w)
1✔
945

946
    v.val = _v
1✔
947
    if self_vld and other_vld:
1!
948
        v.vld_mask = mask(w)
1✔
949
    else:
950
        v.vld_mask = 0
×
951

952
    return v
1✔
953

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