From b271363e790bc3590b0a3df5dcdae958084cf5ad Mon Sep 17 00:00:00 2001 From: Domenic Denicola Date: Thu, 3 Mar 2016 16:36:42 -0500 Subject: [PATCH] Add RBS example --- index.bs | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/index.bs b/index.bs index cd8cf5f96..90f091636 100644 --- a/index.bs +++ b/index.bs @@ -287,12 +287,38 @@ copies. on streams, beyond the provided ones of piping and teeing. -

Using Readable Streams with Byte Source

+
+ The above example showed using the readable stream's default reader. If the stream is a readable byte + stream, you can also acquire a BYOB reader for it, which allows more precise control over buffer + allocation in order to avoid copies. For example, this code reads the first 1024 bytes from the stream into a single + memory buffer: -
- A readable stream may be able to provide a ReadableStreamBYOBReader. It has almost the same methods as - the ReadableStreamDefaultReader, and can be - read in the same manner as the ReadableStreamDefaultReader. +

+    const reader = readableStream.getBYOBReader();
+
+    let startingAB = new ArrayBuffer(1024);
+    readInto(startingAB, 0)
+      .then(buffer => console.log("The first 1024 bytes:", buffer))
+      .catch(e => console.error("Something went wrong!", e));
+
+    function readInto(buffer, offset) {
+      if (offset === buffer.byteLength) {
+        return buffer;
+      }
+
+      const view = new Uint8Array(buffer, offset, buffer.byteLength - offset);
+      reader.read(view).then(newView => {
+        return readInto(newView.buffer, offset + newView.byteLength);
+      });
+    }
+  
+ + An important thing to note here is that the final buffer value is different from the + originalAB, but it (and all intermediate buffers) share the same backing memory allocation. At each step, + the buffer is transferred to a new ArrayBuffer object. The newView is a + new Uint8Array, with that ArrayBuffer object as its buffer property, the offset + that bytes were written to as its byteOffset property, and the number of bytes that were written as its + byteLength property.

Class ReadableStream