1 use std::ffi::{CStr, CString, NulError, FromBytesWithNulError};
2 use std::borrow::Cow;
3 use std::os::raw;
4 
5 #[derive(Debug)]
6 pub struct NullError;
7 
8 impl From<NulError> for NullError {
from(_: NulError) -> NullError9     fn from(_: NulError) -> NullError {
10         NullError
11     }
12 }
13 
14 impl From<FromBytesWithNulError> for NullError {
from(_: FromBytesWithNulError) -> NullError15     fn from(_: FromBytesWithNulError) -> NullError {
16         NullError
17     }
18 }
19 
20 impl From<NullError> for ::std::io::Error {
from(e: NullError) -> ::std::io::Error21     fn from(e: NullError) -> ::std::io::Error {
22         ::std::io::Error::new(::std::io::ErrorKind::Other, format!("{}", e))
23     }
24 }
25 
26 impl ::std::error::Error for NullError {
description(&self) -> &str27     fn description(&self) -> &str { "non-final null byte found" }
28 }
29 
30 impl ::std::fmt::Display for NullError {
fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result31     fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
32         write!(f, "non-final null byte found")
33     }
34 }
35 
36 /// Checks for last byte and avoids allocating if it is zero.
37 ///
38 /// Non-last null bytes still result in an error.
cstr_cow_from_bytes<'a>(slice: &'a [u8]) -> Result<Cow<'a, CStr>, NullError>39 pub fn cstr_cow_from_bytes<'a>(slice: &'a [u8]) -> Result<Cow<'a, CStr>, NullError> {
40     static ZERO: raw::c_char = 0;
41     Ok(match slice.last() {
42         // Slice out of 0 elements
43         None => unsafe { Cow::Borrowed(CStr::from_ptr(&ZERO)) },
44         // Slice with trailing 0
45         Some(&0) => Cow::Borrowed(try!(CStr::from_bytes_with_nul(slice))),
46         // Slice with no trailing 0
47         Some(_) => Cow::Owned(try!(CString::new(slice))),
48     })
49 }
50 
51 #[inline]
ensure_compatible_types<T, E>()52 pub fn ensure_compatible_types<T, E>() {
53     #[cold]
54     #[inline(never)]
55     fn dopanic() {
56         panic!("value of requested type cannot be dynamically loaded");
57     }
58     if ::std::mem::size_of::<T>() != ::std::mem::size_of::<E>() {
59         dopanic()
60     }
61 }
62