Skip to content

Instantly share code, notes, and snippets.

@nervecenter
Created August 21, 2024 18:43
Show Gist options
  • Select an option

  • Save nervecenter/ce1c029655e9281ba4652cba3a1f6aab to your computer and use it in GitHub Desktop.

Select an option

Save nervecenter/ce1c029655e9281ba4652cba3a1f6aab to your computer and use it in GitHub Desktop.
#
# Brotli implementation for static compilation with musl-libc
# Compiled with: --gcc.exe:musl-gcc --gcc.linkerexe:musl-gcc --passL:-static --dynlibOverrideAll --passL:lib/libbrotli.a
#
type
BrotliEncoderMode = enum
BROTLI_MODE_GENERIC = 0.cint
BROTLI_MODE_TEXT = 1.cint
BROTLI_MODE_FONT = 2.cint
BrotliBool = enum
BROTLI_FALSE = 0.cint
BROTLI_TRUE = 1.cint
BrotliDecoderResult = enum
BROTLI_DECODER_RESULT_ERROR = 0.cint
BROTLI_DECODER_RESULT_SUCCESS = 1.cint
BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT = 2.cint
BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT = 3.cint
const
BROTLI_DEFAULT_QUALITY = 11.cint
BROTLI_DEFAULT_WINDOW = 22.cint
# BROTLI_DEFAULT_MODE = BROTLI_MODE_GENERIC
proc BrotliEncoderCompress(quality: cint,
lgwin: cint,
mode: BrotliEncoderMode,
input_size: csize_t,
input_buffer: cstring,
encoded_size: pointer,
encoded_buffer: cstring): BrotliBool {.importc.}
proc BrotliEncoderMaxCompressedSize(input_size: csize_t): csize_t {.importc.}
proc BrotliDecoderDecompress(encoded_size: csize_t,
encoded_buffer: cstring,
decoded_size: pointer,
decoded_buffer: cstring): BrotliDecoderResult {.importc.}
proc brotli_compress*(input: string): string =
let input_size = input.len.csize_t
var
output_size = BrotliEncoderMaxCompressedSize(input_size)
output = new_string(output_size.int)
let compress_result = BrotliEncoderCompress(
BROTLI_DEFAULT_QUALITY, BROTLI_DEFAULT_WINDOW, BROTLI_MODE_GENERIC,
input_size, input.cstring, addr output_size, output.cstring
)
if compress_result == BROTLI_FALSE and output_size == 0:
quit("Error with Brotli compression.", -2)
return output[0 ..< output_size]
proc brotli_decompress*(input: string): string =
let input_size = input.len.csize_t
var
buffer_alloc_size = 512_000 # Allocate 512 kb initially
output_size = buffer_alloc_size.csize_t
output = new_string(output_size.int)
decompress_result: BrotliDecoderResult
# Try decompressing; as we fail, keep doubling the size of the buffer
while true:
# If we've reached 10 Mb we've definitely screwed up
if buffer_alloc_size > 10_000_000:
quit("Failure to decompress, buffer broke 10 Mb.", -3)
decompress_result = BrotliDecoderDecompress(
input_size, input.cstring, addr output_size, output.cstring
)
if decompress_result == BROTLI_DECODER_RESULT_SUCCESS: break
buffer_alloc_size *= 2
output_size = buffer_alloc_size.csize_t
output = new_string(output_size.int)
return output[0 ..< output_size]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment