@@ -57,26 +57,31 @@ The ArrayBuffer `slice` method and TypedArray methods that create new ArrayBuffe
57
57
### Represent arbitrary binary data as an immutable [ netstring] ( https://en.wikipedia.org/wiki/Netstring )
58
58
59
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 );
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!,' );
80
85
```
81
86
82
87
## Implementations
0 commit comments