File
Blob: src/workerd/api/tests/pipe-write-special-buffer-test.js
| 1 | // Copyright (c) 2026 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | import { ok } from 'node:assert'; |
| 5 | |
| 6 | export const SabViewPipeThroughCompressionStream = { |
| 7 | async test() { |
| 8 | const sab = new SharedArrayBuffer(100); |
| 9 | const view = new Uint8Array(sab); |
| 10 | view.fill(0x41); |
| 11 | |
| 12 | const readable = new ReadableStream({ |
| 13 | start(controller) { |
| 14 | controller.enqueue(view); |
| 15 | controller.close(); |
| 16 | }, |
| 17 | }); |
| 18 | |
| 19 | const cs = new CompressionStream('gzip'); |
| 20 | await readable.pipeTo(cs.writable); |
| 21 | |
| 22 | const reader = cs.readable.getReader(); |
| 23 | const { value, done } = await reader.read(); |
| 24 | ok(!done); |
| 25 | ok(value.byteLength > 0, 'Expected compressed output'); |
| 26 | }, |
| 27 | }; |
| 28 | |
| 29 | export const SabViewPipeThroughIdentityTransform = { |
| 30 | async test() { |
| 31 | const sab = new SharedArrayBuffer(1024); |
| 32 | const view = new Uint8Array(sab); |
| 33 | view.fill(0x42); |
| 34 | |
| 35 | const readable = new ReadableStream({ |
| 36 | start(controller) { |
| 37 | controller.enqueue(view); |
| 38 | controller.close(); |
| 39 | }, |
| 40 | }); |
| 41 | |
| 42 | const ts = new IdentityTransformStream(); |
| 43 | const pipePromise = readable.pipeTo(ts.writable); |
| 44 | |
| 45 | const reader = ts.readable.getReader(); |
| 46 | const chunks = []; |
| 47 | while (true) { |
| 48 | const { value, done } = await reader.read(); |
| 49 | if (done) break; |
| 50 | chunks.push(value); |
| 51 | } |
| 52 | await pipePromise; |
| 53 | |
| 54 | const totalLength = chunks.reduce((sum, c) => sum + c.byteLength, 0); |
| 55 | ok(totalLength === 1024, `Expected 1024 bytes, got ${totalLength}`); |
| 56 | }, |
| 57 | }; |
| 58 | |
| 59 | export const ResizableBufferPipeThroughIdentityTransform = { |
| 60 | async test() { |
| 61 | const buffer = new ArrayBuffer(1024, { maxByteLength: 2048 }); |
| 62 | const view = new Uint8Array(buffer); |
| 63 | view.fill(0x43); |
| 64 | |
| 65 | const readable = new ReadableStream({ |
| 66 | start(controller) { |
| 67 | controller.enqueue(view); |
| 68 | controller.close(); |
| 69 | }, |
| 70 | }); |
| 71 | |
| 72 | const ts = new IdentityTransformStream(); |
| 73 | const pipePromise = readable.pipeTo(ts.writable); |
| 74 | |
| 75 | const reader = ts.readable.getReader(); |
| 76 | const chunks = []; |
| 77 | while (true) { |
| 78 | const { value, done } = await reader.read(); |
| 79 | if (done) break; |
| 80 | chunks.push(value); |
| 81 | } |
| 82 | await pipePromise; |
| 83 | |
| 84 | const totalLength = chunks.reduce((sum, c) => sum + c.byteLength, 0); |
| 85 | ok(totalLength === 1024, `Expected 1024 bytes, got ${totalLength}`); |
| 86 | }, |
| 87 | }; |