1 use std::ffi::{CStr, CString};
2 use std::borrow::Cow;
3 use std::os::raw;
4 
5 use 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.
cstr_cow_from_bytes(slice: &[u8]) -> Result<Cow<'_, CStr>, Error>10 pub(crate) fn cstr_cow_from_bytes(slice: &[u8]) -> Result<Cow<'_, 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]
ensure_compatible_types<T, E>() -> Result<(), Error>25 pub(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 }
32