-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmsgpack_decoder.py
More file actions
65 lines (51 loc) · 1.37 KB
/
Copy pathmsgpack_decoder.py
File metadata and controls
65 lines (51 loc) · 1.37 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
# msgpack_decoder.py
def decode(data):
i = 0
def read():
nonlocal i
val = data[i]
i += 1
return val
def read_bytes(n):
nonlocal i
val = data[i:i+n]
i += n
return val
def unpack():
prefix = read()
# FixInt (positive)
if prefix <= 0x7f:
return prefix
# FixMap
elif 0x80 <= prefix <= 0x8f:
size = prefix & 0x0f
obj = {}
for _ in range(size):
key = unpack()
val = unpack()
obj[key] = val
return obj
# FixArray
elif 0x90 <= prefix <= 0x9f:
size = prefix & 0x0f
return [unpack() for _ in range(size)]
# FixStr
elif 0xa0 <= prefix <= 0xbf:
size = prefix & 0x1f
return read_bytes(size).decode()
# uint8
elif prefix == 0xcc:
return read()
# uint16
elif prefix == 0xcd:
return int.from_bytes(read_bytes(2), 'big')
# uint32
elif prefix == 0xce:
return int.from_bytes(read_bytes(4), 'big')
# str8
elif prefix == 0xd9:
size = read()
return read_bytes(size).decode()
else:
raise ValueError(f"Unsupported prefix: {hex(prefix)}")
return unpack()