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

Nic30 / pyMathBitPrecise / eab8b13e-e3a5-4f16-a6d9-8128246a03d7

08 Aug 2025 11:32PM UTC coverage: 66.371% (-0.8%) from 67.159%
eab8b13e-e3a5-4f16-a6d9-8128246a03d7

push

circleci

Nic30
feat(Bits3t): get_min_value, get_max_value

217 of 376 branches covered (57.71%)

Branch coverage included in aggregate %.

3 of 13 new or added lines in 1 file covered. (23.08%)

24 existing lines in 1 file now uncovered.

831 of 1203 relevant lines covered (69.08%)

0.69 hits per line

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

73.49
/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 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✔
NEW
110
        m = self._all_mask
×
NEW
111
        if self.signed:
×
NEW
112
            intMin = -(m // 2) - 1
×
113
        else:
NEW
114
            intMin = 0
×
NEW
115
        return intMin
×
116

117
    def get_max_value(self):
1✔
NEW
118
        m = self._all_mask
×
NEW
119
        if self.signed:
×
NEW
120
            intMax = m // 2
×
121
        else:
NEW
122
            intMax = m
×
NEW
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]) -> Self:
1✔
349
        """
350
        Cast signed-unsigned value
351
        """
352
        t = self._dtype
1✔
353
        if t.signed == signed:
1!
354
            return self
×
355
        selfSign = t.signed
1✔
356
        v = self.__copy__()
1✔
357
        m = t._all_mask
1✔
358
        _v = v.val
1✔
359

360
        if selfSign and not signed:
1✔
361
            if _v < 0:
1!
362
                v.val = m + _v + 1
×
363

364
        v._dtype = v._dtype.__copy__()
1✔
365
        v._dtype = self._dtype.__copy__()
1✔
366
        v._dtype.signed = signed
1✔
367
        return v
1✔
368

369
    def _concat(self, other: "Bits3val") -> Self:
1✔
370
        """
371
        Concatenate two bit vectors together (self will be at MSB side)
372
        Verilog: {self, other}, VHDL: self & other
373
        """
374
        if not isinstance(other, Bits3val):
1✔
375
            raise TypeError(other)
1✔
376
        w = self._dtype.bit_length()
1✔
377
        other_w = other._dtype.bit_length()
1✔
378
        resWidth = w + other_w
1✔
379
        resT = self._dtype.__class__(resWidth, signed=self._SIGNED_FOR_CONCAT_RESULT)
1✔
380
        other_val = other.val
1✔
381
        if other_val < 0:
1!
382
            other_val = to_unsigned(other_val, other_w)
×
383
        v = self.__copy__()
1✔
384
        if v.val < 0:
1!
385
            v.val = to_unsigned(v.val, w)
×
386
        v.val = (v.val << other_w) | other_val
1✔
387
        v.vld_mask = (v.vld_mask << other_w) | other.vld_mask
1✔
388
        v._dtype = resT
1✔
389
        return v
1✔
390

391
    def _ext(self, newWidth: Union[int, Self], signed: Union[bool, Literal[_NOT_SPECIFIED]]=_NOT_SPECIFIED) -> Self:
1✔
392
        """
393
        :note: preserves sign of type
394
        """
395
        if signed is _NOT_SPECIFIED:
×
396
            signed = self._dtype.signed
×
397
        if signed:
×
398
            return self._sext(newWidth)
×
399
        else:
400
            return self._zext(newWidth)
×
401

402
    def _sext(self, newWidth: Union[int, Self]) -> Self:
1✔
403
        """
404
        signed extension, pad with MSB bit on MSB side to newWidth result width
405
        :see: :meth:`Bits3val._ext`
406
        """
407
        t = self._dtype
1✔
408
        w = t.bit_length()
1✔
409
        if newWidth == w:
1✔
410
            return self
1✔
411
        assert newWidth > w, (newWidth, w)
1✔
412
        resTy = t._createMutated(newWidth)
1✔
413
        val = self.val
1✔
414
        newBitsMask = bit_field(w, newWidth)
1✔
415
        if get_bit(val, w - 1):
1✔
416
            val |= newBitsMask
1✔
417
        vldMask = self.vld_mask
1✔
418
        if get_bit(vldMask, w - 1):
1!
419
            vldMask |= newBitsMask
1✔
420

421
        return resTy._from_py(val, vldMask)
1✔
422
        # alfternatively:
423
        # sign_bit = 1 << (bits - 1)
424
        # return (value & (sign_bit - 1)) - (value & sign_bit)
425

426
    def _zext(self, newWidth: Union[int, Self]) -> Self:
1✔
427
        """
428
        zero extension, pad with 0 on msb side to newWidth result width
429
        :see: :meth:`Bits3val._ext`
430
        """
431

432
        t = self._dtype
1✔
433
        w = t.bit_length()
1✔
434
        if newWidth == w:
1✔
435
            return self
1✔
436
        assert newWidth > w, (newWidth, w)
1✔
437
        resTy = t._createMutated(newWidth)
1✔
438
        return resTy.from_py(self.val, vld_mask=self.vld_mask | bit_field(w, newWidth))
1✔
439

440
    def _trunc(self, newWidth: Union[int, Self]) -> Self:
1✔
441
        assert newWidth > 0, newWidth
1✔
442
        w = self._dtype.bit_length()
1✔
443
        assert newWidth <= w, newWidth
1✔
444
        resTy = self._dtype._createMutated(newWidth)
1✔
445
        resMask = mask(newWidth)
1✔
446
        return resTy._from_py(self.val & resMask, self.vld_mask & resMask)
1✔
447

448
    def _extOrTrunc(self, newWidth: int, signed: Union[bool, Literal[_NOT_SPECIFIED]]=_NOT_SPECIFIED) -> Self:
1✔
449
        w = self._dtype.bit_length()
×
450
        if w < newWidth:
×
451
            return self._ext(newWidth, signed)
×
452
        elif w > newWidth:
×
453
            return self._trunc(newWidth)
×
454
        else:
455
            return self
×
456

457
    def __getitem__(self, key: Union[int, slice, Self]) -> Self:
1✔
458
        "self[key]"
459
        if isinstance(key, slice):
1✔
460
            firstBitNo, size = normalize_slice(key, self._dtype.bit_length())
1✔
461
            val = get_bit_range(self.val, firstBitNo, size)
1✔
462
            vld = get_bit_range(self.vld_mask, firstBitNo, size)
1✔
463
        elif isinstance(key, (int, Bits3val)):
1✔
464
            size = 1
1✔
465
            try:
1✔
466
                _i = int(key)
1✔
467
            except ValidityError:
×
468
                _i = None
×
469

470
            if _i is None:
1!
471
                val = 0
×
472
                vld = 0
×
473
            else:
474
                if _i < 0 or _i >= self._dtype.bit_length():
1✔
475
                    raise IndexError("Index out of range", _i)
1✔
476

477
                val = get_bit(self.val, _i)
1✔
478
                vld = get_bit(self.vld_mask, _i)
1✔
479
        else:
480
            raise TypeError(key)
1✔
481

482
        new_t = self._dtype._createMutated(size, signed=self._SIGNED_FOR_SLICE_RESULT)
1✔
483
        return new_t._from_py(val, vld)
1✔
484

485
    def __setitem__(self, index: Union[slice, int, Self],
1✔
486
                    value: Union[int, Self]):
487
        "An item assignment operator self[index] = value."
488
        if isinstance(index, slice):
1✔
489
            firstBitNo, size = normalize_slice(index, self._dtype.bit_length())
1✔
490
            if isinstance(value, Bits3val):
1!
491
                v = value.val
×
492
                m = value.vld_mask
×
493
            else:
494
                v = value
1✔
495
                m = mask(size)
1✔
496

497
            self.val = set_bit_range(self.val, firstBitNo, size, v)
1✔
498
            self.vld_mask = set_bit_range(
1✔
499
                self.vld_mask, firstBitNo, size, m)
500
        else:
501
            if index is None:
1✔
502
                raise TypeError(index)
1✔
503
            try:
1✔
504
                _i = int(index)
1✔
505
            except ValidityError:
×
506
                _i = None
×
507

508
            if _i is None:
1!
509
                self.val = 0
×
510
                self.vld_mask = 0
×
511
            else:
512
                if value is None:
1✔
513
                    v = 0
1✔
514
                    m = 0
1✔
515
                elif isinstance(value, Bits3val):
1!
516
                    v = value.val
×
517
                    m = value.vld_mask
×
518
                else:
519
                    v = value
1✔
520
                    m = 0b1
1✔
521
                try:
1✔
522
                    index = int(index)
1✔
523
                except ValidityError:
×
524
                    index = None
×
525
                if index is None:
1!
526
                    self.val = 0
×
527
                    self.vld_mask = 0
×
528
                else:
529
                    self.val = bit_set_to(self.val, index, v)
1✔
530
                    self.vld_mask = bit_set_to(self.vld_mask, index, m)
1✔
531

532
    def __invert__(self) -> Self:
1✔
533
        "Operator ~x."
534
        v = self.__copy__()
1✔
535
        v.val = ~v.val
1✔
536
        w = v._dtype.bit_length()
1✔
537
        v.val &= mask(w)
1✔
538
        if v.val < 0:
1!
539
            v.val = to_unsigned(v.val, w)
×
540

541
        return v
1✔
542

543
    def __neg__(self) -> Self:
1✔
544
        "Operator -x."
545
        v = self.__copy__()
1✔
546
        width = self._dtype.bit_length()
1✔
547
        _v = -to_signed(v.val, width)
1✔
548
        v.val = to_unsigned(_v, width)
1✔
549
        return v
1✔
550

551
    def __hash__(self) -> int:
1✔
552
        return hash((self._dtype, self.val, self.vld_mask))
×
553

554
    def _is(self, other) -> bool:
1✔
555
        """check if other is object with same values"""
556
        return isinstance(other, Bits3val)\
×
557
            and self._dtype == other._dtype\
558
            and self.val == other.val\
559
            and self.vld_mask == other.vld_mask
560

561
    def _eq(self, other: Union[int, Self]) -> Self:
1✔
562
        """
563
        Operator self._eq(other) as self == other
564
        == is not overridden in order to prevent tricky behavior if hashing partially valid values
565
        """
566
        return bitsCmp__val(self, other, eq)
1✔
567

568
    def __req__(self, other: int) -> Self:
1✔
569
        "Operator ==."
570
        return bitsCmp__val(self._dtype.from_py(other), self, eq)
×
571

572
    def __ne__(self, other: Union[int, Self]) -> Self:
1✔
573
        "Operator !=."
574
        return bitsCmp__val(self, other, ne)
1✔
575

576
    def __rne__(self, other: int) -> Self:
1✔
577
        "Operator !=."
578
        return bitsCmp__val(self._dtype.from_py(other), self, ne)
×
579

580
    def __lt__(self, other: Union[int, Self]) -> Self:
1✔
581
        "Operator <."
582
        return bitsCmp__val(self, other, lt)
1✔
583

584
    def __rlt__(self, other: int) -> Self:
1✔
585
        "Operator <."
586
        return bitsCmp__val(self._dtype.from_py(other), self, lt)
×
587

588
    def __gt__(self, other: Union[int, Self]) -> Self:
1✔
589
        "Operator >."
590
        return bitsCmp__val(self, other, gt)
1✔
591

592
    def __rgt__(self, other: int) -> Self:
1✔
593
        "Operator >."
594
        return bitsCmp__val(self._dtype.from_py(other), self, gt)
×
595

596
    def __ge__(self, other: Union[int, Self]) -> Self:
1✔
597
        "Operator >=."
598
        return bitsCmp__val(self, other, ge)
1✔
599

600
    def __rge__(self, other: int) -> Self:
1✔
601
        "Operator >=."
602
        return bitsCmp__val(self._dtype.from_py(other), self, ge)
×
603

604
    def __le__(self, other: Union[int, Self]) -> Self:
1✔
605
        "Operator <=."
606
        return bitsCmp__val(self, other, le)
1✔
607

608
    def __rle__(self, other: int) -> Self:
1✔
609
        "Operator <=."
610
        return bitsCmp__val(self._dtype.from_py(other), self, le)
×
611

612
    def __xor__(self, other: Union[int, Self]) -> Self:
1✔
613
        "Operator ^."
614
        return bitsBitOp__val(self, other, xor, vld_mask_for_xor)
1✔
615

616
    def __rxor__(self, other: int) -> Self:
1✔
617
        "Operator ^."
618
        return bitsBitOp__val(self._dtype.from_py(other), self, xor,
×
619
                              vld_mask_for_xor)
620

621
    def __and__(self, other: Union[int, Self]) -> Self:
1✔
622
        "Operator &."
623
        return bitsBitOp__val(self, other, and_, vld_mask_for_and)
1✔
624

625
    def __rand__(self, other: int) -> Self:
1✔
626
        "Operator &."
627
        return bitsBitOp__val(self._dtype.from_py(other), self, and_,
×
628
                              vld_mask_for_and)
629

630
    def __or__(self, other: Union[int, Self]) -> Self:
1✔
631
        "Operator |."
632
        return bitsBitOp__val(self, other, or_, vld_mask_for_or)
1✔
633

634
    def __ror__(self, other: int) -> Self:
1✔
635
        "Operator |."
636
        return bitsBitOp__val(self._dtype.from_py(other), self, or_,
×
637
                              vld_mask_for_or)
638

639
    def __sub__(self, other: Union[int, Self]) -> Self:
1✔
640
        "Operator -."
641
        return bitsArithOp__val(self, other, sub)
1✔
642

643
    def __rsub__(self, other: Union[int, Self]) -> Self:
1✔
644
        "Operator -."
645
        return bitsArithOp__val(self._dtype.from_py(other), self, sub)
×
646

647
    def __add__(self, other: Union[int, Self]) -> Self:
1✔
648
        "Operator +."
649
        return bitsArithOp__val(self, other, add)
1✔
650

651
    def __radd__(self, other: Union[int, Self]) -> Self:
1✔
652
        "Operator +."
653
        return bitsArithOp__val(self._dtype.from_py(other), self, add)
×
654

655
    def __rshift__(self, other: Union[int, Self]) -> Self:
1✔
656
        "Operator >>."
657
        if self._dtype.signed:
1✔
658
            return bitsBitOp__ashr(self, other)
1✔
659
        else:
660
            return bitsBitOp__lshr(self, other)
1✔
661

662
    def __lshift__(self, other: Union[int, Self]) -> Self:
1✔
663
        "Operator <<. (shifts in 0)"
664
        try:
1✔
665
            o = int(other)
1✔
666
        except ValidityError:
×
667
            o = None
×
668

669
        v = self.__copy__()
1✔
670
        if o is None:
1!
671
            v.vld_mask = 0
×
672
            v.val = 0
×
673
        elif o == 0:
1✔
674
            return v
1✔
675
        else:
676
            if o < 0:
1!
677
                raise ValueError("negative shift count")
×
678
            t = self._dtype
1✔
679
            m = t.all_mask()
1✔
680
            v.vld_mask <<= o
1✔
681
            v.vld_mask |= mask(o)
1✔
682
            v.vld_mask &= m
1✔
683
            v.val <<= o
1✔
684
            v.val &= m
1✔
685
            assert v.val >= 0, v.val
1✔
686
        return v
1✔
687

688
    def __floordiv__(self, other: Union[int, Self]) -> Self:
1✔
689
        "Operator //."
690
        other_is_int = isinstance(other, int)
1✔
691
        t = self._dtype
1✔
692
        if other_is_int:
1✔
693
            v0 = self.val
1✔
694
            if t.signed:
1✔
695
                w = t.bit_length()
1✔
696
                v0 = to_signed(v0, w)
1✔
697
            v = v0 // other
1✔
698
            m = self._dtype.all_mask()
1✔
699
        else:
700
            if self._is_full_valid() and other._is_full_valid():
1✔
701
                v0 = self.val
1✔
702
                v1 = other.val
1✔
703
                if t.signed:
1✔
704
                    w = t.bit_length()
1✔
705
                    v0 = to_signed(v0, w)
1✔
706
                    v1 = to_signed(v1, w)
1✔
707
                v = v0 // v1
1✔
708
                m = self._dtype.all_mask()
1✔
709
            else:
710
                v = 0
1✔
711
                m = 0
1✔
712
        return self._dtype._from_py(v, m)
1✔
713

714
    def __mul__(self, other: Union[int, Self]) -> Self:
1✔
715
        "Operator *."
716
        resT = self._dtype
1✔
717
        other_is_int = isinstance(other, int)
1✔
718
        if other_is_int:
1!
719
            v0 = self.val
×
720
            if resT.signed:
×
721
                w = resT.bit_length()
×
722
                v0 = to_signed(v0, w)
×
723

724
            v = v0 * other
×
725
        elif isinstance(other, Bits3val):
1✔
726
            v0 = self.val
1✔
727
            v1 = other.val
1✔
728
            if resT.signed:
1✔
729
                w = resT.bit_length()
1✔
730
                v0 = to_signed(v0, w)
1✔
731
                v1 = to_signed(v1, w)
1✔
732

733
            v = v0 * v1
1✔
734
        else:
735
            raise TypeError(other)
1✔
736

737
        v &= resT.all_mask()
1✔
738
        if resT.signed:
1✔
739
            v = to_signed(v, resT.bit_length())
1✔
740

741
        if self._is_full_valid() and (other_is_int
1✔
742
                                      or other._is_full_valid()):
743
            vld_mask = resT._all_mask
1✔
744
        else:
745
            vld_mask = 0
1✔
746

747
        return resT._from_py(v, vld_mask)
1✔
748

749
    def __mod__(self, other: Union[int, Self]) -> Self:
1✔
750
        "Operator %."
751
        resT = self._dtype
×
752
        other_is_int = isinstance(other, int)
×
753
        if other_is_int:
×
754
            v0 = self.val
×
755
            if resT.signed:
×
756
                w = resT.bit_length()
×
757
                v0 = to_signed(v0, w)
×
758

759
            v = v0 % other
×
760
        elif isinstance(other, Bits3val):
×
761
            v0 = self.val
×
762
            v1 = other.val
×
763
            if resT.signed:
×
764
                w = resT.bit_length()
×
765
                v0 = to_signed(v0, w)
×
766
                v1 = to_signed(v1, w)
×
767

768
            v = v0 % v1
×
769
        else:
770
            raise TypeError(other)
×
771

772
        v &= resT.all_mask()
×
773
        if resT.signed:
×
774
            v = to_signed(v, resT.bit_length())
×
775

776
        if self._is_full_valid() and (other_is_int
×
777
                                      or other._is_full_valid()):
778
            vld_mask = resT._all_mask
×
779
        else:
780
            vld_mask = 0
×
781

782
        return resT._from_py(v, vld_mask)
×
783

784
    def _ternary(self, a, b):
1✔
785
        """
786
        Ternary operator (a if self else b).
787
        """
788
        try:
1✔
789
            if self:
1✔
790
                return a
1✔
791
            else:
792
                return b
1✔
793
        except ValidityError:
×
794
            pass
×
795
        res = copy(a)
×
796
        res.vld_mask = 0
×
797
        return res
×
798

799
    def __repr__(self):
800
        t = self._dtype
801
        if self.vld_mask != t.all_mask():
802
            m = ", mask {0:x}".format(self.vld_mask)
803
        else:
804
            m = ""
805
        typeDescrChar = 'b' if t.signed is None else 'i' if t.signed else 'u'
806
        if t.bit_length() == 1 and t.force_vector:
807
            vecSpec = "vec"
808
        else:
809
            vecSpec = ""
810
        return (f"<{self.__class__.__name__:s} {typeDescrChar:s}{t.bit_length():d}{vecSpec:s}"
811
                f" {to_signed(self.val, t.bit_length()) if t.signed else self.val:d}{m:s}>")
812

813

814
def bitsBitOp__ror(self: Bits3val, shAmount: Union[Bits3val, int]):
1✔
815
    """
816
    rotate right by specified amount
817
    """
818
    t = self._dtype
×
819
    width = t.bit_length()
×
820
    try:
×
821
        shAmount = int(shAmount)
×
822
    except ValidityError:
×
823
        return t.from_py(None)
×
824
    assert shAmount >= 0
×
825

826
    v = rotate_right(self.val, width, shAmount)
×
827
    if t.signed:
×
828
        v = to_signed(v, width)
×
829
    return t.from_py(v, rotate_right(self.vld_mask, width, shAmount))
×
830

831

832
def bitsBitOp__rol(self: Bits3val, shAmount: Union[Bits3val, int]):
1✔
833
    """
834
    rotate left by specified amount
835
    """
836
    t = self._dtype
×
837
    width = t.bit_length()
×
838
    try:
×
839
        shAmount = int(shAmount)
×
840
    except ValidityError:
×
841
        return t.from_py(None)
×
842
    assert shAmount >= 0
×
843
    v = rotate_left(self.val, width, shAmount)
×
844
    if t.signed:
×
845
        v = to_signed(v, width)
×
846
    return t.from_py(v, rotate_left(self.vld_mask, width, shAmount))
×
847

848

849
def bitsBitOp__lshr(self: Bits3val, shAmount: Union[Bits3val, int]) -> Bits3val:
1✔
850
    """
851
    logical shift right (shifts in 0)
852
    """
853
    t = self._dtype
1✔
854
    width = t.bit_length()
1✔
855
    try:
1✔
856
        sh = int(shAmount)
1✔
857
    except ValidityError:
×
858
        return t.from_py(None)
×
859
    assert sh >= 0, sh
1✔
860

861
    if sh >= width:
1!
862
        # all bits are shifted out
863
        return t.from_py(0, mask(width))
×
864

865
    v = self.val >> sh
1✔
866
    if t.signed:
1✔
867
        v = to_signed(v, width)
1✔
868
    newBitsMask = bit_field(width - sh, width)
1✔
869
    return t.from_py(v, (self.vld_mask >> sh) | newBitsMask)
1✔
870

871

872
def bitsBitOp__ashr(self: Bits3val, shAmount: Union[Bits3val, int]) -> Bits3val:
1✔
873
    """
874
    arithmetic shift right (shifts in MSB)
875
    """
876
    try:
1✔
877
        sh = int(shAmount)
1✔
878
    except ValidityError:
×
879
        sh = None
×
880

881
    v = self.__copy__()
1✔
882
    if sh is None:
1!
883
        v.vld_mask = 0
×
884
        v.val = 0
×
885
    elif sh == 0:
1✔
886
        pass
1✔
887
    else:
888
        if shAmount < 0:
1!
889
            raise ValueError("negative shift count")
×
890
        w = self._dtype.bit_length()
1✔
891
        if sh < w:
1!
892
            msb = v.val >> (w - 1)
1✔
893
            newBitsMask = bit_field(w - sh, w)
1✔
894
            v.vld_mask >>= sh
1✔
895
            v.vld_mask |= newBitsMask  # set newly shifted-in bits to defined
1✔
896
            v.val >>= sh
1✔
897
            if msb:
1✔
898
                v.val |= newBitsMask
1✔
899
        else:
900
            # completely shifted out
901
            v.val = 0
×
902
            v.vld_mask = mask(w)
×
903
    return v
1✔
904

905

906
def bitsBitOp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
907
                   evalFn, getVldFn) -> "Bits3val":
908
    """
909
    Apply bitwise operator
910
    """
911
    res_t = self._dtype
1✔
912
    if isinstance(other, int):
1✔
913
        other = res_t.from_py(other)
1✔
914
    w = res_t.bit_length()
1✔
915
    assert w == other._dtype.bit_length(), (res_t, other._dtype)
1✔
916
    vld = getVldFn(self, other)
1✔
917
    res = evalFn(self.val, other.val) & vld
1✔
918
    assert res >= 0, res
1✔
919

920
    return res_t._from_py(res, vld)
1✔
921

922

923
def bitsCmp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
924
                 evalFn: Callable[[int, int], bool]) -> "Bits3val":
925
    """
926
    Apply comparative operator
927
    """
928
    t = self._dtype
1✔
929
    w = t.bit_length()
1✔
930
    if isinstance(other, int):
1✔
931
        other = t.from_py(other)
1✔
932
        ot = other._dtype
1✔
933
    else:
934
        ot = other._dtype
1✔
935
        if bool(t.signed) != bool(ot.signed) or w != ot.bit_length():
1✔
936
            raise TypeError("Value compare supports only same width and sign type", t, ot)
1✔
937

938
    v0 = self.val
1✔
939
    v1 = other.val
1✔
940
    if t.signed:
1✔
941
        v0 = to_signed(v0, w)
1✔
942
        v1 = to_signed(v1, w)
1✔
943

944
    vld = self.vld_mask & other.vld_mask
1✔
945
    _vld = int(vld == t._all_mask)
1✔
946
    res = evalFn(v0, v1) & _vld
1✔
947

948
    return self._BOOL._from_py(int(res), int(_vld))
1✔
949

950

951
def bitsArithOp__val(self: Bits3val, other: Union[Bits3val, int],
1✔
952
                     evalFn: Callable[[int, int], int]) -> "Bits3val":
953
    """
954
    Apply arithmetic operator
955
    """
956
    if isinstance(other, int):
1!
957
        other = self._dtype.from_py(other)
1✔
958
    v = self.__copy__()
1✔
959
    self_vld = self._is_full_valid()
1✔
960
    other_vld = other._is_full_valid()
1✔
961
    v0 = self.val
1✔
962
    v1 = other.val
1✔
963
    w = v._dtype.bit_length()
1✔
964
    t = self._dtype
1✔
965
    if t.signed:
1✔
966
        v0 = to_signed(v0, w)
1✔
967
        v1 = to_signed(v1, w)
1✔
968

969
    _v = evalFn(v0, v1)
1✔
970

971
    if t.signed:
1✔
972
        _v = to_unsigned(_v, w)
1✔
973
    else:
974
        _v &= mask(w)
1✔
975

976
    v.val = _v
1✔
977
    if self_vld and other_vld:
1!
978
        v.vld_mask = mask(w)
1✔
979
    else:
980
        v.vld_mask = 0
×
981

982
    return v
1✔
983

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