LazyStream
The LazyStream wrapper allows one to get and "unget" bytes from a stream.
Attributes
| Attribute | Type | Description |
|---|---|---|
| _producer | iterable | An iterable that returns a bytestring each time it is called to provide the underlying data stream. |
| _empty | boolean = False | A boolean flag indicating whether the stream has been exhausted. |
| _leftover | bytes = b"" | Stores bytes that have been "unget" or read from the producer but not yet consumed by the user. |
| length | integer | The total expected length of the stream in bytes, if known. |
| position | integer = 0 | The current byte offset within the stream, which is updated during read and unget operations. |
| _remaining | integer | The number of bytes remaining to be read from the stream based on the initial length. |
| _unget_history | list = [] | A list tracking the sizes of recent unget operations to detect potential infinite loops caused by malformed input. |
Constructor
Signature
def LazyStream(
producer: iterable,
length: int = None
) - > null
Parameters
| Name | Type | Description |
|---|---|---|
| producer | iterable | An iterable that returns a string each time it is called. |
| length | int = None | The total length of the stream, if known. |
Methods
tell()
@classmethod
def tell() - > int
Returns the current byte position within the stream, accounting for both read and unget operations.
Returns
| Type | Description |
|---|---|
int | The current integer offset from the start of the stream |
read()
@classmethod
def read(
size: int = None
) - > bytes
Reads a specified number of bytes from the stream, managing internal buffers and producer iteration to return exactly the requested amount.
Parameters
| Name | Type | Description |
|---|---|---|
| size | int = None | The maximum number of bytes to read; if None, reads until the stream is exhausted |
Returns
| Type | Description |
|---|---|
bytes | The bytestring containing the data read from the stream |
close()
@classmethod
def close()
Used to invalidate/disable this lazy stream. Replace the producer with an empty list. Any leftover bytes that have already been read will still be reported upon read() and/or next().
unget()
@classmethod
def unget(
bytes: bytes
)
Place bytes back onto the front of the lazy stream. Future calls to read() will return those bytes first. The stream position and thus tell() will be rewound.
Parameters
| Name | Type | Description |
|---|---|---|
| bytes | bytes | The bytestring to be pushed back into the stream's internal buffer |