Move collectUint8Arrays() to util/async.ts, clean up, fix bugs, add tests

Original: dcad420b92
This commit is contained in:
Bert Belder 2019-05-20 17:08:05 -07:00
parent 79c88a46bb
commit 16e52ee4b0
3 changed files with 73 additions and 26 deletions

View file

@ -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;
}