File
Blob: src/workerd/api/streams/compression.h
| 1 | // Copyright (c) 2017-2022 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 | |
| 5 | #pragma once |
| 6 | |
| 7 | #include <workerd/api/streams/transform.h> |
| 8 | #include <workerd/jsg/jsg.h> |
| 9 | |
| 10 | #include <zlib.h> |
| 11 | |
| 12 | namespace workerd::api { |
| 13 | |
| 14 | // A custom allocator to be used by the zlib and brotli libraries. |
| 15 | // The allocator should not and can not safely hold a reference to the jsg::Lock |
| 16 | // instance. Therefore, we lookup the current jsg::Lock instance from the |
| 17 | // isolate pointer and use that to get the external memory adjustment. |
| 18 | class CompressionAllocator final { |
| 19 | public: |
| 20 | CompressionAllocator(kj::Arc<const jsg::ExternalMemoryTarget>&& externalMemoryTarget); |
| 21 | void configure(z_stream* stream); |
| 22 | |
| 23 | static void* AllocForZlib(void* data, uInt items, uInt size); |
| 24 | static void* AllocForBrotli(void* data, size_t size); |
| 25 | static void FreeForZlib(void* data, void* pointer); |
| 26 | |
| 27 | private: |
| 28 | struct Allocation { |
| 29 | kj::Array<kj::byte> data; |
| 30 | kj::Maybe<jsg::ExternalMemoryAdjustment> memoryAdjustment = kj::none; |
| 31 | }; |
| 32 | |
| 33 | kj::Arc<const jsg::ExternalMemoryTarget> externalMemoryTarget; |
| 34 | kj::HashMap<void*, Allocation> allocations; |
| 35 | }; |
| 36 | |
| 37 | class CompressionStream: public TransformStream { |
| 38 | public: |
| 39 | using TransformStream::TransformStream; |
| 40 | |
| 41 | static jsg::Ref<CompressionStream> constructor(jsg::Lock& js, kj::String format); |
| 42 | |
| 43 | JSG_RESOURCE_TYPE(CompressionStream) { |
| 44 | JSG_INHERIT(TransformStream); |
| 45 | |
| 46 | JSG_TS_OVERRIDE(extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> { constructor(format |
| 47 | : "gzip" | "deflate" | "deflate-raw"); |
| 48 | }); |
| 49 | } |
| 50 | }; |
| 51 | |
| 52 | class DecompressionStream: public TransformStream { |
| 53 | public: |
| 54 | using TransformStream::TransformStream; |
| 55 | |
| 56 | static jsg::Ref<DecompressionStream> constructor(jsg::Lock& js, kj::String format); |
| 57 | |
| 58 | JSG_RESOURCE_TYPE(DecompressionStream) { |
| 59 | JSG_INHERIT(TransformStream); |
| 60 | |
| 61 | JSG_TS_OVERRIDE(extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> { constructor(format |
| 62 | : "gzip" | "deflate" | "deflate-raw"); |
| 63 | }); |
| 64 | } |
| 65 | }; |
| 66 | |
| 67 | } // namespace workerd::api |