refactor: use result wrapper for ffi

This commit is contained in:
kaichaosun 2026-02-27 15:28:45 +08:00
parent 7019b04ccb
commit 3673d730f3
No known key found for this signature in database
GPG Key ID: 223E0F992F4F03BF
5 changed files with 28 additions and 7 deletions

View File

@ -18,6 +18,7 @@ use storage::StorageConfig;
use crate::{
context::{Context, Introduction},
errors::ChatError,
ffi::utils::CResult,
types::ContentData,
};
@ -65,15 +66,23 @@ pub fn create_context(name: repr_c::String) -> repr_c::Box<ContextHandle> {
/// - db_path: Path to the SQLite database file
///
/// # Returns
/// Opaque handle to the context. Must be freed with destroy_context()
/// CResult with context handle on success, or error string on failure
#[ffi_export]
pub fn create_context_with_storage(
name: repr_c::String,
db_path: repr_c::String,
) -> repr_c::Box<ContextHandle> {
) -> CResult<repr_c::Box<ContextHandle>, repr_c::String> {
let config = StorageConfig::File(db_path.to_string());
let ctx = Context::open(&*name, config).expect("failed to open context with storage");
Box::new(ContextHandle(ctx)).into()
match Context::open(&*name, config) {
Ok(ctx) => CResult {
ok: Some(Box::new(ContextHandle(ctx)).into()),
err: None,
},
Err(e) => CResult {
ok: None,
err: Some(e.to_string().into()),
},
}
}
/// Returns the friendly name of the contexts installation.

View File

@ -18,9 +18,6 @@ pub use crate::inbox::Introduction;
/// Error type for Context operations.
#[derive(Debug, thiserror::Error)]
pub enum ContextError {
#[error("chat error: {0}")]
Chat(#[from] ChatError),
#[error("storage error: {0}")]
Storage(#[from] StorageError),
}

View File

@ -0,0 +1 @@
pub mod utils;

View File

@ -0,0 +1,13 @@
use safer_ffi::prelude::*;
#[derive_ReprC]
#[repr(C)]
pub struct CResult<T: ReprC, Err: ReprC> {
pub ok: Option<T>,
pub err: Option<Err>,
}
#[ffi_export]
pub fn ffi_c_string_free(s: repr_c::String) {
drop(s);
}

View File

@ -3,6 +3,7 @@ mod context;
mod conversation;
mod crypto;
mod errors;
mod ffi;
mod identity;
mod inbox;
mod proto;