File
Blob: src/worker/common/compression.ts
| 1 | import { asByteTransformStream, createBlobFromBytes } from "./webtypes"; |
| 2 | |
| 3 | /** |
| 4 | * Compression and decompression utilities using Web Streams API |
| 5 | */ |
| 6 | |
| 7 | async function transformBytes( |
| 8 | data: Uint8Array, |
| 9 | stream: CompressionStream | DecompressionStream |
| 10 | ): Promise<Uint8Array> { |
| 11 | const body = createBlobFromBytes(data).stream().pipeThrough(stream); |
| 12 | const buf = await new Response(body).arrayBuffer(); |
| 13 | return new Uint8Array(buf); |
| 14 | } |
| 15 | |
| 16 | /** |
| 17 | * Compress data using deflate algorithm |
| 18 | * @param data - Uint8Array to compress |
| 19 | * @returns Compressed Uint8Array |
| 20 | */ |
| 21 | export async function deflate(data: Uint8Array): Promise<Uint8Array> { |
| 22 | return transformBytes(data, new CompressionStream("deflate")); |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * Decompress data using deflate algorithm |
| 27 | * @param data - Compressed Uint8Array |
| 28 | * @returns Decompressed Uint8Array |
| 29 | */ |
| 30 | export async function inflate(data: Uint8Array): Promise<Uint8Array> { |
| 31 | return transformBytes(data, new DecompressionStream("deflate")); |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Compress data using gzip |
| 36 | * @param data - Uint8Array to compress |
| 37 | * @returns Compressed Uint8Array |
| 38 | */ |
| 39 | export async function gzip(data: Uint8Array): Promise<Uint8Array> { |
| 40 | return transformBytes(data, new CompressionStream("gzip")); |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Decompress data using gzip |
| 45 | * @param data - Compressed Uint8Array |
| 46 | * @returns Decompressed Uint8Array |
| 47 | */ |
| 48 | export async function gunzip(data: Uint8Array): Promise<Uint8Array> { |
| 49 | return transformBytes(data, new DecompressionStream("gzip")); |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Create a deflate compression transform stream |
| 54 | * @returns TransformStream for compression |
| 55 | */ |
| 56 | export function createDeflateStream(): TransformStream<Uint8Array, Uint8Array> { |
| 57 | return asByteTransformStream(new CompressionStream("deflate")); |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Create a deflate decompression transform stream |
| 62 | * @returns TransformStream for decompression |
| 63 | */ |
| 64 | export function createInflateStream(): TransformStream<Uint8Array, Uint8Array> { |
| 65 | return asByteTransformStream(new DecompressionStream("deflate")); |
| 66 | } |