Skip to content

Commit

Permalink
Make makeReadableByteFileStream example able to handle non BYOB case
Browse files Browse the repository at this point in the history
  • Loading branch information
tyoshino committed Mar 10, 2016
1 parent 390b8f4 commit da06f3d
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions index.bs
Expand Up @@ -3253,6 +3253,7 @@ size of 1024, it attempts to fill the developer-supplied buffer, allowing full c

<pre><code class="lang-javascript">
const fs = require("pr/fs"); // https://github.com/jden/pr
const CHUNK_SIZE = 1024;

function makeReadableByteFileStream(filename) {
let fd;
Expand All @@ -3268,16 +3269,31 @@ size of 1024, it attempts to fill the developer-supplied buffer, allowing full c
},

pull(controller) {
const v = controller.byobRequest.view;

return fs.read(fd, v, v.byteOffset, v.byteLength, position).then(bytesRead => {
if (bytesRead === 0) {
return fs.close(fd).then(() => controller.close());
} else {
position += bytesRead;
controller.byobRequest.respond(bytesRead);
}
});
const r = controller.byobRequest;

if (r) {
const v = r.view;

return fs.read(fd, v.buffer, v.byteOffset, v.byteLength, position).then(bytesRead => {
if (bytesRead === 0) {
return fs.close(fd).then(() => controller.close());
} else {
position += bytesRead;
controller.byobRequest.respond(bytesRead);
}
});
} else {
// The consumer is using the default reader.
const buffer = new ArrayBuffer(CHUNK_SIZE);
return fs.read(fd, buffer, 0, CHUNK_SIZE, position).then(bytesRead => {
if (bytesRead === 0) {
return fs.close(fd).then(() => controller.close());
} else {
position += bytesRead;
controller.enqueue(new Uint8Array(buffer, 0, bytesRead));
}
});
}
},

cancel() {
Expand Down

0 comments on commit da06f3d

Please sign in to comment.