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
use std::ffi::{OsStr, CStr, CString};
use std::path::{Path, PathBuf};
use std::os::unix::ffi::OsStrExt;

use crate::{Entry};


/// The purpose of this is similar to `AsRef<Path>` but it's optimized for
/// things that can be directly used as `CStr` (which is type passed to
/// the underlying system call).
///
/// This trait should be implemented for everything for which `AsRef<Path>`
/// is implemented
pub trait AsPath {
    /// The return value of the `to_path` that holds data copied from the
    /// original path (if copy is needed, otherwise it's just a reference)
    type Buffer: AsRef<CStr>;
    /// Returns `None` when path contains a zero byte
    fn to_path(self) -> Option<Self::Buffer>;
}

impl<'a> AsPath for &'a Path {
    type Buffer = CString;
    fn to_path(self) -> Option<CString> {
        CString::new(self.as_os_str().as_bytes()).ok()
    }
}

impl<'a> AsPath for &'a PathBuf {
    type Buffer = CString;
    fn to_path(self) -> Option<CString> {
        CString::new(self.as_os_str().as_bytes()).ok()
    }
}

impl<'a> AsPath for &'a OsStr {
    type Buffer = CString;
    fn to_path(self) -> Option<CString> {
        CString::new(self.as_bytes()).ok()
    }
}

impl<'a> AsPath for &'a str {
    type Buffer = CString;
    fn to_path(self) -> Option<CString> {
        CString::new(self.as_bytes()).ok()
    }
}

impl<'a> AsPath for &'a String {
    type Buffer = CString;
    fn to_path(self) -> Option<CString> {
        CString::new(self.as_bytes()).ok()
    }
}

impl<'a> AsPath for String {
    type Buffer = CString;
    fn to_path(self) -> Option<CString> {
        CString::new(self).ok()
    }
}

impl<'a> AsPath for &'a CStr {
    type Buffer = &'a CStr;
    fn to_path(self) -> Option<&'a CStr> {
        Some(self)
    }
}

impl<'a> AsPath for &'a Entry {
    type Buffer = &'a CStr;
    fn to_path(self) -> Option<&'a CStr> {
        Some(&self.name)
    }
}