llama_cpp_bindings/
ffi_error_reader.rs1use std::ffi::{CStr, c_char};
2
3pub 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 std::ffi::CString;
26 use std::ffi::c_char;
27
28 use super::read_and_free_cpp_error;
29
30 unsafe extern "C" {
31 fn strdup(s: *const c_char) -> *mut c_char;
32 }
33
34 #[test]
35 fn returns_unknown_for_null_pointer() {
36 let result = unsafe { read_and_free_cpp_error(std::ptr::null_mut()) };
37
38 assert_eq!(result, "unknown error");
39 }
40
41 #[test]
42 fn returns_message_for_valid_cstring_pointer() {
43 let original = CString::new("expected error message").unwrap();
44 let dup_ptr = unsafe { strdup(original.as_ptr()) };
45 assert!(!dup_ptr.is_null(), "strdup must allocate a copy");
46
47 let result = unsafe { read_and_free_cpp_error(dup_ptr) };
48
49 assert_eq!(result, "expected error message");
50 }
51}