use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::path::Path;
use crate::error::YaraError;
pub(crate) fn path_to_cstring(
path: &Path,
label: &str,
make_err: fn(String) -> YaraError,
) -> Result<CString, YaraError> {
let s = path.to_str().ok_or_else(|| make_err(format!("{label} is not valid UTF-8")))?;
CString::new(s).map_err(|e| make_err(format!("{label} contains null byte: {e}")))
}
pub(crate) unsafe fn collect_contig_names(
count: usize,
name_fn: impl Fn(usize) -> *const c_char,
) -> Vec<String> {
(0..count)
.map(|i| {
let ptr = name_fn(i);
if ptr.is_null() {
String::new()
} else {
unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned()
}
})
.collect()
}
pub(crate) fn bytes_to_cstring(bytes: &[u8]) -> CString {
unsafe { CString::from_vec_unchecked(bytes.to_vec()) }
}
pub(crate) fn collect_contig_lengths(
count: usize,
length_fn: impl Fn(usize) -> usize,
) -> Vec<usize> {
(0..count).map(length_fn).collect()
}