1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108

/// This module provides an interface between Rust native strings and
/// nul-terminated C-strings.

use std::ffi::{CStr, CString};

use libc::c_char;

use error::Error;

/// Create a CStr safely without the need to convert or allocate additional
/// space.
#[macro_export]
macro_rules! cstr {
    ( $( $s:expr ),*) => {
        unsafe {
            CStr::from_bytes_with_nul_unchecked(
                concat!(
                    $( $s:expr ),*
                    '\0'
                ).as_bytes()
            )
        }
    }
}

/// Trait for types which can be converted into a CString.
pub trait IntoCString {
    fn into_cstring(self) -> CString;
}

/// Trait for types which can be attempted to convert into a Rust String.
pub trait TryIntoString {
    type Error;
    fn try_into_string(self) -> Result<String, Self::Error>;
}

impl IntoCString for CString {
    fn into_cstring(self) -> CString {
        self
    }
}

impl<'a> IntoCString for &'a CStr {
    fn into_cstring(self) -> CString {
        CStr::into_c_string(From::from(self))
    }
}

impl IntoCString for String {
    fn into_cstring(mut self) -> CString {
        self.push('\0');
        unsafe { CString::from_vec_unchecked(self.into_bytes()) }
    }
}

impl<'a> IntoCString for &'a String {
    fn into_cstring(self) -> CString {
        self.clone().into_cstring()
    }
}

impl<'a> IntoCString for &'a str {
    fn into_cstring(self) -> CString {
        let mut bytes = self.as_bytes().to_vec();
        bytes.push(0);
        unsafe { CString::from_vec_unchecked(bytes) }
    }
}

impl TryIntoString for *const c_char {
    type Error = Error;
    fn try_into_string(self) -> Result<String, Error> {
        if self.is_null() {
            Err(Error::NullPointer)
        } else {
            unsafe { CStr::from_ptr(self).try_into_string() }
        }
    }
}

impl<'a> TryIntoString for &'a CStr {
    type Error = Error;
    fn try_into_string(self) -> Result<String, Error> {
        self.to_owned().try_into_string()
    }
}

impl TryIntoString for CString {
    type Error = Error;
    fn try_into_string(self) -> Result<String, Error> {
        self.into_string().map_err(From::from)
    }
}

impl<'a> TryIntoString for &'a str {
    type Error = Error;
    fn try_into_string(self) -> Result<String, Error> {
        Ok(self.to_owned())
    }
}

impl TryIntoString for String {
    type Error = Error;
    fn try_into_string(self) -> Result<String, Error> {
        Ok(self)
    }
}