-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparse_utils.py
More file actions
63 lines (51 loc) · 1.98 KB
/
parse_utils.py
File metadata and controls
63 lines (51 loc) · 1.98 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
from datetime import datetime
from enum import IntEnum
from value_converter import ValueConverter
class ParseUtils():
@staticmethod
def consume(data: bytes, n: int) -> tuple[int, bytes]:
# NOTE: copying this bytes object every time is rather wasteful
assert n <= len(data)
value = int.from_bytes(data[0:n], "little")
return value, data[n:]
@staticmethod
def consume_u8(data: bytes) -> tuple[int, bytes]:
value, data = __class__.consume(data, 1)
return value, data
@staticmethod
def consume_u16(data: bytes) -> tuple[int, bytes]:
value, data = __class__.consume(data, 2)
return value, data
@staticmethod
def consume_u32(data: bytes) -> tuple[int, bytes]:
value, data = __class__.consume(data, 4)
return value, data
@staticmethod
def consume_i8(data: bytes) -> tuple[int, bytes]:
value, data = __class__.consume(data, 1)
value = ValueConverter.sign_extend(value, 8)
return value, data
@staticmethod
def consume_i16(data: bytes) -> tuple[int, bytes]:
value, data = __class__.consume(data, 2)
value = ValueConverter.sign_extend(value, 16)
return value, data
@staticmethod
def consume_f16(data: bytes) -> tuple[float, bytes]:
value, data = __class__.consume(data, 2)
value = ValueConverter.decode_medfloat16(value)
return value, data
@staticmethod
def consume_f32(data: bytes) -> tuple[float, bytes]:
value, data = __class__.consume(data, 4)
value = ValueConverter.decode_medfloat32(value)
return value, data
@staticmethod
def consume_datetime(data: bytes) -> tuple[datetime, bytes]:
n = 7
assert n <= len(data)
value = ValueConverter.decode_datetime(data[0:n])
return value, data[n:]
@staticmethod
def parse_flags(raw: int, enum_type: type[IntEnum]) -> list[IntEnum]:
return [flag for flag in enum_type if raw & flag]