From 07410ef387bcd23f5e07deb5abe0a96e6052b72f Mon Sep 17 00:00:00 2001 From: Richard Gibson Date: Sat, 5 Oct 2024 22:08:57 -0400 Subject: [PATCH] README: Add frozen netstring example --- README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.md b/README.md index bc73dd3..815ac3d 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,30 @@ An immutable buffer cannot be detached, resized, or further transferred. Its `ma The ArrayBuffer `slice` method and TypedArray methods that create new ArrayBuffers (`filter`, `map`, `slice`, `toReversed`, etc.) make no effort to preserve immutability, just like they make no effort to preserve resizability (although use of SpeciesConstructor in those methods means that _lack_ of resizability/immutability in the result cannot be guaranteed for the latter). +## Use cases + +### Represent arbitrary binary data as an immutable [netstring](https://en.wikipedia.org/wiki/Netstring) + +```js +// Read data from base64 input and calculate its length. +const data = Uint8Array.fromBase64(inputBase64); +const dataLen = data.length; +const dataLenStr = String(dataLen); +const digitCount = dataLenStr.length; +// Transfer to a new ArrayBuffer with room for the netstring framing. +const tmpBuf = data.buffer.transfer(digitCount + 1 + dataLen + 1); +const tmpArr = new Uint8Array(tmpBuf); +assert(tmpArr.buffer === tmpBuf); +// Frame the data. +tmpArr.copyWithin(digitCount + 1, 0); +for (let i = 0; i < digitCount; i++) tmpArr[i] = dataLenStr.charCodeAt(i); +tmpArr[digitCount] = 0x3A; +tmpArr[tmpArr.length - 1] = 0x2C; +// Transfer to an immutable ArrayBuffer backing a frozen Uint8Array. +const netstringArr = Object.freeze(new Uint8Array(tmpBuf.transferToImmutable())); +assert(tmpBuf.detached); +``` + ## Implementations ### Polyfill/transpiler implementations