mirror of
https://github.com/denoland/deno.git
synced 2025-10-02 07:01:16 +00:00
Move collectUint8Arrays() to util/async.ts, clean up, fix bugs, add tests
Original: dcad420b92
This commit is contained in:
parent
79c88a46bb
commit
16e52ee4b0
3 changed files with 73 additions and 26 deletions
|
@ -83,3 +83,28 @@ export class MuxAsyncIterator<T> implements AsyncIterable<T> {
|
|||
return this.iterate();
|
||||
}
|
||||
}
|
||||
|
||||
/** Collects all Uint8Arrays from an AsyncIterable and retuns a single
|
||||
* Uint8Array with the concatenated contents of all the collected arrays.
|
||||
*/
|
||||
export async function collectUint8Arrays(
|
||||
it: AsyncIterable<Uint8Array>
|
||||
): Promise<Uint8Array> {
|
||||
const chunks = [];
|
||||
let length = 0;
|
||||
for await (const chunk of it) {
|
||||
chunks.push(chunk);
|
||||
length += chunk.length;
|
||||
}
|
||||
if (chunks.length === 1) {
|
||||
// No need to copy.
|
||||
return chunks[0];
|
||||
}
|
||||
const collected = new Uint8Array(length);
|
||||
let offset = 0;
|
||||
for (let chunk of chunks) {
|
||||
collected.set(chunk, offset);
|
||||
offset += chunk.length;
|
||||
}
|
||||
return collected;
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue