-
Notifications
You must be signed in to change notification settings - Fork 124
/
reflection-binary-writer.ts
268 lines (231 loc) · 9.38 KB
/
reflection-binary-writer.ts
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
import type {BinaryWriteOptions, IBinaryWriter} from "./binary-format-contract";
import {UnknownFieldHandler, WireType} from "./binary-format-contract";
import type {FieldInfo} from "./reflection-info";
import {PartialMessageInfo, RepeatType, ScalarType} from "./reflection-info";
import type {IMessageType} from "./message-type-contract";
import {assert} from "./assert";
import {PbLong, PbULong} from "./pb-long";
import type {UnknownMessage, UnknownOneofGroup} from "./unknown-types";
/**
* Writes proto3 messages in binary format using reflection information.
*
* https://developers.google.com/protocol-buffers/docs/encoding
*/
export class ReflectionBinaryWriter {
protected fields?: readonly FieldInfo[];
constructor(private readonly info: PartialMessageInfo) {
}
protected prepare() {
if (!this.fields) {
const fieldsInput = this.info.fields ? this.info.fields.concat() : [];
this.fields = fieldsInput.sort((a, b) => a.no - b.no);
}
}
/**
* Writes the message to binary format.
*/
write<T extends object>(message: T, writer: IBinaryWriter, options: BinaryWriteOptions): void {
this.prepare();
for (const field of this.fields!) {
let value, // this will be our field value, whether it is member of a oneof or not
emitDefault, // whether we emit the default value (only true for oneof members)
repeated = field.repeat,
localName = field.localName;
// handle oneof ADT
if (field.oneof) {
const group = (message as UnknownMessage)[field.oneof] as UnknownOneofGroup;
if (group.oneofKind !== localName)
continue; // if field is not selected, skip
value = group[localName];
emitDefault = true;
} else {
value = (message as UnknownMessage)[localName];
emitDefault = false;
}
// we have handled oneof above. we just have to honor `emitDefault`.
switch (field.kind) {
case "scalar":
case "enum":
let T = field.kind == "enum" ? ScalarType.INT32 : field.T;
if (repeated) {
assert(Array.isArray(value));
if (repeated == RepeatType.PACKED)
this.packed(writer, T, field.no, value);
else
for (const item of value)
this.scalar(writer, T, field.no, item, true);
} else if (value === undefined)
assert(field.opt);
else
this.scalar(writer, T, field.no, value, emitDefault || field.opt);
break;
case "message":
if (repeated) {
assert(Array.isArray(value));
for (const item of value)
this.message(writer, options, field.T(), field.no, item);
} else {
this.message(writer, options, field.T(), field.no, value);
}
break;
case "map":
assert(typeof value == 'object' && value !== null);
for (const [key, val] of Object.entries(value))
this.mapEntry(writer, options, field, key, val);
break;
}
}
let u = options.writeUnknownFields;
if (u !== false)
(u === true ? UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer);
}
protected mapEntry(writer: IBinaryWriter, options: BinaryWriteOptions, field: FieldInfo & { kind: 'map' }, key: any, value: any): void {
writer.tag(field.no, WireType.LengthDelimited);
writer.fork();
// javascript only allows number or string for object properties
// we convert from our representation to the protobuf type
let keyValue = key;
switch (field.K) {
case ScalarType.INT32:
case ScalarType.FIXED32:
case ScalarType.UINT32:
case ScalarType.SFIXED32:
case ScalarType.SINT32:
keyValue = Number.parseInt(key);
break;
case ScalarType.BOOL:
assert(key == 'true' || key == 'false');
keyValue = key == 'true';
break;
}
// write key, expecting key field number = 1
this.scalar(writer, field.K, 1, keyValue, true);
// write value, expecting value field number = 2
switch (field.V.kind) {
case 'scalar':
this.scalar(writer, field.V.T, 2, value, true);
break;
case 'enum':
this.scalar(writer, ScalarType.INT32, 2, value, true);
break;
case 'message':
this.message(writer, options, field.V.T(), 2, value);
break;
}
writer.join();
}
protected message(writer: IBinaryWriter, options: BinaryWriteOptions, handler: IMessageType<any>, fieldNo: number, value: any) {
if (value === undefined)
return;
handler.internalBinaryWrite(value, writer.tag(fieldNo, WireType.LengthDelimited).fork(), options);
writer.join();
}
/**
* Write a single scalar value.
*/
protected scalar(writer: IBinaryWriter, type: ScalarType, fieldNo: number, value: any, emitDefault: boolean): void {
let [wireType, method, isDefault] = this.scalarInfo(type, value);
if (!isDefault || emitDefault) {
writer.tag(fieldNo, wireType);
(writer[method] as (val: any) => IBinaryWriter)(value);
}
}
/**
* Write an array of scalar values in packed format.
*/
protected packed(writer: IBinaryWriter, type: ScalarType, fieldNo: number, value: any[]): void {
if (!value.length)
return;
assert(type !== ScalarType.BYTES && type !== ScalarType.STRING);
// write tag
writer.tag(fieldNo, WireType.LengthDelimited);
// begin length-delimited
writer.fork();
// write values without tags
let [, method,] = this.scalarInfo(type);
for (let i = 0; i < value.length; i++)
(writer[method] as (val: any) => IBinaryWriter)(value[i]);
// end length delimited
writer.join();
}
/**
* Get information for writing a scalar value.
*
* Returns tuple:
* [0]: appropriate WireType
* [1]: name of the appropriate method of IBinaryWriter
* [2]: whether the given value is a default value
*
* If argument `value` is omitted, [2] is always false.
*/
protected scalarInfo(type: ScalarType, value?: any): [WireType, "int32" | "string" | "bool" | "uint32" | "double" | "float" | "int64" | "uint64" | "fixed64" | "bytes" | "fixed32" | "sfixed32" | "sfixed64" | "sint32" | "sint64", boolean] {
let t = WireType.Varint;
let m: "int32" | "string" | "bool" | "uint32" | "double" | "float" | "int64" | "uint64" | "fixed64" | "bytes" | "fixed32" | "sfixed32" | "sfixed64" | "sint32" | "sint64";
let i = value === undefined;
let d = value === 0;
switch (type) {
case ScalarType.INT32:
m = "int32";
break;
case ScalarType.STRING:
d = i || !value.length;
t = WireType.LengthDelimited;
m = "string";
break;
case ScalarType.BOOL:
d = value === false;
m = "bool";
break;
case ScalarType.UINT32:
m = "uint32";
break;
case ScalarType.DOUBLE:
t = WireType.Bit64;
m = "double";
break;
case ScalarType.FLOAT:
t = WireType.Bit32;
m = "float";
break;
case ScalarType.INT64:
d = i || PbLong.from(value).isZero();
m = "int64";
break;
case ScalarType.UINT64:
d = i || PbULong.from(value).isZero();
m = "uint64";
break;
case ScalarType.FIXED64:
d = i || PbULong.from(value).isZero();
t = WireType.Bit64;
m = "fixed64";
break;
case ScalarType.BYTES:
d = i || !(value as Uint8Array).byteLength;
t = WireType.LengthDelimited;
m = "bytes";
break;
case ScalarType.FIXED32:
t = WireType.Bit32;
m = "fixed32";
break;
case ScalarType.SFIXED32:
t = WireType.Bit32;
m = "sfixed32";
break;
case ScalarType.SFIXED64:
d = i || PbLong.from(value).isZero();
t = WireType.Bit64;
m = "sfixed64";
break;
case ScalarType.SINT32:
m = "sint32";
break;
case ScalarType.SINT64:
d = i || PbLong.from(value).isZero();
m = "sint64";
break;
}
return [t, m, i || d];
}
}