-
Notifications
You must be signed in to change notification settings - Fork 1
/
filebytecontent.py
62 lines (52 loc) · 1.51 KB
/
filebytecontent.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
import threading
class FileByteContent:
def __init__(self, text):
self._text = text
self._cond = threading.Condition(threading.Lock())
self._readers = 0
def _r_acquire(self):
self._cond.acquire()
try:
self._readers += 1
finally:
self._cond.release()
def _r_release(self):
self._cond.acquire()
try:
self._readers -= 1
if self._readers == 0:
self._cond.notify_all()
finally:
self._cond.release()
def _w_acquire(self):
self._cond.acquire()
while self._readers > 0:
self._cond.wait()
def _w_release(self):
self._cond.release()
def __len__(self):
self._r_acquire()
length = len(self._text)
self._r_release()
return length
def read_all(self):
self._r_acquire()
text = self._text
self._r_release()
return text
def read_bytes(self, offset, length):
self._r_acquire()
text = self._text[offset:offset + length]
self._r_release()
return text
def write_bytes(self, buf, offset):
self._w_acquire()
bytes_written = len(buf)
new_text = self._text[:offset] + buf + self._text[offset+bytes_written:]
self._text = new_text
self._w_release()
return bytes_written
def truncate(self, length):
self._w_acquire()
self._text = self._text[:length]
self._w_release()