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