1.5 KiB · text History f960521
//! Capped decompression for the ingest edge (`Vigil.Ingest.Codec.Native`).
//!
//! `decompress_brotli(input, max)` inflates at most `max` bytes. Output
//! past the cap is never produced: the reader is bounded at `max + 1`
//! bytes, and reaching that answers `{:error, :too_large}`, so a
//! decompression bomb costs at most `max` bytes of memory.

use rustler::{Atom, Binary, Env, NifResult, OwnedBinary, Term};
use std::io::Read;

mod atoms {
    rustler::atoms! {
        ok,
        error,
        too_large,
        invalid,
    }
}

#[rustler::nif(schedule = "DirtyCpu")]
fn decompress_brotli<'a>(env: Env<'a>, input: Binary, max: u64) -> NifResult<Term<'a>> {
    let reader = brotli_decompressor::Decompressor::new(input.as_slice(), 4096);
    let mut out = Vec::new();

    let result = reader.take(max.saturating_add(1)).read_to_end(&mut out);

    match result {
        Ok(_) if out.len() as u64 > max => Ok(error(env, atoms::too_large())),
        Ok(_) => {
            let mut binary = OwnedBinary::new(out.len())
                .ok_or(rustler::Error::Term(Box::new("allocation failed")))?;
            binary.as_mut_slice().copy_from_slice(&out);
            Ok(rustler::Encoder::encode(
                &(atoms::ok(), binary.release(env)),
                env,
            ))
        }
        Err(_) => Ok(error(env, atoms::invalid())),
    }
}

fn error<'a>(env: Env<'a>, reason: Atom) -> Term<'a> {
    rustler::Encoder::encode(&(atoms::error(), reason), env)
}

rustler::init!("Elixir.Vigil.Ingest.Codec.Native");