OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / tendermint / abci / example / python3 / abci / reader.py
1
2 # Simple read() method around a bytearray
3
4
5 class BytesBuffer():
6
7     def __init__(self, b):
8         self.buf = b
9         self.readCount = 0
10
11     def count(self):
12         return self.readCount
13
14     def reset_count(self):
15         self.readCount = 0
16
17     def size(self):
18         return len(self.buf)
19
20     def peek(self):
21         return self.buf[0]
22
23     def write(self, b):
24         # b should be castable to byte array
25         self.buf += bytearray(b)
26
27     def read(self, n):
28         if len(self.buf) < n:
29             print("reader err: buf less than n")
30             # TODO: exception
31             return
32         self.readCount += n
33         r = self.buf[:n]
34         self.buf = self.buf[n:]
35         return r
36
37 # Buffer bytes off a tcp connection and read them off in chunks
38
39
40 class ConnReader():
41
42     def __init__(self, conn):
43         self.conn = conn
44         self.buf = bytearray()
45
46     # blocking
47     def read(self, n):
48         while n > len(self.buf):
49             moreBuf = self.conn.recv(1024)
50             if not moreBuf:
51                 raise IOError("dead connection")
52             self.buf = self.buf + bytearray(moreBuf)
53
54         r = self.buf[:n]
55         self.buf = self.buf[n:]
56         return r