Debian Codegraph @

node/@bufbuild/protobuf/dist/commonjs/wire/size-delimited.js

raw
1 "use strict";
2 // Copyright 2021-2026 Buf Technologies, Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 var __asyncValues = (this && this.__asyncValues) || function (o) {
16 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
17 var m = o[Symbol.asyncIterator], i;
18 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
19 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
20 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
21 };
22 var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
23 var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
24 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
25 var g = generator.apply(thisArg, _arguments || []), i, q = [];
26 return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
27 function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
28 function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
29 function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
30 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
31 function fulfill(value) { resume("next", value); }
32 function reject(value) { resume("throw", value); }
33 function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
34 };
35 Object.defineProperty(exports, "__esModule", { value: true });
36 exports.sizeDelimitedEncode = sizeDelimitedEncode;
37 exports.sizeDelimitedDecodeStream = sizeDelimitedDecodeStream;
38 exports.sizeDelimitedPeek = sizeDelimitedPeek;
39 const to_binary_js_1 = require("../to-binary.js");
40 const binary_encoding_js_1 = require("./binary-encoding.js");
41 const from_binary_js_1 = require("../from-binary.js");
42 /**
43 * Serialize a message, prefixing it with its size.
44 *
45 * A size-delimited message is a varint size in bytes, followed by exactly
46 * that many bytes of a message serialized with the binary format.
47 *
48 * This size-delimited format is compatible with other implementations.
49 * For details, see https://github.com/protocolbuffers/protobuf/issues/10229
50 */
51 function sizeDelimitedEncode(messageDesc, message, options) {
52 const writer = new binary_encoding_js_1.BinaryWriter();
53 writer.bytes((0, to_binary_js_1.toBinary)(messageDesc, message, options));
54 return writer.finish();
55 }
56 // Default for SizeDelimitedDecodeOptions.readMaxBytes.
57 const defaultReadMaxBytes = 64 * 1024 * 1024; // 64 MiB
58 /**
59 * A growable byte buffer. Used in place of a resizable ArrayBuffer, which is
60 * not widely available.
61 */
62 class ByteBuffer {
63 constructor() {
64 this.buffer = new Uint8Array(0);
65 this.length = 0;
66 }
67 get byteLength() {
68 return this.length;
69 }
70 bytes() {
71 return this.buffer.subarray(0, this.length);
72 }
73 append(chunk) {
74 const newByteLength = this.length + chunk.byteLength;
75 if (newByteLength > this.buffer.byteLength) {
76 const grown = new Uint8Array(Math.max(this.buffer.byteLength * 2, newByteLength));
77 grown.set(this.buffer.subarray(0, this.length));
78 this.buffer = grown;
79 }
80 this.buffer.set(chunk, this.length);
81 this.length += chunk.byteLength;
82 }
83 }
84 /**
85 * Parse a stream of size-delimited messages.
86 *
87 * A size-delimited message is a varint size in bytes, followed by exactly
88 * that many bytes of a message serialized with the binary format.
89 *
90 * This size-delimited format is compatible with other implementations.
91 * For details, see https://github.com/protocolbuffers/protobuf/issues/10229
92 *
93 * Messages exceeding the limit given with the option readMaxBytes raise an
94 * error. The limit is 64 MiB by default. All other options are the
95 * standard binary read options, passed through to decode each message.
96 */
97 function sizeDelimitedDecodeStream(messageDesc, iterable, options) {
98 return __asyncGenerator(this, arguments, function* sizeDelimitedDecodeStream_1() {
99 var _a, e_1, _b, _c;
100 var _d;
101 const readMaxBytes = (_d = options === null || options === void 0 ? void 0 : options.readMaxBytes) !== null && _d !== void 0 ? _d : defaultReadMaxBytes;
102 let buffer = new ByteBuffer();
103 try {
104 for (var _e = true, iterable_1 = __asyncValues(iterable), iterable_1_1; iterable_1_1 = yield __await(iterable_1.next()), _a = iterable_1_1.done, !_a; _e = true) {
105 _c = iterable_1_1.value;
106 _e = false;
107 const chunk = _c;
108 buffer.append(chunk);
109 const bytes = buffer.bytes();
110 let offset = 0;
111 for (;;) {
112 const size = sizeDelimitedPeek(bytes.subarray(offset));
113 if (size.eof) {
114 // size is incomplete, buffer more data
115 break;
116 }
117 if (size.size > readMaxBytes) {
118 throw new Error(`message size ${size.size} is larger than configured readMaxBytes ${readMaxBytes}`);
119 }
120 const messageStart = offset + size.offset;
121 const messageEnd = messageStart + size.size;
122 if (messageEnd > bytes.byteLength) {
123 // message is incomplete, buffer more data
124 break;
125 }
126 yield yield __await((0, from_binary_js_1.fromBinary)(messageDesc, bytes.subarray(messageStart, messageEnd), options));
127 offset = messageEnd;
128 }
129 if (offset > 0) {
130 buffer = new ByteBuffer();
131 buffer.append(bytes.subarray(offset));
132 }
133 }
134 }
135 catch (e_1_1) { e_1 = { error: e_1_1 }; }
136 finally {
137 try {
138 if (!_e && !_a && (_b = iterable_1.return)) yield __await(_b.call(iterable_1));
139 }
140 finally { if (e_1) throw e_1.error; }
141 }
142 if (buffer.byteLength > 0) {
143 throw new Error("incomplete data");
144 }
145 });
146 }
147 /**
148 * Decodes the size from the given size-delimited message, which may be
149 * incomplete.
150 *
151 * Returns an object with the following properties:
152 * - size: The size of the delimited message in bytes
153 * - offset: The offset in the given byte array where the message starts
154 * - eof: true
155 *
156 * If the size-delimited data does not include all bytes of the varint size,
157 * the following object is returned:
158 * - size: null
159 * - offset: null
160 * - eof: false
161 *
162 * This function can be used to implement parsing of size-delimited messages
163 * from a stream.
164 */
165 function sizeDelimitedPeek(data) {
166 const sizeEof = { eof: true, size: null, offset: null };
167 for (let i = 0; i < 10; i++) {
168 if (i > data.byteLength) {
169 return sizeEof;
170 }
171 if ((data[i] & 0x80) == 0) {
172 const reader = new binary_encoding_js_1.BinaryReader(data);
173 let size;
174 try {
175 size = reader.uint32();
176 }
177 catch (e) {
178 if (e instanceof RangeError) {
179 return sizeEof;
180 }
181 throw e;
182 }
183 return {
184 eof: false,
185 size,
186 offset: reader.pos,
187 };
188 }
189 }
190 throw new Error("invalid varint");
191 }