Coverage for oarepo_c4gh / crypt4gh / util.py: 100%
15 statements
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-06 16:58 +0000
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-06 16:58 +0000
1"""Miscellaneous helper functions for Crypt4GH stream processing.
3"""
5import io
8def read_crypt4gh_stream_le_uint32(
9 istream: io.RawIOBase, name: str = "number"
10) -> int:
11 """Reads little-endian integer from given stream handling read
12 errors with customizable error message.
14 Parameters:
15 istream: the container input stream
16 name: optional name of the number in the error message
18 Raises:
19 ValueError: if not enough data can be read
21 """
22 number_bytes = istream.read(4)
23 return parse_crypt4gh_bytes_le_uint(number_bytes, name, 4)
26def read_crypt4gh_bytes_le_uint32(
27 ibytes: bytes, offset: int, name: str = "number"
28) -> int:
29 """Extracts little-endian integer from given bytes object handling
30 errors with customizable message.
32 Parameters:
33 ibytes: bytes with the binary structure
34 offset: starting byte of the encoded number
35 name: optional name of the number in the error message
37 Raises:
38 ValueError: if not enough data given
40 """
41 number_bytes = ibytes[offset : offset + 4]
42 return parse_crypt4gh_bytes_le_uint(number_bytes, name, 4)
45def read_crypt4gh_bytes_le_uint64(
46 ibytes: bytes, offset: int, name: str = "number"
47) -> int:
48 """Extracts little-endian integer from given bytes object handling
49 errors with customizable message.
51 Parameters:
52 ibytes: bytes with the binary structure
53 offset: starting byte of the encoded number
54 name: optional name of the number in the error message
56 Raises:
57 ValueError: if not enough data given
59 """
60 number_bytes = ibytes[offset : offset + 8]
61 return parse_crypt4gh_bytes_le_uint(number_bytes, name, 8)
64def parse_crypt4gh_bytes_le_uint(
65 number_bytes: bytes, name: str, size: int
66) -> int:
67 """Parses size-byte little-endian binary number from given bytes
68 handling insufficient data errors with customizable error message.
70 Parameters:
71 number_bytes: the bytes to parse
72 name: optional name of the number in the error message
73 size: number of bytes the encoding should contain
75 Raises:
76 ValueError: if the bytes given are too short
78 """
79 number_bytes_len = len(number_bytes)
80 if number_bytes_len != size:
81 raise ValueError(
82 f"Only {number_bytes_len} bytes for reading le_uint({size}) {name}"
83 )
84 return int.from_bytes(number_bytes, byteorder="little")