File size: 1,477 Bytes
b4c506d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
import io
import logging


logger = logging.getLogger(__name__)


class StringIteratorIO(io.TextIOBase):
    """From: https://stackoverflow.com/a/12604375"""

    def __init__(self, iter):
        self._iter = iter
        self._left = ''

    def readable(self):
        return True

    def _read1(self, n=None):
        while not self._left:
            try:
                self._left = next(self._iter)
            except StopIteration:
                break
        ret = self._left[:n]
        self._left = self._left[len(ret):]
        return ret

    def read(self, n=None):
        buf = []
        if n is None or n < 0:
            while True:
                m = self._read1()
                if not m:
                    break
                buf.append(m)
        else:
            while n > 0:
                m = self._read1(n)
                if not m:
                    break
                n -= len(m)
                buf.append(m)
        return ''.join(buf)

    def readline(self):
        buf = []
        while True:
            i = self._left.find('\n')
            if i == -1:
                buf.append(self._left)
                try:
                    self._left = next(self._iter)
                except StopIteration:
                    self._left = ''
                    break
            else:
                buf.append(self._left[:i+1])
                self._left = self._left[i+1:]
                break
        return ''.join(buf)