Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 20 additions & 29 deletions lib/fs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,42 +20,33 @@ const rangeToFSOpts = (range, size = Infinity) => {
return { length: end - start + 1, position: start };
};

const readRanges = async (url, ranges, size, fd) => {
try {
fd ??= await open(url);
const readRanges = async (url, ranges, size) => {
await using fd = await open(url);

return Promise.all(ranges.map(range => {
const { length, position } = rangeToFSOpts(range, size);
return Promise.all(ranges.map(range => {
const { length, position } = rangeToFSOpts(range, size);

return fd.read(new Uint8Array(length), {
length,
position,
}).then(({ buffer }) => buffer);
}));
} finally {
await fd?.close();
}
return fd.read(new Uint8Array(length), {
length,
position,
}).then(({ buffer }) => buffer);
}));
};

const writeRange = async (url, range, body, flag) => {
let { length, position } = rangeToFSOpts(range);

let fd;
try {
fd = await open(url, flag);
for await (const $ of body) {
const byteLength = Math.min($.byteLength ?? $.length, length);
await fd.write(...ArrayBuffer.isView($)
? [new Uint8Array($.buffer, $.byteOffset, byteLength),,, position]
: [`${$}`.slice(0, byteLength), position]
);

if (!(length -= byteLength))
return;
position += byteLength;
}
} finally {
await fd?.close();
await using fd = await open(url, flag);
for await (const $ of body) {
const byteLength = Math.min($.byteLength ?? $.length, length);
await fd.write(...ArrayBuffer.isView($)
? [new Uint8Array($.buffer, $.byteOffset, byteLength),,, position]
: [`${$}`.slice(0, byteLength), position]
);

if (!(length -= byteLength))
return;
position += byteLength;
}
};

Expand Down
Loading