llama_cpp_path_c_string/
path_c_string.rs1use std::ffi::CString;
2use std::path::Path;
3
4use crate::path_c_string_error::PathCStringError;
5
6pub fn path_c_string(path: &Path) -> Result<CString, PathCStringError> {
11 let path_str = path
12 .to_str()
13 .ok_or_else(|| PathCStringError::NotUtf8(path.to_path_buf()))?;
14
15 CString::new(path_str).map_err(PathCStringError::ContainsNulByte)
16}
17
18#[cfg(test)]
19mod tests {
20 use std::ffi::CString;
21 use std::ffi::OsStr;
22 use std::os::unix::ffi::OsStrExt;
23 use std::path::Path;
24
25 use super::path_c_string;
26 use crate::path_c_string_error::PathCStringError;
27
28 #[test]
29 fn a_utf8_path_becomes_its_c_string() {
30 assert_eq!(
31 path_c_string(Path::new("/models/decision.gguf")),
32 Ok(c"/models/decision.gguf".to_owned())
33 );
34 }
35
36 #[test]
37 fn a_path_that_is_not_utf8_is_refused() {
38 let path = Path::new(OsStr::from_bytes(b"/models/\xff\xfe.gguf"));
39
40 assert_eq!(
41 path_c_string(path),
42 Err(PathCStringError::NotUtf8(path.to_path_buf()))
43 );
44 }
45
46 #[test]
47 fn a_path_with_a_nul_byte_is_refused() {
48 assert_eq!(
49 path_c_string(Path::new("/models/deci\0sion.gguf")),
50 Err(PathCStringError::ContainsNulByte(
51 CString::new("/models/deci\0sion.gguf").unwrap_err()
52 ))
53 );
54 }
55}