use std::ffi::CStr;
use std::ffi::c_char;
use std::ptr::NonNull;
use std::string::FromUtf8Error;
use crate::bindings::llama_rs_string_free;
use crate::exception_message_error::ExceptionMessageError;
#[derive(Debug)]
pub struct CppAllocatedString {
pointer: NonNull<c_char>,
}
impl CppAllocatedString {
#[must_use]
pub const unsafe fn from_raw(pointer: *mut c_char) -> Self {
Self {
pointer: unsafe { NonNull::new_unchecked(pointer) },
}
}
pub fn into_reported_error<TError>(
self,
operation: &'static str,
reported: impl FnOnce(String) -> TError,
) -> TError
where
TError: ExceptionMessageError,
{
self.into_string().map_or_else(
|source| TError::exception_message_not_utf8(operation, source),
reported,
)
}
pub fn into_string(self) -> Result<String, FromUtf8Error> {
String::from_utf8(
unsafe { CStr::from_ptr(self.pointer.as_ptr()) }
.to_bytes()
.to_vec(),
)
}
}
impl Drop for CppAllocatedString {
fn drop(&mut self) {
unsafe { llama_rs_string_free(self.pointer.as_ptr()) };
}
}
#[cfg(test)]
mod tests {
use std::string::FromUtf8Error;
use super::CppAllocatedString;
use crate::bindings::llama_rs_string_dup;
use crate::exception_message_error::ExceptionMessageError;
#[derive(Debug, PartialEq, Eq)]
enum ReportedFailure {
Reported(String),
ExceptionMessageNotUtf8 {
operation: &'static str,
source: FromUtf8Error,
},
}
impl ExceptionMessageError for ReportedFailure {
fn exception_message_not_utf8(operation: &'static str, source: FromUtf8Error) -> Self {
Self::ExceptionMessageNotUtf8 { operation, source }
}
}
#[test]
fn into_reported_error_builds_the_reported_error_from_the_message() {
let message = unsafe {
CppAllocatedString::from_raw(llama_rs_string_dup(c"llama.cpp threw".as_ptr()))
};
assert_eq!(
message.into_reported_error("llama_rs_process", ReportedFailure::Reported),
ReportedFailure::Reported("llama.cpp threw".to_owned())
);
}
#[test]
fn into_reported_error_reports_a_message_that_is_not_utf8() {
let message =
unsafe { CppAllocatedString::from_raw(llama_rs_string_dup(c"\xff".as_ptr())) };
assert_eq!(
message.into_reported_error("llama_rs_process", ReportedFailure::Reported),
ReportedFailure::ExceptionMessageNotUtf8 {
operation: "llama_rs_process",
source: String::from_utf8(vec![0xFF]).unwrap_err(),
}
);
}
}