node-opcua-binary-stream 2.176.0 → 2.180.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -26,34 +26,45 @@ class BinaryStreamSizeCalculator {
26
26
  rewind() {
27
27
  this.length = 0;
28
28
  }
29
- writeInt8(value) {
29
+ writeInt8(_value) {
30
30
  this.length += 1;
31
31
  }
32
- writeUInt8(value) {
32
+ writeUInt8(_value) {
33
33
  this.length += 1;
34
34
  }
35
- writeInt16(value) {
35
+ writeInt16(_value) {
36
36
  this.length += 2;
37
37
  }
38
- writeInteger(value) {
38
+ writeInteger(_value) {
39
39
  this.length += 4;
40
40
  }
41
- writeUInt32(value) {
41
+ writeUInt32(_value) {
42
42
  this.length += 4;
43
43
  }
44
- writeUInt16(value) {
44
+ writeUInt16(_value) {
45
45
  this.length += 2;
46
46
  }
47
- writeFloat(value) {
47
+ writeFloat(_value) {
48
48
  this.length += 4;
49
49
  }
50
- writeDouble(value) {
50
+ writeDouble(_value) {
51
51
  this.length += 8;
52
52
  }
53
- writeArrayBuffer(arrayBuf, offset, byteLength) {
54
- offset = offset || 0;
53
+ /**
54
+ * counterpart of BinaryStream.reserveUInt32: only the 4 reserved bytes matter here.
55
+ * The returned position is meaningless for a calculator - patchUInt32 ignores it.
56
+ */
57
+ reserveUInt32() {
58
+ this.length += 4;
59
+ return -1;
60
+ }
61
+ patchUInt32(_position, _value) {
62
+ /* nothing to patch: a size calculator only accumulates a byte count */
63
+ }
64
+ writeArrayBuffer(arrayBuf, offset = 0, byteLength) {
55
65
  (0, node_opcua_assert_1.assert)(arrayBuf instanceof ArrayBuffer);
56
- this.length += byteLength || arrayBuf.byteLength;
66
+ // must resolve (offset, byteLength) exactly as BinaryStream.writeArrayBuffer does
67
+ this.length += (0, binaryStream_1.clampArrayBufferLength)(arrayBuf.byteLength, offset, byteLength);
57
68
  }
58
69
  writeByteStream(buf) {
59
70
  if (!buf) {
@@ -1 +1 @@
1
- {"version":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C;QAC3C,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;QAC5B,IAAI,CAAC,MAAM,IAAI,SAAS,CAAC;IAC7B,CAAC;CACJ;AAhFD,gEAgFC"}
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * @module node-opcua-binary-stream
3
3
  */
4
- import { BinaryStream } from "./binaryStream";
5
- import { BinaryStreamSizeCalculator } from "./binaryStreamSizeCalculator";
4
+ import type { BinaryStream } from "./binaryStream";
5
+ import type { BinaryStreamSizeCalculator } from "./binaryStreamSizeCalculator";
6
6
  export type OutputBinaryStream = BinaryStream | BinaryStreamSizeCalculator;
7
7
  export * from "./binaryStream";
8
8
  export * from "./binaryStreamSizeCalculator";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-opcua-binary-stream",
3
- "version": "2.176.0",
3
+ "version": "2.180.0",
4
4
  "description": "pure nodejs OPCUA SDK - module binary-stream",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -8,14 +8,14 @@
8
8
  "build": "tsc -b",
9
9
  "test": "mocha",
10
10
  "clean": "npx rimraf -g node_modules dist *.tsbuildinfo",
11
- "lint": "eslint source/**/*.ts"
11
+ "lint": "biome check --no-errors-on-unmatched ."
12
12
  },
13
13
  "dependencies": {
14
- "node-opcua-assert": "2.175.6",
15
- "node-opcua-buffer-utils": "2.176.0"
14
+ "node-opcua-assert": "2.179.0",
15
+ "node-opcua-buffer-utils": "2.179.0"
16
16
  },
17
17
  "devDependencies": {
18
- "node-opcua-benchmarker": "2.176.0"
18
+ "node-opcua-benchmarker": "2.179.0"
19
19
  },
20
20
  "author": "Etienne Rossignon",
21
21
  "license": "MIT",
@@ -32,7 +32,7 @@
32
32
  "internet of things"
33
33
  ],
34
34
  "homepage": "http://node-opcua.github.io/",
35
- "gitHead": "a4569830a5a564a7ff3e8cf37c44fd35b3f72ac1",
35
+ "gitHead": "11ad1e0894355cd279e19443c6c9a4fc090e7d7a",
36
36
  "files": [
37
37
  "dist",
38
38
  "source"
@@ -1,14 +1,56 @@
1
1
  /**
2
2
  * @module node-opcua-binary-stream
3
3
  */
4
- import "util";
4
+ import "node:util";
5
5
 
6
6
  import { assert } from "node-opcua-assert";
7
- import { createFastUninitializedBuffer } from "node-opcua-buffer-utils";
8
7
 
9
8
  const MAXUINT32 = 4294967295; // 2**32 -1;
10
9
  const performCheck = false;
11
10
 
11
+ /**
12
+ * raised when a growable BinaryStream would have to exceed its declared maximum size.
13
+ *
14
+ * Distinct from every other encoding failure on purpose: a caller that sized the stream
15
+ * from a negotiated limit needs to tell "the peer's message is too big" apart from
16
+ * "the encoder is broken".
17
+ */
18
+ export class BinaryStreamMaxSizeExceededError extends Error {
19
+ constructor(message: string) {
20
+ super(message);
21
+ this.name = "BinaryStreamMaxSizeExceededError";
22
+ }
23
+ }
24
+
25
+ /**
26
+ * raised when a decoder descends past BinaryStream.maxNestingLevel while reading a
27
+ * recursive type (ExtensionObject, Variant, DiagnosticInfo).
28
+ *
29
+ * Distinct from a size error on purpose: a message can be well within its size limit yet
30
+ * still nest deeply enough to exhaust the call stack, so a caller needs to tell "the peer
31
+ * nested too deep" apart from "the message is too big".
32
+ */
33
+ export class BinaryStreamMaxNestingLevelExceededError extends Error {
34
+ constructor(message: string) {
35
+ super(message);
36
+ this.name = "BinaryStreamMaxNestingLevelExceededError";
37
+ }
38
+ }
39
+
40
+ /**
41
+ * raised when a wire array length is refused before any element is decoded - it exceeds
42
+ * either BinaryStream.maxArrayLength or the number of bytes left to read.
43
+ *
44
+ * Named distinctly so a caller can map it to Bad_EncodingLimitsExceeded (Part 4 §5.3)
45
+ * rather than mistaking it for a genuine parse error.
46
+ */
47
+ export class BinaryStreamArrayLengthExceededError extends Error {
48
+ constructor(message: string) {
49
+ super(message);
50
+ this.name = "BinaryStreamArrayLengthExceededError";
51
+ }
52
+ }
53
+
12
54
  /**
13
55
  * a BinaryStream can be use to perform sequential read or write
14
56
  * inside a buffer.
@@ -35,6 +77,36 @@ const performCheck = false;
35
77
  export class BinaryStream {
36
78
  public static maxByteStringLength = 16 * 1024 * 1024;
37
79
  public static maxStringLength = 16 * 1024 * 1024;
80
+ /**
81
+ * how deep decoders may nest recursive types (ExtensionObject, Variant,
82
+ * DiagnosticInfo) while reading from this stream.
83
+ *
84
+ * These types can nest without ever making the message larger than the negotiated
85
+ * limit, so a message well under the size cap can still drive the decoder deep enough
86
+ * to exhaust the call stack. OPC UA Part 6 §5.1.8/§5.1.9 anticipates this and requires
87
+ * a decoder to support at least 100 levels and to report an error beyond what it
88
+ * supports; §5.2.2.12 says the same for the self-recursive DiagnosticInfo. One shared
89
+ * budget across the three types bounds what actually matters - total stack depth -
90
+ * regardless of how a message mixes them.
91
+ *
92
+ * Set to 128, comfortably above the 100 the spec requires us to support (so a message
93
+ * that legitimately nests 100 deep still decodes whichever way you count the outermost
94
+ * level) and far below the depth at which the call stack would actually overflow.
95
+ */
96
+ public static maxNestingLevel = 128;
97
+
98
+ /**
99
+ * hard ceiling on the number of elements a single array length prefix may declare.
100
+ *
101
+ * The length is read straight off the wire as a UInt32, so without a ceiling a tiny
102
+ * message can declare billions of elements and drive the decoder to loop and allocate
103
+ * to match. Mirrors the cap the Variant value path has always enforced
104
+ * (Variant.maxArrayLength); the generic path that decodes every structured-type array
105
+ * field never had one. Adjustable so a deployment that legitimately exchanges larger
106
+ * arrays can raise it.
107
+ */
108
+ public static maxArrayLength = 1 * 1024 * 1024;
109
+
38
110
  /**
39
111
  * the current position inside the buffer
40
112
  */
@@ -45,11 +117,124 @@ export class BinaryStream {
45
117
  */
46
118
  public buffer: Buffer;
47
119
 
120
+ /**
121
+ * 0 means "fixed size": the buffer is never reallocated and an overflowing write
122
+ * fails the same way it always has. A non-zero value turns the stream growable and
123
+ * caps how far it may grow. Kept as a single field so a fixed stream - the
124
+ * overwhelming majority - pays exactly one compare per write.
125
+ */
126
+ #maxLength = 0;
127
+
128
+ /**
129
+ * current recursive-decode depth. Bumped by enterNestingLevel/exitNestingLevel as a
130
+ * decoder descends into nested ExtensionObject/Variant/DiagnosticInfo values.
131
+ */
132
+ #nestingLevel = 0;
133
+
134
+ /**
135
+ * signal that the decoder is about to descend one level into a recursive type.
136
+ * Throws BinaryStreamMaxNestingLevelExceededError once the depth passes
137
+ * BinaryStream.maxNestingLevel, before the recursive call is made and before any
138
+ * further stack frame is consumed. Every successful call must be paired with
139
+ * exitNestingLevel, which is why callers use try/finally.
140
+ */
141
+ public enterNestingLevel(): void {
142
+ // Check before incrementing: a refused entry must leave the depth untouched.
143
+ // Callers put enterNestingLevel() outside their try/finally, so a throw here is
144
+ // never paired with an exitNestingLevel - incrementing first would leak a level
145
+ // every time the guard trips (e.g. when decodeExtensionObject swallows the throw)
146
+ // and slowly starve the budget for the rest of the message.
147
+ if (this.#nestingLevel >= BinaryStream.maxNestingLevel) {
148
+ throw new BinaryStreamMaxNestingLevelExceededError(
149
+ `BinaryStream: maximum nesting level of ${BinaryStream.maxNestingLevel} exceeded while decoding a recursive type`
150
+ );
151
+ }
152
+ this.#nestingLevel++;
153
+ }
154
+
155
+ /**
156
+ * mark that the decoder has finished one level of a recursive type. Pair with a
157
+ * preceding successful enterNestingLevel via try/finally so the depth is restored
158
+ * even when the nested decode throws.
159
+ */
160
+ public exitNestingLevel(): void {
161
+ this.#nestingLevel--;
162
+ }
163
+
164
+ /**
165
+ * validate a wire array length before a decoder loops over it.
166
+ *
167
+ * Two independent bounds:
168
+ * - it may not exceed BinaryStream.maxArrayLength;
169
+ * - it may not exceed the bytes left in the stream, since every encoded element
170
+ * occupies at least one byte. This tight check alone rejects an implausible length
171
+ * (0x7FFFFFFE elements behind a 100-byte body) immediately, and also catches a
172
+ * length that sits under the ceiling yet is still far larger than the remaining
173
+ * payload can back.
174
+ *
175
+ * @param length the element count just read from the stream
176
+ */
177
+ public checkArrayLength(length: number): void {
178
+ if (length > BinaryStream.maxArrayLength) {
179
+ throw new BinaryStreamArrayLengthExceededError(
180
+ `BinaryStream: array length ${length} exceeds the maximum allowed length of ${BinaryStream.maxArrayLength}`
181
+ );
182
+ }
183
+ const remaining = this.buffer.length - this.length;
184
+ if (length > remaining) {
185
+ throw new BinaryStreamArrayLengthExceededError(
186
+ `BinaryStream: array length ${length} exceeds the ${remaining} bytes remaining in the stream`
187
+ );
188
+ }
189
+ }
190
+
191
+ /**
192
+ * create a stream that reallocates its buffer as needed, up to maxLength bytes.
193
+ *
194
+ * Encoding a message whose size is not known up front otherwise means encoding it
195
+ * twice: once into a BinaryStreamSizeCalculator to learn the length, then again for
196
+ * real. Both passes walk the whole object graph, and measuring shows the sizing pass
197
+ * costs about as much as the real one.
198
+ *
199
+ * @param initialSize starting capacity; a good guess avoids reallocation entirely
200
+ * @param maxLength hard ceiling - exceeding it throws BinaryStreamMaxSizeExceededError
201
+ */
202
+ public static createGrowable(initialSize: number, maxLength: number): BinaryStream {
203
+ const stream = new BinaryStream(Math.max(1, initialSize));
204
+ stream.#maxLength = maxLength;
205
+ return stream;
206
+ }
207
+
208
+ #ensure(n: number): void {
209
+ if (this.#maxLength !== 0 && this.length + n > this.buffer.length) {
210
+ this.#grow(n);
211
+ }
212
+ }
213
+
214
+ #grow(n: number): void {
215
+ const needed = this.length + n;
216
+ if (needed > this.#maxLength) {
217
+ throw new BinaryStreamMaxSizeExceededError(
218
+ `BinaryStream: cannot grow to ${needed} bytes, the maximum allowed size is ${this.#maxLength}`
219
+ );
220
+ }
221
+ let newSize = this.buffer.length * 2;
222
+ while (newSize < needed) {
223
+ newSize *= 2;
224
+ }
225
+ if (newSize > this.#maxLength) {
226
+ newSize = this.#maxLength;
227
+ }
228
+ const bigger = Buffer.allocUnsafe(newSize);
229
+ this.buffer.copy(bigger, 0, 0, this.length);
230
+ this.buffer = bigger;
231
+ }
232
+
48
233
  constructor(data: undefined | Buffer | number) {
49
234
  if (data === undefined) {
50
- this.buffer = createFastUninitializedBuffer(1024);
235
+ this.buffer = Buffer.allocUnsafe(1024);
51
236
  } else if (typeof data === "number") {
52
- this.buffer = createFastUninitializedBuffer(data);
237
+ this.buffer = Buffer.allocUnsafe(data);
53
238
  } else {
54
239
  assert(data instanceof Buffer);
55
240
  this.buffer = data;
@@ -71,6 +256,7 @@ export class BinaryStream {
71
256
  * @param value the value to write
72
257
  */
73
258
  public writeInt8(value: number): void {
259
+ this.#ensure(1);
74
260
  // c8 ignore next
75
261
  if (performCheck) {
76
262
  assert(this.buffer.length >= this.length + 1, "not enough space in buffer");
@@ -85,6 +271,7 @@ export class BinaryStream {
85
271
  * @param value the value to write
86
272
  */
87
273
  public writeUInt8(value: number): void {
274
+ this.#ensure(1);
88
275
  // c8 ignore next
89
276
  if (performCheck) {
90
277
  assert(this.buffer.length >= this.length + 1, "not enough space in buffer");
@@ -99,6 +286,7 @@ export class BinaryStream {
99
286
  * @param value the value to write
100
287
  */
101
288
  public writeInt16(value: number): void {
289
+ this.#ensure(2);
102
290
  // c8 ignore next
103
291
  if (performCheck) {
104
292
  assert(this.buffer.length >= this.length + 2, "not enough space in buffer");
@@ -112,6 +300,7 @@ export class BinaryStream {
112
300
  * @param value the value to write
113
301
  */
114
302
  public writeUInt16(value: number): void {
303
+ this.#ensure(2);
115
304
  // c8 ignore next
116
305
  if (performCheck) {
117
306
  assert(this.buffer.length >= this.length + 2, "not enough space in buffer");
@@ -125,6 +314,7 @@ export class BinaryStream {
125
314
  * @param value the value to write
126
315
  */
127
316
  public writeInteger(value: number): void {
317
+ this.#ensure(4);
128
318
  // c8 ignore next
129
319
  if (performCheck) {
130
320
  assert(this.buffer.length >= this.length + 4, "not enough space in buffer");
@@ -139,10 +329,11 @@ export class BinaryStream {
139
329
  * @param value the value to write
140
330
  */
141
331
  public writeUInt32(value: number): void {
332
+ this.#ensure(4);
142
333
  // c8 ignore next
143
334
  if (performCheck) {
144
335
  assert(this.buffer.length >= this.length + 4, "not enough space in buffer");
145
- assert(isFinite(value));
336
+ assert(Number.isFinite(value));
146
337
  assert(value >= 0 && value <= MAXUINT32);
147
338
  }
148
339
  this.buffer.writeUInt32LE(value, this.length);
@@ -160,6 +351,7 @@ export class BinaryStream {
160
351
  * @param value the value to write
161
352
  */
162
353
  public writeFloat(value: number): void {
354
+ this.#ensure(4);
163
355
  // c8 ignore next
164
356
  if (performCheck) {
165
357
  assert(this.buffer.length >= this.length + 4, "not enough space in buffer");
@@ -173,6 +365,7 @@ export class BinaryStream {
173
365
  * @param value the value to write
174
366
  */
175
367
  public writeDouble(value: number): void {
368
+ this.#ensure(8);
176
369
  // c8 ignore next
177
370
  if (performCheck) {
178
371
  assert(this.buffer.length >= this.length + 8, "not enough space in buffer");
@@ -181,21 +374,66 @@ export class BinaryStream {
181
374
  this.length += 8;
182
375
  }
183
376
 
377
+ /**
378
+ * reserve room for a 32 bit unsigned integer whose value is not known yet,
379
+ * and return the position at which it can later be written with patchUInt32.
380
+ *
381
+ * This lets a length-prefixed body be written in a single pass: reserve the slot,
382
+ * encode the body, then patch in the byte count. The alternative - computing the
383
+ * size up front - means encoding the body twice, which compounds for nested
384
+ * structures.
385
+ */
386
+ public reserveUInt32(): number {
387
+ this.#ensure(4);
388
+ const position = this.length;
389
+ this.length += 4;
390
+ return position;
391
+ }
392
+
393
+ /**
394
+ * write a 32 bit unsigned integer at an absolute position previously returned by
395
+ * reserveUInt32, without moving the cursor.
396
+ */
397
+ public patchUInt32(position: number, value: number): void {
398
+ this.buffer.writeUInt32LE(value, position);
399
+ }
400
+
184
401
  /**
185
402
  * @param arrayBuf a buffer or byte array write
186
403
  * @param offset the offset position (default =0)
187
404
  * @param length the number of byte to write
188
405
  */
189
- public writeArrayBuffer(arrayBuf: ArrayBuffer, offset = 0, length = 0): void {
406
+ public writeArrayBuffer(arrayBuf: ArrayBuffer, offset = 0, length?: number): void {
190
407
  // c8 ignore next
191
408
  if (performCheck) {
192
409
  assert(arrayBuf instanceof ArrayBuffer);
193
410
  }
411
+ // note: for a real ArrayBuffer this is a zero-copy view. It also preserves the
412
+ // legacy shape where a caller passes a TypedArray instead: that takes the
413
+ // array-like constructor path and truncates element-wise, which some tests rely on.
194
414
  const byteArr = new Uint8Array(arrayBuf);
195
- const n = (length || byteArr.length) + offset;
196
- for (let i = offset; i < n; i++) {
197
- this.buffer[this.length++] = byteArr[i];
415
+ // `length` must default to "the rest of the buffer", not to the *whole* buffer:
416
+ // the old `length || byteArr.length` turned an explicit 0 into a full copy, and
417
+ // ignored `offset` when length was omitted.
418
+ const len = clampArrayBufferLength(byteArr.length, offset, length);
419
+ if (len === 0) {
420
+ return;
198
421
  }
422
+ this.#ensure(len);
423
+ // make sure there is enough room in destination buffer
424
+ const remainingBytes = this.buffer.length - this.length;
425
+ /* c8 ignore next */
426
+ if (remainingBytes < len) {
427
+ throw new Error(
428
+ "BinaryStream.writeArrayBuffer error : not enough bytes left in buffer : requested is " +
429
+ len +
430
+ " but only " +
431
+ remainingBytes +
432
+ " left"
433
+ );
434
+ }
435
+ this.buffer.set(byteArr.subarray(offset, offset + len), this.length);
436
+ this.length += len;
199
437
  }
200
438
 
201
439
  // writeArrayBuffer(arrayBuf, offset, length) {
@@ -304,6 +542,7 @@ export class BinaryStream {
304
542
  }
305
543
  assert(buf instanceof Buffer);
306
544
  this.writeInteger(buf.length);
545
+ this.#ensure(buf.length);
307
546
  // make sure there is enough room in destination buffer
308
547
  const remainingBytes = this.buffer.length - this.length;
309
548
 
@@ -311,10 +550,10 @@ export class BinaryStream {
311
550
  if (remainingBytes < buf.length) {
312
551
  throw new Error(
313
552
  "BinaryStream.writeByteStream error : not enough bytes left in buffer : bufferLength is " +
314
- buf.length +
315
- " but only " +
316
- remainingBytes +
317
- " left"
553
+ buf.length +
554
+ " but only " +
555
+ remainingBytes +
556
+ " left"
318
557
  );
319
558
  }
320
559
  buf.copy(this.buffer, this.length, 0, buf.length);
@@ -331,16 +570,17 @@ export class BinaryStream {
331
570
  if (byteLength === 0) {
332
571
  return;
333
572
  }
573
+ this.#ensure(byteLength);
334
574
  // make sure there is enough room in destination buffer
335
575
  const remainingBytes = this.buffer.length - this.length;
336
576
  /* c8 ignore next */
337
577
  if (remainingBytes < byteLength) {
338
578
  throw new Error(
339
579
  "BinaryStream.writeByteStream error : not enough bytes left in buffer : bufferLength is " +
340
- byteLength +
341
- " but only " +
342
- remainingBytes +
343
- " left"
580
+ byteLength +
581
+ " but only " +
582
+ remainingBytes +
583
+ " left"
344
584
  );
345
585
  }
346
586
  this.buffer.write(value, this.length);
@@ -369,7 +609,9 @@ export class BinaryStream {
369
609
 
370
610
  public readArrayBuffer(length: number): Uint8Array {
371
611
  if (length > BinaryStream.maxByteStringLength) {
372
- throw new Error(`maxStringLength(${BinaryStream.maxByteStringLength}) has been exceeded in BinaryStream.readArrayBuffer len=${length}`);
612
+ throw new Error(
613
+ `maxStringLength(${BinaryStream.maxByteStringLength}) has been exceeded in BinaryStream.readArrayBuffer len=${length}`
614
+ );
373
615
  }
374
616
  // c8 ignore next
375
617
  if (performCheck) {
@@ -404,7 +646,9 @@ export class BinaryStream {
404
646
  return zeroLengthBuffer;
405
647
  }
406
648
  if (bufLen > BinaryStream.maxByteStringLength) {
407
- throw new Error(`maxStringLength(${BinaryStream.maxByteStringLength}) has been exceeded in BinaryStream.readArrayBuffer len=${bufLen}`);
649
+ throw new Error(
650
+ `maxStringLength(${BinaryStream.maxByteStringLength}) has been exceeded in BinaryStream.readArrayBuffer len=${bufLen}`
651
+ );
408
652
  }
409
653
  // check that there is enough space in the buffer
410
654
  const remainingBytes = this.buffer.length - this.length;
@@ -412,10 +656,10 @@ export class BinaryStream {
412
656
  if (remainingBytes < bufLen) {
413
657
  throw new Error(
414
658
  "BinaryStream.readByteStream error : not enough bytes left in buffer : bufferLength is " +
415
- bufLen +
416
- " but only " +
417
- remainingBytes +
418
- " left"
659
+ bufLen +
660
+ " but only " +
661
+ remainingBytes +
662
+ " left"
419
663
  );
420
664
  }
421
665
  // create a shared memory buffer ! for speed
@@ -433,7 +677,9 @@ export class BinaryStream {
433
677
  return "";
434
678
  }
435
679
  if (bufLen > BinaryStream.maxStringLength) {
436
- throw new Error(`maxStringLength(${BinaryStream.maxStringLength}) has been exceeded in BinaryStream.readString len=${bufLen}`);
680
+ throw new Error(
681
+ `maxStringLength(${BinaryStream.maxStringLength}) has been exceeded in BinaryStream.readString len=${bufLen}`
682
+ );
437
683
  }
438
684
  // check that there is enough space in the buffer
439
685
  const remainingBytes = this.buffer.length - this.length;
@@ -441,10 +687,10 @@ export class BinaryStream {
441
687
  if (remainingBytes < bufLen) {
442
688
  throw new Error(
443
689
  "BinaryStream.readByteStream error : not enough bytes left in buffer : bufferLength is " +
444
- bufLen +
445
- " but only " +
446
- remainingBytes +
447
- " left"
690
+ bufLen +
691
+ " but only " +
692
+ remainingBytes +
693
+ " left"
448
694
  );
449
695
  }
450
696
  const str = this.buffer.toString("utf-8", this.length, this.length + bufLen);
@@ -453,6 +699,36 @@ export class BinaryStream {
453
699
  }
454
700
  }
455
701
 
702
+ /**
703
+ * resolve the (offset, length) arguments of writeArrayBuffer into a byte count.
704
+ *
705
+ * Shared by BinaryStream and BinaryStreamSizeCalculator so the two can never
706
+ * disagree: MessageChunker sizes a message with the calculator, allocates
707
+ * exactly that many bytes, then encodes with the stream. Any divergence here
708
+ * shows up as malformed chunk framing, not as a wrong number.
709
+ *
710
+ * @internal
711
+ */
712
+ export function clampArrayBufferLength(byteLength: number, offset: number, length?: number): number {
713
+ // A negative offset would make `available` larger than the source, and
714
+ // TypedArray#subarray reads a negative start as an offset from the *end* - so the
715
+ // caller would advance the cursor by more bytes than were actually copied, leaving
716
+ // a window of untouched destination memory inside the stream. Reject it here, in
717
+ // the one place both the stream and the size calculator agree on.
718
+ if (!(offset >= 0)) {
719
+ throw new Error(`BinaryStream.writeArrayBuffer: offset must be a non-negative number, got ${offset}`);
720
+ }
721
+ const available = byteLength - offset;
722
+ if (available <= 0) {
723
+ return 0;
724
+ }
725
+ const requested = length === undefined ? available : length;
726
+ if (requested <= 0) {
727
+ return 0;
728
+ }
729
+ return requested < available ? requested : available;
730
+ }
731
+
456
732
  /**
457
733
  * @function calculateByteLength
458
734
  * calculate the size in bytes of a utf8 string
@@ -477,4 +753,4 @@ export function calculateByteLength(str: string): number {
477
753
  return s;
478
754
  }
479
755
 
480
- const zeroLengthBuffer = createFastUninitializedBuffer(0);
756
+ const zeroLengthBuffer = Buffer.allocUnsafe(0);