Skip to main content

llama_cpp_bindings/
ffi_error_reader.rs

1use std::ffi::{CStr, c_char};
2
3/// Reads a C error string, converts to Rust `String`, and frees the C memory.
4///
5/// # Safety
6///
7/// `error_ptr` must be either null or a valid pointer to a null-terminated
8/// C string allocated by `llama_rs_dup_string`.
9pub unsafe fn read_and_free_cpp_error(error_ptr: *mut c_char) -> String {
10    if error_ptr.is_null() {
11        return "unknown error".to_owned();
12    }
13
14    let message = unsafe { CStr::from_ptr(error_ptr) }
15        .to_string_lossy()
16        .into_owned();
17
18    unsafe { llama_cpp_bindings_sys::llama_rs_string_free(error_ptr) };
19
20    message
21}
22
23#[cfg(test)]
24mod tests {
25    use super::read_and_free_cpp_error;
26
27    #[test]
28    fn returns_unknown_for_null_pointer() {
29        let result = unsafe { read_and_free_cpp_error(std::ptr::null_mut()) };
30
31        assert_eq!(result, "unknown error");
32    }
33}