Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions packages/node/tests/_helpers/chunks.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,30 @@
import { Readable } from 'stream';
import { ChunkSplitter } from '../../src/streams/chunkifier.js';

/**
* Trims array from right until `predicate` returns `false`.
* @returns Trimmed array.
*/
function trimRightIf<T>(t: T[], predicate: (t: T) => boolean) {
for (let i = t.length - 1; i >= 0; i--) {
if (predicate(t[i])) {
continue;
}

return t.slice(0, i + 1);
}

return [];
}

export async function splitToEnd(readable: Readable, splitter: ChunkSplitter) {
const results: Buffer[][] = [[]];

for await (let chunk of readable) {
while (chunk) {
const [c1, c2] = splitter(chunk, readable.readableEncoding ?? 'utf-8');
results[results.length - 1].push(c1);
if (!c2?.length) {
break;
} else if (c2) {
if (c2) {
chunk = c2;
results.push([]);
} else {
Expand All @@ -19,7 +33,11 @@ export async function splitToEnd(readable: Readable, splitter: ChunkSplitter) {
}
}

return results.map((b) => Buffer.concat(b));
// Remove all trailing empty arrays
return trimRightIf(
results.map((b) => Buffer.concat(b)),
(t) => !t.length,
);
}

export function* chunkify(chunk: Buffer, length: number) {
Expand Down