Skip to content

Commit 5bcc6d2

Browse files
authored
README: Improve frozen netstring example (#8)
1 parent 518e86a commit 5bcc6d2

File tree

1 file changed

+25
-20
lines changed

1 file changed

+25
-20
lines changed

README.md

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -57,26 +57,31 @@ The ArrayBuffer `slice` method and TypedArray methods that create new ArrayBuffe
5757
### Represent arbitrary binary data as an immutable [netstring](https://en.wikipedia.org/wiki/Netstring)
5858

5959
```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);
60+
const consumeIntoNetstring = data => {
61+
// Transfer to a new ArrayBuffer with room for the netstring framing.
62+
// https://en.wikipedia.org/wiki/Netstring
63+
const prefix = new TextEncoder().encode(`${data.length}:`);
64+
const buf = data.buffer.transfer(prefix.length + data.length + 1);
65+
66+
// Frame the data.
67+
const tmpArr = new Uint8Array(buf);
68+
tmpArr.copyWithin(prefix.length, 0);
69+
tmpArr.set(prefix);
70+
tmpArr[tmpArr.length - 1] = 0x2C;
71+
72+
// Transfer to an immutable ArrayBuffer backing a frozen Uint8Array.
73+
const frozenNetstring = Object.freeze(new Uint8Array(buf.transferToImmutable()));
74+
assert(buf.detached);
75+
return frozenNetstring;
76+
};
77+
78+
const input = new TextEncoder().encode('hello world!');
79+
const result = consumeIntoNetstring(input);
80+
assert(Object.isFrozen(result));
81+
try { result[0] = 0; } catch (_err) {}
82+
try { new Uint8Array(result.buffer)[0] = 1; } catch (_err) {}
83+
try { result.buffer.transferToImmutable(); } catch (_err) {}
84+
assert(String.fromCharCode(...result) === '12:hello world!,');
8085
```
8186

8287
## Implementations

0 commit comments

Comments
 (0)