esbuild-gas-plugin
Version:
esbuild plugin for Google Apps Script.
74 lines (73 loc) • 3.04 kB
JavaScript
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import * as dntShim from "../../../../_dnt.shims.js";
import { copy as copyBytes } from "../bytes/copy.js";
import { assert } from "../_util/asserts.js";
const DEFAULT_BUFFER_SIZE = 32 * 1024;
/**
* Read a range of bytes from a file or other resource that is readable and
* seekable. The range start and end are inclusive of the bytes within that
* range.
*
* ```ts
* import { assertEquals } from "https://deno.land/std@$STD_VERSION/testing/asserts.ts";
* import { readRange } from "https://deno.land/std@$STD_VERSION/io/read_range.ts";
*
* // Read the first 10 bytes of a file
* const file = await Deno.open("example.txt", { read: true });
* const bytes = await readRange(file, { start: 0, end: 9 });
* assertEquals(bytes.length, 10);
* ```
*/
export async function readRange(r, range) {
// byte ranges are inclusive, so we have to add one to the end
let length = range.end - range.start + 1;
assert(length > 0, "Invalid byte range was passed.");
await r.seek(range.start, dntShim.Deno.SeekMode.Start);
const result = new Uint8Array(length);
let off = 0;
while (length) {
const p = new Uint8Array(Math.min(length, DEFAULT_BUFFER_SIZE));
const nread = await r.read(p);
assert(nread !== null, "Unexpected EOF reach while reading a range.");
assert(nread > 0, "Unexpected read of 0 bytes while reading a range.");
copyBytes(p, result, off);
off += nread;
length -= nread;
assert(length >= 0, "Unexpected length remaining after reading range.");
}
return result;
}
/**
* Read a range of bytes synchronously from a file or other resource that is
* readable and seekable. The range start and end are inclusive of the bytes
* within that range.
*
* ```ts
* import { assertEquals } from "https://deno.land/std@$STD_VERSION/testing/asserts.ts";
* import { readRangeSync } from "https://deno.land/std@$STD_VERSION/io/read_range.ts";
*
* // Read the first 10 bytes of a file
* const file = Deno.openSync("example.txt", { read: true });
* const bytes = readRangeSync(file, { start: 0, end: 9 });
* assertEquals(bytes.length, 10);
* ```
*/
export function readRangeSync(r, range) {
// byte ranges are inclusive, so we have to add one to the end
let length = range.end - range.start + 1;
assert(length > 0, "Invalid byte range was passed.");
r.seekSync(range.start, dntShim.Deno.SeekMode.Start);
const result = new Uint8Array(length);
let off = 0;
while (length) {
const p = new Uint8Array(Math.min(length, DEFAULT_BUFFER_SIZE));
const nread = r.readSync(p);
assert(nread !== null, "Unexpected EOF reach while reading a range.");
assert(nread > 0, "Unexpected read of 0 bytes while reading a range.");
copyBytes(p, result, off);
off += nread;
length -= nread;
assert(length >= 0, "Unexpected length remaining after reading range.");
}
return result;
}