Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Unverified Commit a335c149 authored by Simon Chan's avatar Simon Chan
Browse files

feat(stream): improve SplitStringStream handling incomplete chunks

parent 0f29501c
Loading
Loading
Loading
Loading
+22 −21
Original line number Diff line number Diff line
import { TransformStream } from "./stream.js";

function* split(
    input: string,
    separator: string,
): Generator<string, void, void> {
    let start = 0;
export class SplitStringStream extends TransformStream<string, string> {
    constructor(separator: string) {
        let remaining: string | undefined = undefined;

    while (true) {
        const index = input.indexOf(separator, start);
        if (index === -1) {
            return;
        super({
            transform(chunk, controller) {
                if (remaining) {
                    chunk = remaining + chunk;
                    remaining = undefined;
                }

        const part = input.substring(start, index);
        yield part;
                let start = 0;
                while (start < chunk.length) {
                    const index = chunk.indexOf(separator, start);
                    if (index === -1) {
                        remaining = chunk.substring(start);
                        break;
                    }

                    controller.enqueue(chunk.substring(start, index));
                    start = index + 1;
                }
}

export class SplitStringStream extends TransformStream<string, string> {
    constructor(separator: string) {
        super({
            transform(chunk, controller) {
                for (const part of split(chunk, separator)) {
                    controller.enqueue(part);
            },
            flush(controller) {
                if (remaining) {
                    controller.enqueue(remaining);
                }
            },
        });