forked from micheleberetta98/freya-fs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filebytecontent.py
71 lines (61 loc) · 1.92 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
63
64
65
66
67
68
69
70
71
import threading
class FileByteContent:
def __init__(self, text):
# NOTE: We use bytearray instead of bytes because we may need to extend
# it due to write operations
self._text = bytearray(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 bytes(text)
def read_bytes(self, offset, length):
self._r_acquire()
text = self._text[offset:offset + length]
self._r_release()
return bytes(text)
def write_bytes(self, buf, offset):
self._w_acquire()
# Rewrite old part of the text
bytes_written = 0
current_size = len(self._text)
if offset < current_size:
self._text[offset:] = buf[:(current_size - offset)]
bytes_written += current_size - offset
# Concatenate new part of the text
if bytes_written < len(buf):
self._text.extend(buf[bytes_written:])
bytes_written = len(buf)
self._w_release()
return bytes_written
def truncate(self, length):
self._w_acquire()
self._text = self._text[:length]
self._w_release()