use cxx::UniquePtr;
use crate::FastPForResult;
use crate::codec::default_max_decoded_len;
use crate::cpp::ffi;
use crate::helpers::AsUsize;
pub fn encode32_to_vec_ffi(
codec: &UniquePtr<ffi::IntegerCODEC>,
input: &[u32],
out: &mut Vec<u32>,
) -> FastPForResult<()> {
let capacity = input.len() * 2 + 1024;
let start = out.len();
out.resize(start + capacity, 0);
let n = ffi::codec_encode32(codec, input, &mut out[start..])?;
assert!(
n <= capacity,
"C++ codec encoded more than the allocated capacity"
);
out.truncate(start + n);
Ok(())
}
pub fn decode32_anylen_ffi(
codec: &UniquePtr<ffi::IntegerCODEC>,
input: &[u32],
out: &mut Vec<u32>,
expected_len: Option<u32>,
) -> FastPForResult<()> {
let max = default_max_decoded_len(input.len());
let capacity = if let Some(n) = expected_len {
n.is_valid_expected(max)?
} else {
max
};
let start = out.len();
if !input.is_empty() {
const DECODE_OVERFLOW_PADDING: usize = 32;
out.resize(start + capacity + DECODE_OVERFLOW_PADDING, 0);
let n = ffi::codec_decode32(codec, input, &mut out[start..])?;
assert!(
n < capacity + DECODE_OVERFLOW_PADDING,
"C++ codec decoded more than the allocated capacity + padding"
);
out.truncate(start + n);
}
if let Some(n) = expected_len {
(out.len() - start).is_decoded_mismatch(n)?;
}
Ok(())
}
pub fn encode64_to_vec_ffi(
codec: &UniquePtr<ffi::IntegerCODEC>,
input: &[u64],
out: &mut Vec<u32>,
) -> FastPForResult<()> {
let capacity = input.len() * 3 + 1024;
let start = out.len();
out.resize(start + capacity, 0);
let n = ffi::codec_encode64(codec, input, &mut out[start..])?;
out.truncate(start + n);
Ok(())
}
pub fn decode64_to_vec_ffi(
codec: &UniquePtr<ffi::IntegerCODEC>,
input: &[u32],
out: &mut Vec<u64>,
) -> FastPForResult<()> {
if !input.is_empty() {
let capacity = input.len().saturating_mul(4);
let start = out.len();
out.resize(start + capacity, 0);
let n = ffi::codec_decode64(codec, input, &mut out[start..])?;
out.truncate(start + n);
}
Ok(())
}