-
Notifications
You must be signed in to change notification settings - Fork 82
/
custom_newline.py
37 lines (33 loc) · 1.01 KB
/
custom_newline.py
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
class CustomNewlineReader:
def __init__(self, fileobj, newline):
self.fileobj = fileobj
if len(newline) != 1:
raise ValueError("newline must be exactly one character long")
self.newline = newline
self.buffer_size = 1 << 18
self._chunks = []
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
self.fileobj.close()
def __iter__(self):
return self
def __next__(self):
if self._chunks:
return self._chunks.pop(0)
read = self.fileobj.read
buffer = read(self.buffer_size)
if not buffer:
raise StopIteration
extra = bytearray()
b = buffer[-1:]
while b != self.newline:
b = read(1)
if not b:
break
extra.append(b[0])
buffer += extra
self._chunks = buffer.split(self.newline)
if b == self.newline:
self._chunks = self._chunks[:-1]
return next(self)