llama_cpp_bindings_sys/
cpp_allocated_string.rs1use std::ffi::CStr;
2use std::ffi::c_char;
3use std::ptr::NonNull;
4use std::string::FromUtf8Error;
5
6use crate::bindings::llama_rs_string_free;
7use crate::exception_message_error::ExceptionMessageError;
8
9#[derive(Debug)]
12pub struct CppAllocatedString {
13 pointer: NonNull<c_char>,
14}
15
16impl CppAllocatedString {
17 #[must_use]
22 pub const unsafe fn from_raw(pointer: *mut c_char) -> Self {
23 Self {
24 pointer: unsafe { NonNull::new_unchecked(pointer) },
25 }
26 }
27
28 pub fn into_reported_error<TError>(
32 self,
33 operation: &'static str,
34 reported: impl FnOnce(String) -> TError,
35 ) -> TError
36 where
37 TError: ExceptionMessageError,
38 {
39 self.into_string().map_or_else(
40 |source| TError::exception_message_not_utf8(operation, source),
41 reported,
42 )
43 }
44
45 pub fn into_string(self) -> Result<String, FromUtf8Error> {
49 String::from_utf8(
50 unsafe { CStr::from_ptr(self.pointer.as_ptr()) }
51 .to_bytes()
52 .to_vec(),
53 )
54 }
55}
56
57impl Drop for CppAllocatedString {
58 fn drop(&mut self) {
59 unsafe { llama_rs_string_free(self.pointer.as_ptr()) };
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use std::string::FromUtf8Error;
66
67 use super::CppAllocatedString;
68 use crate::bindings::llama_rs_string_dup;
69 use crate::exception_message_error::ExceptionMessageError;
70
71 #[derive(Debug, PartialEq, Eq)]
72 enum ReportedFailure {
73 Reported(String),
74 ExceptionMessageNotUtf8 {
75 operation: &'static str,
76 source: FromUtf8Error,
77 },
78 }
79
80 impl ExceptionMessageError for ReportedFailure {
81 fn exception_message_not_utf8(operation: &'static str, source: FromUtf8Error) -> Self {
82 Self::ExceptionMessageNotUtf8 { operation, source }
83 }
84 }
85
86 #[test]
87 fn into_reported_error_builds_the_reported_error_from_the_message() {
88 let message = unsafe {
89 CppAllocatedString::from_raw(llama_rs_string_dup(c"llama.cpp threw".as_ptr()))
90 };
91
92 assert_eq!(
93 message.into_reported_error("llama_rs_process", ReportedFailure::Reported),
94 ReportedFailure::Reported("llama.cpp threw".to_owned())
95 );
96 }
97
98 #[test]
99 fn into_reported_error_reports_a_message_that_is_not_utf8() {
100 let message =
101 unsafe { CppAllocatedString::from_raw(llama_rs_string_dup(c"\xff".as_ptr())) };
102
103 assert_eq!(
104 message.into_reported_error("llama_rs_process", ReportedFailure::Reported),
105 ReportedFailure::ExceptionMessageNotUtf8 {
106 operation: "llama_rs_process",
107 source: String::from_utf8(vec![0xFF]).unwrap_err(),
108 }
109 );
110 }
111}