libloading/
util.rs

1use std::ffi::{CStr, CString};
2use std::borrow::Cow;
3use std::os::raw;
4
5use crate::Error;
6
7/// Checks for last byte and avoids allocating if it is zero.
8///
9/// Non-last null bytes still result in an error.
10pub(crate) fn cstr_cow_from_bytes<'a>(slice: &'a [u8]) -> Result<Cow<'a, CStr>, Error> {
11    static ZERO: raw::c_char = 0;
12    Ok(match slice.last() {
13        // Slice out of 0 elements
14        None => unsafe { Cow::Borrowed(CStr::from_ptr(&ZERO)) },
15        // Slice with trailing 0
16        Some(&0) => Cow::Borrowed(CStr::from_bytes_with_nul(slice)
17            .map_err(|source| Error::CreateCStringWithTrailing { source })?),
18        // Slice with no trailing 0
19        Some(_) => Cow::Owned(CString::new(slice)
20            .map_err(|source| Error::CreateCString { source })?),
21    })
22}
23
24#[inline]
25pub(crate) fn ensure_compatible_types<T, E>() -> Result<(), Error> {
26    if ::std::mem::size_of::<T>() != ::std::mem::size_of::<E>() {
27        Err(Error::IncompatibleSize)
28    } else {
29        Ok(())
30    }
31}