Recursive AI

Resize a JavaScript ArrayBuffer in C#

OneEcma is a free, open-source JavaScript interpreter for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Resize the byte buffer without rebuilding its views.

Terminal
dotnet add package RecursiveAI.OneEcma

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
  const b = new ArrayBuffer(4,
      { maxByteLength: 8 });
  const fixed = new Uint8Array(b, 0, 4);
  const tracked = new Uint8Array(b);
  b.resize(2);
  const small = [fixed.length, tracked.length];
  b.resize(6);
  [small, fixed.length, tracked.length].join();
  """).AsString);

Unzip the example, then dotnet run.

After shrinking, the fixed view has length 0 and the tracking view has length 2. After growing, the fixed view has length 4 and the tracking view has length 6.

Text
0,2,4,6

Full program

This version starts with four nonzero bytes. It prints both views before the resize, while the fixed-length view is out of bounds, and after that view becomes usable again.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
    const buffer = new ArrayBuffer(4, { maxByteLength: 8 });
    const fixed = new Uint8Array(buffer, 0, 4);
    const tracked = new Uint8Array(buffer);
    tracked.set([10, 20, 30, 40]);
    const snapshot = label =>
      `${label}: buffer=${buffer.byteLength}, fixed=${fixed.length}, ` +
      `tracked=${tracked.length}, fixed[0]=${fixed[0]}, bytes=${tracked.join()}`;
    const output = [snapshot("start")];
    buffer.resize(2);
    output.push(snapshot("shrink"));
    buffer.resize(6);
    output.push(snapshot("grow"));
    output.join("\n");
    """).AsString);

dotnet run prints:

Text
start: buffer=4, fixed=4, tracked=4, fixed[0]=10, bytes=10,20,30,40
shrink: buffer=2, fixed=0, tracked=2, fixed[0]=undefined, bytes=10,20
grow: buffer=6, fixed=4, tracked=6, fixed[0]=10, bytes=10,20,0,0,0,0

A request above maxByteLength, such as buffer.resize(9) here, throws RangeError in JavaScript (JsException in C# if you don’t catch it in script).

Variations

Track from a nonzero byte offset. This view starts at byte 2 and leaves the element count unspecified, so it covers the tail of the buffer.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
  const buffer = new ArrayBuffer(4, { maxByteLength: 8 });
  const tail = new Uint8Array(buffer, 2);
  const before = tail.length;
  buffer.resize(6);
  `${before} -> ${tail.length}`;
  """).AsString);
Text
2 -> 4

The short answer

Create new ArrayBuffer(initialSize, { maxByteLength }) and call resize(newSize), with sizes in bytes. A Uint8Array created without an explicit element count tracks the buffer size; one constructed with a count keeps that count when its whole range fits. After a shrink, a fixed-length view that no longer fits reports length zero. It isn’t detached: it can become usable again after the buffer grows.

How do you resize an ArrayBuffer in JavaScript?

Supply maxByteLength at construction to make the buffer resizable. resize() changes the existing buffer, so the views keep referring to it. It does not turn a fixed-length buffer into a resizable one. When you didn’t create the buffer, read its resizable property to tell the two cases apart.

Choose the maximum from the payload your program is prepared to handle. In the example the initial allocation is four bytes, the maximum is eight, and the buffer never exceeds six. The resize reference describes the upper bound and the zero-initialization of new bytes. OneEcma also charges buffer allocations to its memory budget, including allocations made during resizing. A declared maximum is not a guarantee that the engine can reach it within that budget.

What happens to a typed array when its buffer shrinks?

In the full program, the fixed view needs all four original bytes. At two bytes it doesn’t show a two-element prefix: its length is zero and fixed[0] is undefined. The tracking view still reads two bytes because it starts at byte 0 and has no explicit element count. OneEcma’s binary data notes say that it recomputes each view’s length and out-of-bounds status on access.

After growing to six bytes, the fixed view can see four elements again. Both views can see the retained prefix, 10,20, but the removed values 30,40 don’t come back. The new space contains zeros. Use a fixed view when a consumer needs an entire record or nothing; use a tracking view when it should see however many bytes are currently available from its start offset. With Uint8Array, one element is one byte. For wider typed arrays, don’t confuse the buffer’s byte length with the view’s element count.

All oneecma recipes