Newer
Older
minerva / Tests / LibWeb / Text / input / Streams / ReadableByteStream-default-tee.html
@minerva minerva on 13 Jul 1 KB Initial commit
<script src="../include.js"></script>
<script>
    const CHUNK1 = "abcdefghijklmnopqrstuvwxyz";
    const CHUNK2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const CHUNK3 = "0123456789!@#$%^&*()-=_+,<";

    const readStream = (stream, name) => {
        const reader = stream.getReader();

        return new Promise((resolve, reject) => {
            const processText = ({ done, value }) => {
                if (done) {
                    println(`${name}: Done!`);
                    resolve();
                    return;
                }

                value = new TextDecoder().decode(value);
                println(`${name}: ${value}`);

                return reader.read().then(processText);
            };

            reader.read().then(processText);
        });
    };

    const writeStream = (controller, data) => {
        const source = Uint8Array.from(Array.from(data).map(ch => ch.charCodeAt(0)));
        controller.enqueue(source);
    };

    asyncTest(done => {
        const stream = new ReadableStream({
            type: "bytes",

            start(controller) {
                pullCount = 0;
            },

            pull(controller) {
                ++pullCount;

                if (pullCount == 1) {
                    writeStream(controller, CHUNK1);
                } else if (pullCount == 2) {
                    writeStream(controller, CHUNK2);
                } else if (pullCount == 3) {
                    writeStream(controller, CHUNK3);
                } else {
                    controller.close();
                }
            },

            cancel() {},
        });

        const teed = stream.tee();

        readStream(teed[0], "stream1").then(() => {
            readStream(teed[1], "stream2").then(done);
        });
    });
</script>