Merge implementations of read_exact functions/methods

The old functions/methods still exist, so that they continue to raise
the same exceptions as before (which are different depending on
context), but they now use the same implementation internally.
This commit is contained in:
dgelessus
2020-07-18 21:07:12 +02:00
parent 4bbf2f7c14
commit 476a68916b
3 changed files with 29 additions and 8 deletions

18
rsrcfork/_io_utils.py Normal file
View File

@@ -0,0 +1,18 @@
"""A collection of utility functions and classes related to IO streams. For internal use only."""
import typing
def read_exact(stream: typing.BinaryIO, byte_count: int) -> bytes:
"""Read byte_count bytes from the stream and raise an exception if too few bytes are read (i. e. if EOF was hit prematurely).
:param stream: The stream to read from.
:param byte_count: The number of bytes to read.
:return: The read data, which is exactly ``byte_count`` bytes long.
:raise EOFError: If not enough data could be read from the stream.
"""
data = stream.read(byte_count)
if len(data) != byte_count:
raise EOFError(f"Attempted to read {byte_count} bytes of data, but only got {len(data)} bytes")
return data