Skip to content

Commit

Permalink
Merge pull request #584 from nidhijaju/byob-example
Browse files Browse the repository at this point in the history
Add examples for reading with BYOB readers
  • Loading branch information
nidhijaju authored Jan 31, 2024
2 parents 3d22dbb + 69988a2 commit 363c152
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions index.bs
Original file line number Diff line number Diff line change
Expand Up @@ -2805,6 +2805,41 @@ async function receiveDatagrams(url) {
}
</pre>

## Receiving datagrams with a BYOB reader ## {#example-datagrams-byob}

*This section is non-normative.*

As {{WebTransport/datagrams}} are [=readable byte streams=], you can acquire a
[=BYOB reader=] for them, which allows more precise control over buffer allocation
in order to avoid copies. This example reads the datagram into a 64kB memory buffer.

<pre class="example" highlight="js">
const wt = new WebTransport(url);

for await (const datagram of wt.datagrams.readable) {
const reader = datagram.getReader({ mode: "byob" });

let array_buffer = new ArrayBuffer(65536);
const buffer = await readInto(array_buffer);
}

async function readInto(buffer) {
let offset = 0;

while (offset < buffer.byteLength) {
const {value: view, done} = await reader.read(
new Uint8Array(buffer, offset, buffer.byteLength - offset));
buffer = view.buffer;
if (done) {
break;
}
offset += view.byteLength;
}

return buffer;
}
</pre>

## Sending a stream ## {#example-sending-stream}

*This section is non-normative.*
Expand Down Expand Up @@ -2889,6 +2924,42 @@ async function receiveText(url, createWritableStreamForTextData) {
}
</pre>

## Receiving a stream with a BYOB reader ## {#example-stream-byob}

*This section is non-normative.*

As {{WebTransportReceiveStream}}s are [=readable byte streams=], you can acquire a
[=BYOB reader=] for them, which allows more precise control over buffer allocation
in order to avoid copies. This example reads the first 1024 bytes from a
{{WebTransportReceiveStream}} into a single memory buffer.

<pre class="example" highlight="js">
const wt = new WebTransport(url);

const reader = wt.incomingUnidirectionalStreams.getReader();
const { value: recv_stream, done } = await reader.read();
const byob_reader = recv_stream.getReader({ mode: "byob" });

let array_buffer = new ArrayBuffer(1024);
const buffer = await readInto(array_buffer);

async function readInto(buffer) {
let offset = 0;

while (offset < buffer.byteLength) {
const {value: view, done} = await reader.read(
new Uint8Array(buffer, offset, buffer.byteLength - offset));
buffer = view.buffer;
if (done) {
break;
}
offset += view.byteLength;
}

return buffer;
}
</pre>

## Sending a transactional chunk on a stream ## {#example-transactional-stream}

*This section is non-normative.*
Expand Down

0 comments on commit 363c152

Please sign in to comment.