Created
July 29, 2020 14:40
-
-
Save justinmklam/d8d1c60678827fc4d3943c548cf4d1c2 to your computer and use it in GitHub Desktop.
Faster implementation of pyserial's readline. Source: https://github.com/pyserial/pyserial/issues/216#issuecomment-369414522
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
#!/usr/bin/python3 | |
class ReadLine: | |
def __init__(self, s): | |
self.buf = bytearray() | |
self.s = s | |
def readline(self): | |
i = self.buf.find(b"\n") | |
if i >= 0: | |
r = self.buf[:i+1] | |
self.buf = self.buf[i+1:] | |
return r | |
while True: | |
i = max(1, min(2048, self.s.in_waiting)) | |
data = self.s.read(i) | |
i = data.find(b"\n") | |
if i >= 0: | |
r = self.buf + data[:i+1] | |
self.buf[0:] = data[i+1:] | |
return r | |
else: | |
self.buf.extend(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment