File size: 1,431 Bytes
44bafb2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
"""This module implements a `Buffer` class for handling in-memory data storage, downloading streams,
and redirecting content to standard output (stdout)."""
import sys
import io
class Buffer:
def __init__(self):
"""
Initializes the in-memory buffer to store data.
"""
self.buffer = io.BytesIO()
def download_in_buffer(self, source):
"""
Downloads data directly into the buffer. Accepts objects with the `stream_to_buffer`
method or strings.
Args:
source: Object or data to be written to the buffer.
"""
if hasattr(source, 'stream_to_buffer') and callable(source.stream_to_buffer):
source.stream_to_buffer(self.buffer)
elif isinstance(source, str):
self.buffer.write(source.encode('utf-8'))
else:
raise TypeError("The provided object is not compatible for downloading into the buffer.")
def redirect_to_stdout(self):
"""
Redirects the buffer's content to stdout.
"""
self.buffer.seek(0) # Go back to the start of the buffer
sys.stdout.buffer.write(self.buffer.read())
def read(self):
"""
Reads the buffer's content.
"""
self.buffer.seek(0)
return self.buffer.read()
def clear(self):
"""
Clears the buffer for reuse.
"""
self.buffer = io.BytesIO() |