Skip to content

Commit 518e86a

Browse files
authored
README: Add frozen netstring example (#7)
1 parent 8eeea75 commit 518e86a

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,33 @@ 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+
66+
// Transfer to a new ArrayBuffer with room for the netstring framing.
67+
const tmpBuf = data.buffer.transfer(digitCount + 1 + dataLen + 1);
68+
const tmpArr = new Uint8Array(tmpBuf);
69+
assert(tmpArr.buffer === tmpBuf);
70+
71+
// Frame the data.
72+
tmpArr.copyWithin(digitCount + 1, 0);
73+
for (let i = 0; i < digitCount; i++) tmpArr[i] = dataLenStr.charCodeAt(i);
74+
tmpArr[digitCount] = 0x3A;
75+
tmpArr[tmpArr.length - 1] = 0x2C;
76+
77+
// Transfer to an immutable ArrayBuffer backing a frozen Uint8Array.
78+
const netstringArr = Object.freeze(new Uint8Array(tmpBuf.transferToImmutable()));
79+
assert(tmpBuf.detached);
80+
```
81+
5582
## Implementations
5683

5784
### Polyfill/transpiler implementations

0 commit comments

Comments
 (0)