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-12-05 10:43 +0000

1""" 

2The module provides help methods for bit fields calculation. 

3""" 

4 

5from zserio.exception import PythonRuntimeException 

6 

7 

8def bitfield_lowerbound(length: int) -> int: 

9 """ 

10 Gets the lower bound of a unsigned bitfield type with given length. 

11 

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 """ 

16 

17 _check_bitfield_length(length) 

18 return 0 

19 

20 

21def bitfield_upperbound(length: int) -> int: 

22 """ 

23 Gets the upper bound of a unsigned bitfield type with given length. 

24 

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 """ 

29 

30 _check_bitfield_length(length) 

31 return (1 << length) - 1 

32 

33 

34def signed_bitfield_lowerbound(length: int) -> int: 

35 """ 

36 Gets the lower bound of a signed bitfield type with given length. 

37 

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 """ 

42 

43 _check_bitfield_length(length) 

44 return -(1 << (length - 1)) 

45 

46 

47def signed_bitfield_upperbound(length: int) -> int: 

48 """ 

49 Gets the upper bound of a signed bitfield type with given length. 

50 

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 """ 

55 

56 _check_bitfield_length(length) 

57 return (1 << (length - 1)) - 1 

58 

59 

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}'!") 

63 

64 

65MAX_BITFIELD_BITS = 64