aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils.rs
blob: af3ce29217e6ed2836fcc825658aa3d0ac3abada (plain) (blame)
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
use std::{
    ffi,
    path,
    str,
};

use std::os::unix::ffi::OsStrExt;

use libc;

pub trait NewFromPtr<T> {
    fn new(ptr: T) -> Self;
}

pub trait ToCString {
    fn to_cstring(&self) -> Result<ffi::CString, ffi::NulError>;
}

impl<T: AsRef<path::Path>> ToCString for T {
    fn to_cstring(&self) -> Result<ffi::CString, ffi::NulError> {
        let path: &ffi::OsStr = self.as_ref().as_ref();
        path.to_cstring()
    }
}

pub trait ToStr {
    fn to_str<'a>(&self) -> Result<&'a str, str::Utf8Error>;
}

impl ToStr for *const libc::c_char {
    fn to_str<'a>(&self) -> Result<&'a str, str::Utf8Error> {
        str::from_utf8(unsafe {
            ffi::CStr::from_ptr(*self)
        }.to_bytes())
    }
}