forked from xszyou/Fay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream_util.py
84 lines (66 loc) · 2.24 KB
/
stream_util.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from io import BytesIO
import threading
import functools
def synchronized(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
with self.lock:
return func(self, *args, **kwargs)
return wrapper
class StreamCache:
def __init__(self, maxbytes):
self.lock = threading.Lock()
self.bytesio = BytesIO()
self.writeSeek = 0
self.readSeek = 0
self.maxbytes = maxbytes
self.idle = 0
@synchronized
def write(self, bs):
# print("写:{},{}".format(len(bs),bs), end=' ')
if self.idle >= self.maxbytes:
print("缓存区不够用")
self.bytesio.seek(self.writeSeek)
if self.writeSeek + len(bs) <= self.maxbytes:
self.bytesio.write(bs)
else:
self.bytesio.write(bs[0:self.maxbytes - self.writeSeek])
self.bytesio.seek(0)
self.bytesio.write(bs[self.maxbytes - self.writeSeek:])
self.idle += len(bs)
self.writeSeek = self.bytesio.tell()
if self.writeSeek >= self.maxbytes - 1:
self.writeSeek = 0
@synchronized
def read(self, length, exception_on_overflow = False):
if self.idle < length:
return None
# print("读:{}".format(length), end=' ')
self.bytesio.seek(self.readSeek)
if self.readSeek + length <= self.maxbytes:
bs = self.bytesio.read(length)
else:
bs = self.bytesio.read(self.maxbytes - self.readSeek)
self.bytesio.seek(0)
bs.append(self.bytesio.read(self.readSeek + length - self.maxbytes))
self.idle -= length
self.readSeek = self.bytesio.tell()
if self.readSeek >= self.maxbytes - 1:
self.readSeek = 0
return bs
@synchronized
def clear(self):
self.bytesio = BytesIO()
self.writeSeek = 0
self.readSeek = 0
self.idle = 0
if __name__ == '__main__':
streamCache = StreamCache(5)
streamCache.write(b'\x01\x02')
streamCache.write(b'\x03\x04\x00')
print(streamCache.read(2))
print(streamCache.read(3))
streamCache.write(b'\x05\x06')
print(streamCache.read(2))
print(streamCache.read(2))
print(streamCache.read(3))