Last active
June 24, 2020 04:23
-
-
Save tripulse/1b40450f264d0521642bea53fb98af24 to your computer and use it in GitHub Desktop.
File-stream emulation with Python buffer API.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io | |
class ByteWriter(io.RawIOBase): | |
""" | |
Emulates file-writing by pushing the content into a underyling buffer. | |
Underlying buffer stores the data contents in the RAM, dumps them when required. | |
>>> from bytewriter import ByteWriter | |
>>> b = ByteWriter() | |
>>> b.write(b"Hello World") | |
>>> bytes(b) | |
b'Hello World' | |
""" | |
_rawbuf = bytes() | |
def read(self, n=-1): | |
raise OSError() | |
def readable(self): | |
return False | |
def writable(self): | |
return True | |
def write(self, _o): | |
self._rawbuf+= _o | |
def writelines(self, lines, crlf= False): | |
LINE_CHAR = '\r\n' if crlf else '\n' | |
for line in lines: | |
self.write(line + LINE_CHAR) | |
def _flush(self): | |
self._rawbuf = bytes() | |
def __bytes__(self): | |
return self._rawbuf | |
self._flush() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is shouldn't be used as
BytesIO
is a inbuilt CPython implementation which is way faster than this.