Skip to content

Delete unsafe from brotli refcount translation - #618

Merged
nunoplopes merged 2 commits into
Cpp2Rust:masterfrom
lucic71:brotli-safe
Nov 14, 2026
Merged

nunoplopes merged 2 commits into
Cpp2Rust:masterfrom
lucic71:brotli-safe

Conversation

@lucic71

@lucic71 lucic71 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

The previous refcount translation of brotli used unsafe FFI. This PR adds a safe shim that keeps the API structure of C while using the safe brotli crate in the background.

For example in C, BrotliDecoderState is an opaque pointer and functions return memory inside it:

BrotliDecoderState* s = BrotliDecoderCreateInstance(...);
const uint8_t* chunk = BrotliDecoderTakeOutput(s, ...);

In the safe brotli crate the pattern is:

let mut s: BrotliState<...> = BrotliState::new_strict(...);
let chunk: &[u8] = BrotliDecoderTakeOutput(&mut s, ...);

The shim bridges these 2 APIs:

pub struct BrotliDecoderState {
    pub state: BrotliState<...>,
    taken: Ptr<u8>,
}

// BrotliDecoderState* s = BrotliDecoderCreateInstance(...);
let s: Ptr<BrotliDecoderState> = Ptr::alloc(BrotliDecoderState::default());

// const uint8_t* chunk = BrotliDecoderTakeOutput(s, &n);
pub fn BrotliDecoderTakeOutput(s: Ptr<BrotliDecoderState>, n: Ptr<usize>) -> Ptr<u8> {
    s.with_mut(|s| {
        ...
        let out: &[u8] = brotli_decompressor::BrotliDecoderTakeOutput(&mut s.state, &mut len);
        s.taken = Ptr::alloc_array(out.into()); // transform &[u8] into Ptr<u8>
        s.taken.clone()
    })
}

The safe rust brotli crate promises byte-by-byte identical output to C only for compression levels 0-9. For 10 and 11 the output of the encoder might differ.

This is fine, encoders are not required to be byte-by-byte identical. Only decoding requires that. This means that we need to change the scripts in cpp2rust-testsuite.

@nunoplopes
nunoplopes merged commit 56fe426 into Cpp2Rust:master Nov 14, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants