1use std::borrow::Cow; 2use std::ffi::{CStr, CString}; 3use std::os::raw; 4 5use crate::Error; 6 7/// Checks for the 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(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( 17 CStr::from_bytes_with_nul(slice) 18 .map_err(|source| Error::CreateCStringWithTrailing { source })?, 19 ), 20 // Slice with no trailing 0 21 Some(_) => { 22 Cow::Owned(CString::new(slice).map_err(|source| Error::CreateCString { source })?) 23 } 24 }) 25} 26 27#[inline] 28pub(crate) fn ensure_compatible_types<T, E>() -> Result<(), Error> { 29 if ::std::mem::size_of::<T>() != ::std::mem::size_of::<E>() { 30 Err(Error::IncompatibleSize) 31 } else { 32 Ok(()) 33 } 34} 35