forked from msgpack/msgpack-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.ts
More file actions
42 lines (36 loc) · 1.18 KB
/
stream.ts
File metadata and controls
42 lines (36 loc) · 1.18 KB
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
// utility for whatwg streams
// The living standard of whatwg streams says
// ReadableStream is also AsyncIterable, but
// as of June 2019, no browser implements it.
// See https://streams.spec.whatwg.org/ for details
export type ReadableStreamLike<T> = AsyncIterable<T> | ReadableStream<T>;
export function isAsyncIterable<T>(object: ReadableStreamLike<T>): object is AsyncIterable<T> {
return (object as any)[Symbol.asyncIterator] != null;
}
function assertNonNull<T>(value: T | null | undefined): asserts value is T {
if (value == null) {
throw new Error("Assertion Failure: value must not be null nor undefined");
}
}
export async function* asyncIterableFromStream<T>(stream: ReadableStream<T>): AsyncIterable<T> {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
return;
}
assertNonNull(value);
yield value;
}
} finally {
reader.releaseLock();
}
}
export function ensureAsyncIterabe<T>(streamLike: ReadableStreamLike<T>): AsyncIterable<T> {
if (isAsyncIterable(streamLike)) {
return streamLike;
} else {
return asyncIterableFromStream(streamLike);
}
}