Coverage for oarepo_c4gh/crypt4gh/util.py: 100%
12 statements
« prev ^ index » next coverage.py v7.10.2, created at 2025-08-07 12:05 +0000
« prev ^ index » next coverage.py v7.10.2, created at 2025-08-07 12:05 +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 parse_crypt4gh_bytes_le_uint(
46 number_bytes: bytes, name: str, size: int
47) -> int:
48 """Parses size-byte little-endian binary number from given bytes
49 handling insufficient data errors with customizable error message.
51 Parameters:
52 number_bytes: the bytes to parse
53 name: optional name of the number in the error message
54 size: number of bytes the encoding should contain
56 Raises:
57 ValueError: if the bytes given are too short
59 """
60 number_bytes_len = len(number_bytes)
61 if number_bytes_len != size:
62 raise ValueError(
63 f"Only {number_bytes_len} bytes for reading le_uint({size}) {name}"
64 )
65 return int.from_bytes(number_bytes, byteorder="little")