-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathread_write.py
More file actions
283 lines (204 loc) · 8.42 KB
/
read_write.py
File metadata and controls
283 lines (204 loc) · 8.42 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
from __future__ import annotations
import struct
from typing import BinaryIO, Callable, TypeVar, Final
from uuid import UUID
UUID_ZERO: Final = UUID(int=0)
T = TypeVar("T")
def read_exact(buffer: BinaryIO, num_bytes: int) -> bytes:
value = buffer.read(num_bytes)
if len(value) != num_bytes:
raise ValueError(f"Buffer underflow: expected {num_bytes}, got {len(value)}")
return value
def read_int8(buffer: BinaryIO) -> int:
return int.from_bytes(read_exact(buffer, 1), byteorder="big", signed=True)
def write_int8(value: int, buffer: BinaryIO) -> None:
if -(2**7) <= value <= 2**7 - 1:
buffer.write(value.to_bytes(1, byteorder="big", signed=True))
else:
raise ValueError(f"Value {value} is out of range for INT8")
def read_boolean(buffer: BinaryIO) -> bool:
return read_int8(buffer) != 0
def write_boolean(value: bool, buffer: BinaryIO) -> None:
write_int8(1 if value is True else 0, buffer)
def read_int16(buffer: BinaryIO) -> int:
return int.from_bytes(read_exact(buffer, 2), byteorder="big", signed=True)
def write_int16(value: int, buffer: BinaryIO) -> None:
if -(2**15) <= value <= 2**15 - 1:
buffer.write(value.to_bytes(2, byteorder="big", signed=True))
else:
raise ValueError(f"Value {value} is out of range for INT16")
def read_int32(buffer: BinaryIO) -> int:
return int.from_bytes(read_exact(buffer, 4), byteorder="big", signed=True)
def write_int32(value: int, buffer: BinaryIO) -> None:
if -(2**31) <= value <= 2**31 - 1:
buffer.write(value.to_bytes(4, byteorder="big", signed=True))
else:
raise ValueError(f"Value {value} is out of range for INT32")
def read_int64(buffer: BinaryIO) -> int:
return int.from_bytes(read_exact(buffer, 8), byteorder="big", signed=True)
def write_int64(value: int, buffer: BinaryIO) -> None:
if -(2**63) <= value <= 2**63 - 1:
buffer.write(value.to_bytes(8, byteorder="big", signed=True))
else:
raise ValueError(f"Value {value} is out of range for INT64")
def read_uint16(buffer: BinaryIO) -> int:
return int.from_bytes(read_exact(buffer, 2), byteorder="big", signed=False)
def write_uint16(value: int, buffer: BinaryIO) -> None:
if 0 <= value <= 2**16 - 1:
buffer.write(value.to_bytes(2, byteorder="big", signed=False))
else:
raise ValueError(f"Value {value} is out of range for UINT16")
def read_float64(buffer: BinaryIO) -> float:
return struct.unpack(">d", read_exact(buffer, 8))[0]
def write_float64(value: float, buffer: BinaryIO) -> None:
buffer.write(struct.pack(">d", value))
def read_unsigned_varint(buffer: BinaryIO) -> int:
result = 0
# Go by 7 bit steps.
for offset in [0, 7, 14, 21, 28]:
byte = int.from_bytes(read_exact(buffer, 1), byteorder="big", signed=False)
# Concat the payload, 7 lower bits, to the result.
payload_bits = byte & 0b111_1111
result |= payload_bits << offset
# This is the last byte if its most significant bit is 0.
if byte & 0b1000_0000 == 0:
return result
else:
raise ValueError("Varint is too long, most significant bit in 5th byte is set")
def write_unsigned_varint(value: int, buffer: BinaryIO) -> None:
if value < 0 or value > 2**31 - 1:
raise ValueError(f"Value {value} is out of range for UNSIGNED VARINT")
written = False # has at least one byte been written?
while not written or value > 0:
byte_to_write = value & 0b111_1111 # 7 lower bits
value = value >> 7
# Add the bit that signifies that more is to come.
if value > 0:
byte_to_write |= 0b1000_0000
buffer.write(byte_to_write.to_bytes(1, byteorder="big", signed=False))
written = True
def read_uuid(buffer: BinaryIO) -> UUID | None:
byte_value: bytes = read_exact(buffer, 16)
if byte_value == UUID_ZERO.bytes:
return None
else:
return UUID(bytes=byte_value)
def write_uuid(value: UUID | None, buffer: BinaryIO) -> None:
if value is None:
buffer.write(UUID_ZERO.bytes)
else:
buffer.write(value.bytes)
def read_string(buffer: BinaryIO, compact: bool) -> str:
result = read_nullable_string(buffer, compact)
if result is None:
raise ValueError("Non-nullable field was serialized as null")
return result
def read_nullable_string(buffer: BinaryIO, compact: bool) -> str | None:
length = read_string_length(buffer, compact)
if length == -1:
return None
else:
return read_exact(buffer, length).decode(encoding="utf-8")
def read_string_length(buffer: BinaryIO, compact: bool) -> int:
# In the compact variant, stored lengths are increased by 1
# to preserve unsignedness.
length: int
if compact:
length = read_unsigned_varint(buffer) - 1
else:
length = read_int16(buffer)
if length < -1 or length > 2**15 - 1:
raise ValueError(f"string has invalid length {length}")
return length
def write_string(value: str, buffer: BinaryIO, compact: bool) -> None:
write_nullable_string(value, buffer, compact)
def write_nullable_string(value: str | None, buffer: BinaryIO, compact: bool) -> None:
if value is None:
write_string_length(-1, buffer, compact)
else:
value_b = value.encode(encoding="utf-8")
write_string_length(len(value_b), buffer, compact)
buffer.write(value_b)
def write_string_length(length: int, buffer: BinaryIO, compact: bool) -> None:
if length > 2**15 - 1:
raise ValueError(f"string has invalid length {length}")
# In the compact variant, stored lengths are increased by 1
# to preserve unsignedness.
if compact:
write_unsigned_varint(length + 1, buffer)
else:
write_int16(length, buffer)
def read_bytes(buffer: BinaryIO, compact: bool) -> bytes:
result = read_nullable_bytes(buffer, compact)
if result is None:
raise ValueError("Non-nullable field was serialized as null")
return result
def read_nullable_bytes(buffer: BinaryIO, compact: bool) -> bytes | None:
length = read_array_length(buffer, compact)
if length < -1 or length > 2**31 - 1:
raise ValueError(f"bytes has invalid length {length}")
if length == -1:
return None
else:
return read_exact(buffer, length)
def read_array_length(buffer: BinaryIO, compact: bool) -> int:
# In the compact variant, stored lengths are increased by 1
# to preserve unsignedness.
if compact:
return read_unsigned_varint(buffer) - 1
else:
return read_int32(buffer)
def write_bytes(value: bytes, buffer: BinaryIO, compact: bool) -> None:
write_nullable_bytes(value, buffer, compact)
def write_nullable_bytes(value: bytes | None, buffer: BinaryIO, compact: bool) -> None:
if value is None:
write_array_length(-1, buffer, compact)
else:
write_array_length(len(value), buffer, compact)
buffer.write(value)
def write_array_length(length: int, buffer: BinaryIO, compact: bool) -> None:
if length > 2**31 - 1:
raise ValueError(f"bytes has invalid length {length}")
# In the compact variant, stored lengths are increased by 1
# to preserve unsignedness.
if compact:
write_unsigned_varint(length + 1, buffer)
else:
write_int32(length, buffer)
def read_array(
read_element: Callable[[BinaryIO], T], buffer: BinaryIO, compact: bool
) -> list[T]:
result = read_nullable_array(read_element, buffer, compact)
if result is None:
raise ValueError("Non-nullable field was serialized as null")
return result
def read_nullable_array(
read_element: Callable[[BinaryIO], T], buffer: BinaryIO, compact: bool
) -> list[T] | None:
length = read_array_length(buffer, compact)
if length == -1:
return None
else:
array = []
for _ in range(length):
array.append(read_element(buffer))
return array
def write_array(
array: list[T],
write_element: Callable[[T, BinaryIO], None],
buffer: BinaryIO,
compact: bool,
) -> None:
write_nullable_array(array, write_element, buffer, compact)
def write_nullable_array(
array: list[T] | None,
write_element: Callable[[T, BinaryIO], None],
buffer: BinaryIO,
compact: bool,
) -> None:
if array is None:
write_array_length(-1, buffer, compact)
else:
write_array_length(len(array), buffer, compact)
for el in array:
write_element(el, buffer)