-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.py
More file actions
71 lines (54 loc) · 2.39 KB
/
binary.py
File metadata and controls
71 lines (54 loc) · 2.39 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
from typing import IO, Literal
class Binary:
def __init__(self,
io: IO,
char_encoding: str,
byteorder: Literal["little", "big"] = "little") -> None:
self._io = io
self.byteorder = byteorder
self.char_encoding = char_encoding
@property
def current_position(self) -> int:
return self._io.tell()
def move_to_position(self,
offset: int,
from_start: bool = True,
from_current: bool = False,
from_end: bool = False) -> int:
if from_start: return self._io.seek(offset, 0)
elif from_current: return self._io.seek(offset, 1)
elif from_end: return self._io.seek(offset, 2)
else: return 0
def read_bytes(self, size: int) -> bytes:
if not self._io.readable(): return b'\x00' * size
return self._io.read(size)
def write_bytes(self, source: bytes) -> int:
if not self._io.writable(): return 0
return self._io.write(source)
def read_integer(self, size: int = 4, signed: bool = False) -> int:
serialized_integer = self.read_bytes(size)
return int.from_bytes(serialized_integer, self.byteorder, signed=signed)
def write_integer(self, integer: int = 0, size: int = 4, signed: bool = False) -> int:
serialized_integer = integer.to_bytes(size, self.byteorder, signed=signed)
return self.write_bytes(serialized_integer)
def read_char(self, size: int = 1) -> str:
serialized_char = self.read_bytes(size)
return serialized_char.replace(b"\x00", b"").decode(self.char_encoding)
def write_char(self, source: str, size: int = 1) -> int:
serialized_char = source.rjust("\0").encode(self.char_encoding)
return self.write_bytes(serialized_char)
def read_string(self) -> str:
length = self.read_integer()
char = self.read_char(length)
while self.current_position % 4 != 0:
if length == 0:
break
assert self.read_char() == "@"
return char
def write_string(self, string: str) -> None:
length = len(string)
self.write_integer(length)
self.write_char(string, length)
while length % 4 != 0:
self.write_char("@")
length += 1