forked from LagrangeDev/lagrange-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoder.py
174 lines (137 loc) · 4.61 KB
/
coder.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
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
from typing import Union, TypeVar, TYPE_CHECKING, cast
from collections.abc import Mapping, Sequence
from typing_extensions import Self, TypeAlias
from lagrange.utils.binary.builder import Builder
from lagrange.utils.binary.reader import Reader
Proto: TypeAlias = dict[int, "ProtoEncodable"]
LengthDelimited: TypeAlias = Union[str, "Proto", bytes]
ProtoEncodable: TypeAlias = Union[
int,
float,
bool,
LengthDelimited,
Sequence["ProtoEncodable"],
Mapping[int, "ProtoEncodable"],
]
TProtoEncodable = TypeVar("TProtoEncodable", bound="ProtoEncodable")
class ProtoDecoded:
def __init__(self, proto: Proto):
self.proto = proto
def __getitem__(self, item: int) -> "ProtoEncodable":
return self.proto[item]
def into(self, field: Union[int, tuple[int, ...]], tp: type[TProtoEncodable]) -> TProtoEncodable:
if isinstance(field, int):
return self.proto[field] # type: ignore
else:
data = self.proto
for f in field:
data = data[f] # type: ignore
return data # type: ignore
class ProtoBuilder(Builder):
def write_varint(self, v: int) -> Self:
if v >= 127:
buffer = bytearray()
while v > 127:
buffer.append((v & 127) | 128)
v >>= 7
buffer.append(v)
self.write_bytes(buffer)
else:
self.write_u8(v)
return self
def write_length_delimited(self, v: LengthDelimited) -> Self:
if isinstance(v, dict):
v = proto_encode(v)
elif isinstance(v, str):
v = v.encode("utf-8")
self.write_varint(len(v)).write_bytes(v)
return self
class ProtoReader(Reader):
def read_varint(self) -> int:
value = 0
count = 0
while True:
byte = self.read_u8()
value |= (byte & 127) << (count * 7)
count += 1
if (byte & 128) <= 0:
break
return value
def read_length_delimited(self) -> bytes:
length = self.read_varint()
data = self.read_bytes(length)
if len(data) != length:
raise ValueError("length of data does not match")
return data
def _encode(builder: ProtoBuilder, tag: int, value: ProtoEncodable):
if value is None:
return
if isinstance(value, int):
wire_type = 0
elif isinstance(value, bool):
wire_type = 0
elif isinstance(value, float):
wire_type = 1
elif isinstance(value, (str, bytes, bytearray, dict)):
wire_type = 2
else:
raise Exception("Unsupported wire type in protobuf")
head = int(tag) << 3 | wire_type
builder.write_varint(head)
if wire_type == 0:
if isinstance(value, bool):
value = 1 if value else 0
if TYPE_CHECKING:
assert isinstance(value, int)
if value >= 0:
builder.write_varint(value)
else:
raise NotImplementedError
elif wire_type == 1:
raise NotImplementedError
elif wire_type == 2:
if isinstance(value, dict):
value = proto_encode(value)
if TYPE_CHECKING:
value = cast(LengthDelimited, value)
builder.write_length_delimited(value)
else:
raise AssertionError
def proto_decode(data: bytes, max_layer=-1) -> ProtoDecoded:
reader = ProtoReader(data)
proto = {}
while reader.remain > 0:
leaf = reader.read_varint()
tag = leaf >> 3
wire_type = leaf & 0b111
assert tag > 0, f"Invalid tag: {tag}"
if wire_type == 0:
value = reader.read_varint()
elif wire_type == 2:
value = reader.read_length_delimited()
if max_layer > 0 or max_layer < 0 and len(value) > 1:
try: # serialize nested
value = proto_decode(value, max_layer - 1).proto
except Exception:
pass
elif wire_type == 5:
value = reader.read_u32()
else:
raise AssertionError(wire_type)
if tag in proto: # repeated elem
if not isinstance(proto[tag], list):
proto[tag] = [proto[tag]]
proto[tag].append(value)
else:
proto[tag] = value
return ProtoDecoded(proto)
def proto_encode(proto: Proto) -> bytes:
builder = ProtoBuilder()
for tag in proto:
value = proto[tag]
if isinstance(value, list):
for i in value:
_encode(builder, tag, i)
else:
_encode(builder, tag, value)
return bytes(builder.data)