Skip to content

Instantly share code, notes, and snippets.

@tripulse
Last active June 24, 2020 04:23
Show Gist options
  • Save tripulse/1b40450f264d0521642bea53fb98af24 to your computer and use it in GitHub Desktop.
Save tripulse/1b40450f264d0521642bea53fb98af24 to your computer and use it in GitHub Desktop.
File-stream emulation with Python buffer API.
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()
@tripulse
Copy link
Author

This is shouldn't be used as BytesIO is a inbuilt CPython implementation which is way faster than this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment