Skip to content

Commit 07410ef

Browse files
authored
README: Add frozen netstring example
1 parent 8eeea75 commit 07410ef

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,30 @@ An immutable buffer cannot be detached, resized, or further transferred. Its `ma
5252

5353
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).
5454

55+
## Use cases
56+
57+
### Represent arbitrary binary data as an immutable [netstring](https://en.wikipedia.org/wiki/Netstring)
58+
59+
```js
60+
// Read data from base64 input and calculate its length.
61+
const data = Uint8Array.fromBase64(inputBase64);
62+
const dataLen = data.length;
63+
const dataLenStr = String(dataLen);
64+
const digitCount = dataLenStr.length;
65+
// Transfer to a new ArrayBuffer with room for the netstring framing.
66+
const tmpBuf = data.buffer.transfer(digitCount + 1 + dataLen + 1);
67+
const tmpArr = new Uint8Array(tmpBuf);
68+
assert(tmpArr.buffer === tmpBuf);
69+
// Frame the data.
70+
tmpArr.copyWithin(digitCount + 1, 0);
71+
for (let i = 0; i < digitCount; i++) tmpArr[i] = dataLenStr.charCodeAt(i);
72+
tmpArr[digitCount] = 0x3A;
73+
tmpArr[tmpArr.length - 1] = 0x2C;
74+
// Transfer to an immutable ArrayBuffer backing a frozen Uint8Array.
75+
const netstringArr = Object.freeze(new Uint8Array(tmpBuf.transferToImmutable()));
76+
assert(tmpBuf.detached);
77+
```
78+
5579
## Implementations
5680

5781
### Polyfill/transpiler implementations

0 commit comments

Comments
 (0)