Skip to content

Commit

Permalink
Add RBS example
Browse files Browse the repository at this point in the history
  • Loading branch information
domenic committed Mar 3, 2016
1 parent 985e513 commit b271363
Showing 1 changed file with 31 additions and 5 deletions.
36 changes: 31 additions & 5 deletions index.bs
Expand Up @@ -287,12 +287,38 @@ copies.
on streams, beyond the provided ones of <a>piping</a> and <a lt="tee a readable stream">teeing</a>.
</div>

<h3 id="rs-with-byte-source-intro">Using Readable Streams with Byte Source</h3>
<div class="example">
The above example showed using the readable stream's <a>default reader</a>. If the stream is a <a>readable byte
stream</a>, you can also acquire a <a>BYOB reader</a> 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:

<div class="note">
A readable stream may be able to provide a <code>ReadableStreamBYOBReader</code>. It has almost the same methods as
the <code>ReadableStreamDefaultReader</code>, and can be
read in the same manner as the <code>ReadableStreamDefaultReader</code>.
<pre><code class="lang-javascript">
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);
});
}
</code></pre>

An important thing to note here is that the final <code>buffer</code> value is different from the
<code>originalAB</code>, but it (and all intermediate buffers) share the same backing memory allocation. At each step,
the buffer is transferred <!-- TODO link --> to a new <code>ArrayBuffer</code> object. The <code>newView</code> is a
new <code>Uint8Array</code>, with that <code>ArrayBuffer</code> object as its <code>buffer</code> property, the offset
that bytes were written to as its <code>byteOffset</code> property, and the number of bytes that were written as its
<code>byteLength</code> property.
</div>

<h3 id="rs-class">Class <code>ReadableStream</code></h3>
Expand Down

1 comment on commit b271363

@tyoshino
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

committed a fix for some typos.

Please sign in to comment.