/
util.ts
351 lines (335 loc) · 9.91 KB
/
util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import { Buffer } from "./buffer.ts";
import { copy as copyBytes } from "../bytes/mod.ts";
import { assert } from "../testing/asserts.ts";
const DEFAULT_BUFFER_SIZE = 32 * 1024;
/** Read Reader `r` until EOF (`null`) and resolve to the content as
* Uint8Array`.
*
* ```ts
* import { readAll } from "./util.ts";
* import { Buffer } from "./buffer.ts";
*
* // Example from stdin
* const stdinContent = await readAll(Deno.stdin);
*
* // Example from file
* const file = await Deno.open("my_file.txt", {read: true});
* const myFileContent = await readAll(file);
* Deno.close(file.rid);
*
* // Example from buffer
* const myData = new Uint8Array(100);
* // ... fill myData array with data
* const reader = new Buffer(myData.buffer);
* const bufferContent = await readAll(reader);
* ```
*/
export async function readAll(r: Deno.Reader): Promise<Uint8Array> {
const buf = new Buffer();
await buf.readFrom(r);
return buf.bytes();
}
/** Synchronously reads Reader `r` until EOF (`null`) and returns the content
* as `Uint8Array`.
*
* ```ts
* import { readAllSync } from "./util.ts";
* import { Buffer } from "./buffer.ts";
*
* // Example from stdin
* const stdinContent = readAllSync(Deno.stdin);
*
* // Example from file
* const file = Deno.openSync("my_file.txt", {read: true});
* const myFileContent = readAllSync(file);
* Deno.close(file.rid);
*
* // Example from buffer
* const myData = new Uint8Array(100);
* // ... fill myData array with data
* const reader = new Buffer(myData.buffer);
* const bufferContent = readAllSync(reader);
* ```
*/
export function readAllSync(r: Deno.ReaderSync): Uint8Array {
const buf = new Buffer();
buf.readFromSync(r);
return buf.bytes();
}
export interface ByteRange {
/** The 0 based index of the start byte for a range. */
start: number;
/** The 0 based index of the end byte for a range, which is inclusive. */
end: number;
}
/**
* 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 "../testing/asserts.ts";
* import { readRange } from "./util.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: Deno.Reader & Deno.Seeker,
range: ByteRange,
): Promise<Uint8Array> {
// 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, 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 "../testing/asserts.ts";
* import { readRangeSync } from "./util.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: Deno.ReaderSync & Deno.SeekerSync,
range: ByteRange,
): Uint8Array {
// 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, 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;
}
/** Write all the content of the array buffer (`arr`) to the writer (`w`).
*
* ```ts
* import { Buffer } from "./buffer.ts";
* import { writeAll } from "./util.ts";
* // Example writing to stdout
* let contentBytes = new TextEncoder().encode("Hello World");
* await writeAll(Deno.stdout, contentBytes);
*
* // Example writing to file
* contentBytes = new TextEncoder().encode("Hello World");
* const file = await Deno.open('test.file', {write: true});
* await writeAll(file, contentBytes);
* Deno.close(file.rid);
*
* // Example writing to buffer
* contentBytes = new TextEncoder().encode("Hello World");
* const writer = new Buffer();
* await writeAll(writer, contentBytes);
* console.log(writer.bytes().length); // 11
* ```
*/
export async function writeAll(w: Deno.Writer, arr: Uint8Array) {
let nwritten = 0;
while (nwritten < arr.length) {
nwritten += await w.write(arr.subarray(nwritten));
}
}
/** Synchronously write all the content of the array buffer (`arr`) to the
* writer (`w`).
*
* ```ts
* import { Buffer } from "./buffer.ts";
* import { writeAllSync } from "./util.ts";
*
* // Example writing to stdout
* let contentBytes = new TextEncoder().encode("Hello World");
* writeAllSync(Deno.stdout, contentBytes);
*
* // Example writing to file
* contentBytes = new TextEncoder().encode("Hello World");
* const file = Deno.openSync('test.file', {write: true});
* writeAllSync(file, contentBytes);
* Deno.close(file.rid);
*
* // Example writing to buffer
* contentBytes = new TextEncoder().encode("Hello World");
* const writer = new Buffer();
* writeAllSync(writer, contentBytes);
* console.log(writer.bytes().length); // 11
* ```
*/
export function writeAllSync(w: Deno.WriterSync, arr: Uint8Array): void {
let nwritten = 0;
while (nwritten < arr.length) {
nwritten += w.writeSync(arr.subarray(nwritten));
}
}
/** Turns a Reader, `r`, into an async iterator.
*
* ```ts
* import { iter } from "./util.ts";
*
* let f = await Deno.open("/etc/passwd");
* for await (const chunk of iter(f)) {
* console.log(chunk);
* }
* f.close();
* ```
*
* Second argument can be used to tune size of a buffer.
* Default size of the buffer is 32kB.
*
* ```ts
* import { iter } from "./util.ts";
*
* let f = await Deno.open("/etc/passwd");
* const it = iter(f, {
* bufSize: 1024 * 1024
* });
* for await (const chunk of it) {
* console.log(chunk);
* }
* f.close();
* ```
*
* Iterator uses an internal buffer of fixed size for efficiency; it returns
* a view on that buffer on each iteration. It is therefore caller's
* responsibility to copy contents of the buffer if needed; otherwise the
* next iteration will overwrite contents of previously returned chunk.
*/
export async function* iter(
r: Deno.Reader,
options?: {
bufSize?: number;
},
): AsyncIterableIterator<Uint8Array> {
const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE;
const b = new Uint8Array(bufSize);
while (true) {
const result = await r.read(b);
if (result === null) {
break;
}
yield b.subarray(0, result);
}
}
/** Turns a ReaderSync, `r`, into an iterator.
*
* ```ts
* import { iterSync } from "./util.ts";
*
* let f = Deno.openSync("/etc/passwd");
* for (const chunk of iterSync(f)) {
* console.log(chunk);
* }
* f.close();
* ```
*
* Second argument can be used to tune size of a buffer.
* Default size of the buffer is 32kB.
*
* ```ts
* import { iterSync } from "./util.ts";
* let f = await Deno.open("/etc/passwd");
* const iter = iterSync(f, {
* bufSize: 1024 * 1024
* });
* for (const chunk of iter) {
* console.log(chunk);
* }
* f.close();
* ```
*
* Iterator uses an internal buffer of fixed size for efficiency; it returns
* a view on that buffer on each iteration. It is therefore caller's
* responsibility to copy contents of the buffer if needed; otherwise the
* next iteration will overwrite contents of previously returned chunk.
*/
export function* iterSync(
r: Deno.ReaderSync,
options?: {
bufSize?: number;
},
): IterableIterator<Uint8Array> {
const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE;
const b = new Uint8Array(bufSize);
while (true) {
const result = r.readSync(b);
if (result === null) {
break;
}
yield b.subarray(0, result);
}
}
/** Copies from `src` to `dst` until either EOF (`null`) is read from `src` or
* an error occurs. It resolves to the number of bytes copied or rejects with
* the first error encountered while copying.
*
* ```ts
* import { copy } from "./util.ts";
*
* const source = await Deno.open("my_file.txt");
* const bytesCopied1 = await copy(source, Deno.stdout);
* const destination = await Deno.create("my_file_2.txt");
* const bytesCopied2 = await copy(source, destination);
* ```
*
* @param src The source to copy from
* @param dst The destination to copy to
* @param options Can be used to tune size of the buffer. Default size is 32kB
*/
export async function copy(
src: Deno.Reader,
dst: Deno.Writer,
options?: {
bufSize?: number;
},
): Promise<number> {
let n = 0;
const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE;
const b = new Uint8Array(bufSize);
let gotEOF = false;
while (gotEOF === false) {
const result = await src.read(b);
if (result === null) {
gotEOF = true;
} else {
let nwritten = 0;
while (nwritten < result) {
nwritten += await dst.write(b.subarray(nwritten, result));
}
n += nwritten;
}
}
return n;
}