Debian Codegraph @

node/@bufbuild/protobuf/dist/esm/from-binary.js

raw
1 // Copyright 2021-2026 Buf Technologies, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 import { ScalarType } from "./descriptors.js";
15 import { scalarZeroValue } from "./reflect/scalar.js";
16 import { FieldError } from "./reflect/error.js";
17 import { unsafeLocal } from "./reflect/unsafe.js";
18 import { localMessageMapper } from "./reflect/message.js";
19 import { create } from "./create.js";
20 import { BinaryReader, WireType } from "./wire/binary-encoding.js";
21 import { varint32write } from "./wire/varint.js";
22 /**
23 * @private Only exported for getExtension()
24 */
25 export function makeReadContext(options) {
26 return Object.assign(Object.assign({ readUnknownFields: true, recursionLimit: 100 }, options), { depth: 0 });
27 }
28 /**
29 * Parse serialized binary data.
30 */
31 export function fromBinary(schema, bytes, options) {
32 const message = create(schema);
33 compiledReader(schema).read(message, new BinaryReader(bytes), makeReadContext(options), bytes.byteLength);
34 return message;
35 }
36 /**
37 * Parse from binary data, merging fields.
38 *
39 * Repeated fields are appended. Map entries are added, overwriting
40 * existing keys.
41 *
42 * If a message field is already present, it will be merged with the
43 * new data.
44 */
45 export function mergeFromBinary(schema, target, bytes, options) {
46 if (target.$typeName !== schema.typeName &&
47 schema.fields.length > 0) {
48 throw new FieldError(schema.fields[0], `cannot use ${schema.fields[0]} with message ${target.$typeName}`, "ForeignFieldError");
49 }
50 compiledReader(schema).read(target, new BinaryReader(bytes), makeReadContext(options), bytes.byteLength);
51 return target;
52 }
53 const compiledReaders = new WeakMap();
54 /**
55 * Return the compiled decoder for a message, compiling it on first use.
56 */
57 function compiledReader(desc) {
58 let compiled = compiledReaders.get(desc);
59 if (compiled === undefined) {
60 compiled = compileMessage(desc);
61 }
62 return compiled;
63 }
64 function compileMessage(desc) {
65 const descString = String(desc);
66 const fieldReaders = new Map();
67 const compiled = {
68 read: compileMessageReader(descString, fieldReaders),
69 readGroup: compileGroupReader(descString, fieldReaders),
70 };
71 // Register before compiling fields, so that recursive message types
72 // resolve to this instance instead of compiling endlessly.
73 compiledReaders.set(desc, compiled);
74 for (const field of desc.fields) {
75 fieldReaders.set(field.number, compileFieldReader(field));
76 }
77 return compiled;
78 }
79 /**
80 * Create a decoder for a length-prefixed message body, dispatching wire
81 * records to the compiled field decoders by field number.
82 */
83 function compileMessageReader(descString, fieldReaders) {
84 return (message, reader, ctx, length) => {
85 var _a;
86 if (++ctx.depth > ctx.recursionLimit) {
87 throw new Error(`cannot decode ${descString} from binary: maximum recursion depth of ${ctx.recursionLimit} reached`);
88 }
89 const end = reader.pos + length;
90 const unknownFields = (_a = message.$unknown) !== null && _a !== void 0 ? _a : [];
91 while (reader.pos < end) {
92 const [fieldNo, wireType] = reader.tag();
93 const fieldReader = fieldReaders.get(fieldNo);
94 if (fieldReader === undefined) {
95 // Use remaining recursion budget for skipping nested groups
96 const data = reader.skip(wireType, fieldNo, ctx.recursionLimit - ctx.depth);
97 if (ctx.readUnknownFields) {
98 unknownFields.push({ no: fieldNo, wireType, data });
99 }
100 continue;
101 }
102 fieldReader(message, reader, ctx, wireType);
103 }
104 if (unknownFields.length > 0) {
105 message.$unknown = unknownFields;
106 }
107 ctx.depth--;
108 };
109 }
110 /**
111 * Create a decoder for a message with the delimited encoding (group),
112 * reading until the EndGroup tag, like compileMessageReader.
113 */
114 function compileGroupReader(descString, fieldReaders) {
115 return (message, reader, ctx, fieldNo) => {
116 var _a;
117 if (++ctx.depth > ctx.recursionLimit) {
118 throw new Error(`cannot decode ${descString} from binary: maximum recursion depth of ${ctx.recursionLimit} reached`);
119 }
120 let recordFieldNo;
121 let wireType;
122 const unknownFields = (_a = message.$unknown) !== null && _a !== void 0 ? _a : [];
123 while (reader.pos < reader.len) {
124 [recordFieldNo, wireType] = reader.tag();
125 if (wireType == WireType.EndGroup) {
126 break;
127 }
128 const fieldReader = fieldReaders.get(recordFieldNo);
129 if (fieldReader === undefined) {
130 // Use remaining recursion budget for skipping nested groups
131 const data = reader.skip(wireType, recordFieldNo, ctx.recursionLimit - ctx.depth);
132 if (ctx.readUnknownFields) {
133 unknownFields.push({ no: recordFieldNo, wireType, data });
134 }
135 continue;
136 }
137 fieldReader(message, reader, ctx, wireType);
138 }
139 if (wireType != WireType.EndGroup || recordFieldNo !== fieldNo) {
140 throw new Error("invalid end group tag");
141 }
142 if (unknownFields.length > 0) {
143 message.$unknown = unknownFields;
144 }
145 ctx.depth--;
146 };
147 }
148 /**
149 * @private Only exported for getExtension()
150 */
151 export function readField(message, reader, field, wireType, ctx) {
152 compileFieldReader(field)(message[unsafeLocal], reader, ctx, wireType);
153 }
154 function compileFieldReader(field) {
155 switch (field.fieldKind) {
156 case "scalar":
157 return compileScalarFieldReader(field);
158 case "enum":
159 return compileEnumFieldReader(field);
160 case "message":
161 return compileMessageFieldReader(field);
162 case "list":
163 return compileListFieldReader(field);
164 case "map":
165 return compileMapFieldReader(field);
166 }
167 }
168 function compileScalarFieldReader(field) {
169 const readScalar = compileScalarReader(field.scalar, field.utf8Validation, field.longAsString);
170 const localName = field.localName;
171 if (field.oneof) {
172 const oneofLocalName = field.oneof.localName;
173 return (message, reader) => {
174 message[oneofLocalName] = {
175 case: localName,
176 value: readScalar(reader),
177 };
178 };
179 }
180 return (message, reader) => {
181 message[localName] = readScalar(reader);
182 };
183 }
184 function compileEnumFieldReader(field) {
185 var _a;
186 const localName = field.localName;
187 const oneofLocalName = (_a = field.oneof) === null || _a === void 0 ? void 0 : _a.localName;
188 if (field.enum.open) {
189 if (oneofLocalName !== undefined) {
190 return (message, reader) => {
191 message[oneofLocalName] = { case: localName, value: reader.int32() };
192 };
193 }
194 return (message, reader) => {
195 message[localName] = reader.int32();
196 };
197 }
198 // Closed enums: unknown values are stored as unknown fields.
199 const values = field.enum.values;
200 const fieldNo = field.number;
201 return (message, reader, ctx, wireType) => {
202 var _a;
203 const val = reader.int32();
204 if (values.some((v) => v.number === val)) {
205 if (oneofLocalName !== undefined) {
206 message[oneofLocalName] = { case: localName, value: val };
207 }
208 else {
209 message[localName] = val;
210 }
211 }
212 else if (ctx.readUnknownFields) {
213 const bytes = [];
214 varint32write(val, bytes);
215 const unknownFields = (_a = message.$unknown) !== null && _a !== void 0 ? _a : [];
216 unknownFields.push({
217 no: fieldNo,
218 wireType,
219 data: new Uint8Array(bytes),
220 });
221 message.$unknown = unknownFields;
222 }
223 };
224 }
225 function compileMessageFieldReader(field) {
226 const localName = field.localName;
227 const { toMessage, toLocal } = localMessageMapper(field);
228 const readChild = compileChildReader(field);
229 if (field.oneof) {
230 const oneofLocalName = field.oneof.localName;
231 return (message, reader, ctx) => {
232 const oneof = message[oneofLocalName];
233 const child = toMessage(oneof.case === localName ? oneof.value : undefined);
234 readChild(child, reader, ctx);
235 message[oneofLocalName] = { case: localName, value: toLocal(child) };
236 };
237 }
238 return (message, reader, ctx) => {
239 const child = toMessage(message[localName]);
240 readChild(child, reader, ctx);
241 message[localName] = toLocal(child);
242 };
243 }
244 /**
245 * Compile a decoder for the wire format of a message field, honoring the
246 * delimited encoding of the field.
247 */
248 function compileChildReader(field) {
249 const compiledChild = compiledReader(field.message);
250 if (field.delimitedEncoding) {
251 const fieldNo = field.number;
252 return (child, reader, ctx) => compiledChild.readGroup(child, reader, ctx, fieldNo);
253 }
254 return (child, reader, ctx) => compiledChild.read(child, reader, ctx, reader.uint32());
255 }
256 function compileListFieldReader(field) {
257 const localName = field.localName;
258 if (field.listKind == "message") {
259 const { toMessage, toLocal } = localMessageMapper(field);
260 const readChild = compileChildReader(field);
261 return (message, reader, ctx) => {
262 const child = toMessage(undefined);
263 readChild(child, reader, ctx);
264 message[localName].push(toLocal(child));
265 };
266 }
267 const scalarType = field.listKind == "enum" ? ScalarType.INT32 : field.scalar;
268 const longAsString = field.listKind == "scalar" ? field.longAsString : false;
269 const readScalar = compileScalarReader(scalarType, field.utf8Validation, longAsString);
270 const packedPossible = scalarType != ScalarType.STRING && scalarType != ScalarType.BYTES;
271 return (message, reader, ctx, wireType) => {
272 const items = message[localName];
273 if (wireType == WireType.LengthDelimited && packedPossible) {
274 const end = reader.uint32() + reader.pos;
275 while (reader.pos < end) {
276 items.push(readScalar(reader));
277 }
278 }
279 else {
280 items.push(readScalar(reader));
281 }
282 };
283 }
284 function compileMapFieldReader(field) {
285 const localName = field.localName;
286 const readKey = compileScalarReader(field.mapKey, field.utf8Validation, false);
287 const keyZero = scalarZeroValue(field.mapKey, false);
288 let readValue;
289 let valueDefault;
290 switch (field.mapKind) {
291 case "scalar": {
292 const scalar = field.scalar;
293 const readScalar = compileScalarReader(scalar, field.utf8Validation, false);
294 readValue = (reader) => readScalar(reader);
295 // Bytes zero values are created per entry, so that entries do not share
296 // one instance.
297 if (scalar == ScalarType.BYTES) {
298 valueDefault = () => new Uint8Array(0);
299 }
300 else {
301 const zero = scalarZeroValue(scalar, false);
302 valueDefault = () => zero;
303 }
304 break;
305 }
306 case "enum": {
307 const zero = field.enum.values[0].number;
308 readValue = (reader) => reader.int32();
309 valueDefault = () => zero;
310 break;
311 }
312 case "message": {
313 const { toMessage, toLocal } = localMessageMapper(field);
314 const readChild = compiledReader(field.message).read;
315 readValue = (reader, ctx) => {
316 const child = toMessage(undefined);
317 readChild(child, reader, ctx, reader.uint32());
318 return toLocal(child);
319 };
320 valueDefault = () => toLocal(toMessage(undefined));
321 break;
322 }
323 }
324 return (message, reader, ctx) => {
325 const record = message[localName];
326 let key;
327 let val;
328 // Read the length of the map entry, which is a varint.
329 const len = reader.uint32();
330 // Calculate end AFTER advancing reader.pos (above), so that reader.pos is
331 // at the start of the map entry.
332 const end = reader.pos + len;
333 while (reader.pos < end) {
334 // Map entries have the key in field 1, and the value in field 2.
335 const [fieldNo] = reader.tag();
336 switch (fieldNo) {
337 case 1:
338 key = readKey(reader);
339 break;
340 case 2:
341 val = readValue(reader, ctx);
342 break;
343 }
344 }
345 if (key === undefined) {
346 key = keyZero;
347 }
348 if (val === undefined) {
349 val = valueDefault();
350 }
351 // Object property keys are always strings or symbols. Assigning with a
352 // boolean, number, or bigint key implicitly converts it to a string.
353 record[key] = val;
354 };
355 }
356 /**
357 * Returns a reader for a scalar value. For 64-bit integers, BinaryReader
358 * already returns the local representation (bigint or string), so, unlike in
359 * the reflection layer, no validation is needed here.
360 */
361 function compileScalarReader(type, utf8Validation, longAsString) {
362 switch (type) {
363 case ScalarType.STRING:
364 return (reader) => reader.string(utf8Validation);
365 case ScalarType.BOOL:
366 return (reader) => reader.bool();
367 case ScalarType.DOUBLE:
368 return (reader) => reader.double();
369 case ScalarType.FLOAT:
370 return (reader) => reader.float();
371 case ScalarType.INT32:
372 return (reader) => reader.int32();
373 case ScalarType.INT64:
374 if (longAsString) {
375 return (reader) => String(reader.int64());
376 }
377 return (reader) => reader.int64();
378 case ScalarType.UINT64:
379 if (longAsString) {
380 return (reader) => String(reader.uint64());
381 }
382 return (reader) => reader.uint64();
383 case ScalarType.FIXED64:
384 if (longAsString) {
385 return (reader) => String(reader.fixed64());
386 }
387 return (reader) => reader.fixed64();
388 case ScalarType.BYTES:
389 return (reader) => reader.bytes();
390 case ScalarType.FIXED32:
391 return (reader) => reader.fixed32();
392 case ScalarType.SFIXED32:
393 return (reader) => reader.sfixed32();
394 case ScalarType.SFIXED64:
395 if (longAsString) {
396 return (reader) => String(reader.sfixed64());
397 }
398 return (reader) => reader.sfixed64();
399 case ScalarType.SINT64:
400 if (longAsString) {
401 return (reader) => String(reader.sint64());
402 }
403 return (reader) => reader.sint64();
404 case ScalarType.UINT32:
405 return (reader) => reader.uint32();
406 case ScalarType.SINT32:
407 return (reader) => reader.sint32();
408 }
409 }