Yokan / rebuild
Course 1 8624561

GzipDecompress.wasm.kt

composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/extensions/GzipDecompress.wasm.kt

implementation65 lines
1@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)23package eu.friedcutlet.yokan.services.extensions45import kotlinx.coroutines.suspendCancellableCoroutine6import kotlin.coroutines.resume7import kotlin.coroutines.resumeWithException8import kotlin.io.encoding.Base649import kotlin.io.encoding.ExperimentalEncodingApi10import kotlin.js.JsAny11import kotlin.js.Promise12import kotlin.js.js1314@OptIn(ExperimentalEncodingApi::class)15internal actual suspend fun gzipDecompress(bytes: ByteArray): ByteArray =16    suspendCancellableCoroutine { continuation ->17        gzipDecompressJs(Base64.encode(bytes), MaxProtobufDecompressedBytes).then(18            onFulfilled = { value ->19                runCatching { Base64.decode(jsString(value)) }20                    .fold(continuation::resume, continuation::resumeWithException)21                null22            },23            onRejected = { error ->24                continuation.resumeWithException(IllegalStateException(jsString(error)))25                null26            },27        )28    }2930private fun gzipDecompressJs(base64: String, maxOutputBytes: Int): Promise<JsAny> = js(31    """32    (async () => {33        const binary = atob(base64);34        const input = new Uint8Array(binary.length);35        for (let i = 0; i < binary.length; i++) input[i] = binary.charCodeAt(i);36        const stream = new Blob([input]).stream().pipeThrough(new DecompressionStream('gzip'));37        const reader = stream.getReader();38        const chunks = [];39        let outputLength = 0;40        while (true) {41            const result = await reader.read();42            if (result.done) break;43            outputLength += result.value.byteLength;44            if (outputLength > maxOutputBytes) {45                await reader.cancel();46                throw new Error('decompressed protobuf exceeds the 64 MiB limit');47            }48            chunks.push(result.value);49        }50        const bytes = new Uint8Array(outputLength);51        let offset = 0;52        for (const chunk of chunks) {53            bytes.set(chunk, offset);54            offset += chunk.byteLength;55        }56        let result = '';57        for (let i = 0; i < bytes.length; i += 0x8000) {58            result += String.fromCharCode(...bytes.subarray(i, i + 0x8000));59        }60        return btoa(result);61    })()62    """,63)6465private fun jsString(value: JsAny): String = js("String(value)")66

Search chapters, reference and source filenames.