Skip to main content

Module state

Module state 

Source
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’s combine method is responsible — the FfiState wrapper ensures T’s method is called.
  • L2: No double-free — destroy_callback clears the state’s tag before dropping T, and drops only a state whose tag matches.
  • L3: No panic across FFI — with_state_mut returns an Option, not a panic.

Structs§

FfiState
A generic FFI-compatible state wrapper for use with DuckDB aggregate functions.

Traits§

AggregateState
Trait for types that can be used as DuckDB aggregate state.