Coverage for /home/runner/work/zserio/zserio/compiler/extensions/python/runtime/src/zserio/bitfield.py: 100%
17 statements
« prev ^ index » next coverage.py v6.5.0, created at 2024-10-29 13:10 +0000
« prev ^ index » next coverage.py v6.5.0, created at 2024-10-29 13:10 +0000
1"""
2The module provides help methods for bit fields calculation.
3"""
5from zserio.exception import PythonRuntimeException
8def bitfield_lowerbound(length: int) -> int:
9 """
10 Gets the lower bound of a unsigned bitfield type with given length.
12 :param length: Length of the unsigned bitfield in bits.
13 :returns: The lowest value the unsigned bitfield can hold.
14 :raises PythonRuntimeException: If unsigned bitfield with wrong length has been specified.
15 """
17 _check_bitfield_length(length)
18 return 0
21def bitfield_upperbound(length: int) -> int:
22 """
23 Gets the upper bound of a unsigned bitfield type with given length.
25 :param length: Length of the unsigned bitfield in bits.
26 :returns: The largest value the unsigned bitfield can hold.
27 :raises PythonRuntimeException: If unsigned bitfield with wrong length has been specified.
28 """
30 _check_bitfield_length(length)
31 return (1 << length) - 1
34def signed_bitfield_lowerbound(length: int) -> int:
35 """
36 Gets the lower bound of a signed bitfield type with given length.
38 :param length: Length of the signed bitfield in bits.
39 :returns: The lowest value the signed bitfield can hold.
40 :raises PythonRuntimeException: If signed bitfield with wrong length has been specified.
41 """
43 _check_bitfield_length(length)
44 return -(1 << (length - 1))
47def signed_bitfield_upperbound(length: int) -> int:
48 """
49 Gets the upper bound of a signed bitfield type with given length.
51 :param length: Length of the signed bitfield in bits.
52 :returns: The largest value the signed bitfield can hold.
53 :raises PythonRuntimeException: If signed bitfield with wrong length has been specified.
54 """
56 _check_bitfield_length(length)
57 return (1 << (length - 1)) - 1
60def _check_bitfield_length(length: int) -> None:
61 if length <= 0 or length > MAX_BITFIELD_BITS:
62 raise PythonRuntimeException(f"bitfield: Asking for bound of bitfield with invalid length '{length}'!")
65MAX_BITFIELD_BITS = 64