openat/
name.rs

1use std::ffi::{OsStr, CStr, CString};
2use std::path::{Path, PathBuf};
3use std::os::unix::ffi::OsStrExt;
4
5use {Entry};
6
7
8/// The purpose of this is similar to `AsRef<Path>` but it's optimized for
9/// things that can be directly used as `CStr` (which is type passed to
10/// the underlying system call).
11///
12/// This trait should be implemented for everything for which `AsRef<Path>`
13/// is implemented
14pub trait AsPath {
15    /// The return value of the `to_path` that holds data copied from the
16    /// original path (if copy is needed, otherwise it's just a reference)
17    type Buffer: AsRef<CStr>;
18    /// Returns `None` when path contains a zero byte
19    fn to_path(self) -> Option<Self::Buffer>;
20}
21
22impl<'a> AsPath for &'a Path {
23    type Buffer = CString;
24    fn to_path(self) -> Option<CString> {
25        CString::new(self.as_os_str().as_bytes()).ok()
26    }
27}
28
29impl<'a> AsPath for &'a PathBuf {
30    type Buffer = CString;
31    fn to_path(self) -> Option<CString> {
32        CString::new(self.as_os_str().as_bytes()).ok()
33    }
34}
35
36impl<'a> AsPath for &'a OsStr {
37    type Buffer = CString;
38    fn to_path(self) -> Option<CString> {
39        CString::new(self.as_bytes()).ok()
40    }
41}
42
43impl<'a> AsPath for &'a str {
44    type Buffer = CString;
45    fn to_path(self) -> Option<CString> {
46        CString::new(self.as_bytes()).ok()
47    }
48}
49
50impl<'a> AsPath for &'a String {
51    type Buffer = CString;
52    fn to_path(self) -> Option<CString> {
53        CString::new(self.as_bytes()).ok()
54    }
55}
56
57impl<'a> AsPath for String {
58    type Buffer = CString;
59    fn to_path(self) -> Option<CString> {
60        CString::new(self).ok()
61    }
62}
63
64impl<'a> AsPath for &'a CStr {
65    type Buffer = &'a CStr;
66    fn to_path(self) -> Option<&'a CStr> {
67        Some(self)
68    }
69}
70
71impl<'a> AsPath for &'a Entry {
72    type Buffer = &'a CStr;
73    fn to_path(self) -> Option<&'a CStr> {
74        Some(&self.name)
75    }
76}