deno.land / std@0.224.0 / streams / byte_slice_stream.ts

byte_slice_stream.ts
View Documentation
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
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.// This module is browser compatible.
import { assert } from "../assert/assert.ts";
/** * A transform stream that only transforms from the zero-indexed `start` and * `end` bytes (both inclusive). * * @example * ```ts * import { ByteSliceStream } from "https://deno.land/std@$STD_VERSION/streams/byte_slice_stream.ts"; * * const response = await fetch("https://example.com"); * const rangedStream = response.body! * .pipeThrough(new ByteSliceStream(3, 8)); * ``` */export class ByteSliceStream extends TransformStream<Uint8Array, Uint8Array> { #offsetStart = 0; #offsetEnd = 0;
/** Constructs a new instance. */ constructor(start = 0, end: number = Infinity) { super({ start: () => { assert(start >= 0, "`start` must be greater than 0"); end += 1; }, transform: (chunk, controller) => { this.#offsetStart = this.#offsetEnd; this.#offsetEnd += chunk.byteLength; if (this.#offsetEnd > start) { if (this.#offsetStart < start) { chunk = chunk.slice(start - this.#offsetStart); } if (this.#offsetEnd >= end) { chunk = chunk.slice(0, chunk.byteLength - this.#offsetEnd + end); controller.enqueue(chunk); controller.terminate(); } else { controller.enqueue(chunk); } } }, }); }}
std

Version Info

Tagged at
6 months ago