Expand description
Generic FfiState<T> wrapper for safe aggregate state management.
§Problem solved
Writing the state init/destroy lifecycle using raw pointers is error-prone. The canonical pattern is:
use libduckdb_sys::{duckdb_function_info, duckdb_aggregate_state, idx_t};
#[derive(Default)]
struct MyState { count: u64 }
#[repr(C)]
struct FfiState { inner: *mut MyState }
unsafe extern "C" fn state_init(_: duckdb_function_info, state: duckdb_aggregate_state) {
let ffi = &mut *(state as *mut FfiState);
ffi.inner = Box::into_raw(Box::new(MyState::default()));
}
unsafe extern "C" fn state_destroy(states: *mut duckdb_aggregate_state, count: idx_t) {
for i in 0..count as usize {
let state_ptr = *states.add(i);
let ffi = &mut *(state_ptr as *mut FfiState);
if !ffi.inner.is_null() {
drop(Box::from_raw(ffi.inner));
ffi.inner = std::ptr::null_mut();
}
}
}FfiState<T> encapsulates this pattern. Your type T only needs to
implement AggregateState (which requires Default), and you call the
provided helper methods instead of writing raw pointer code.
§Pitfalls prevented
- L1: Combine propagates all fields because your type
T’scombinemethod is responsible — theFfiStatewrapper ensuresT’s method is called. - L2: No double-free —
destroy_callbackclears the state’s tag before droppingT, and drops only a state whose tag matches. - L3: No panic across FFI —
with_state_mutreturns anOption, not a panic.
Structs§
- FfiState
- A generic FFI-compatible state wrapper for use with
DuckDBaggregate functions.
Traits§
- Aggregate
State - Trait for types that can be used as
DuckDBaggregate state.