chj_rustbin/
path_from.rs

1//! More From implementations for Path
2
3use std::{
4    ffi::{CStr, CString, NulError, OsStr, OsString},
5    os::unix::prelude::{OsStrExt, OsStringExt},
6    path::{Path, PathBuf},
7};
8
9pub trait MoreTryFrom<T>: Sized {
10    /// The type returned in the event of a conversion error.
11    type Error;
12
13    /// Performs the conversion.
14    fn more_try_from(value: T) -> Result<Self, Self::Error>;
15}
16
17// Ah, for Unix only!
18impl MoreTryFrom<&OsStr> for CString {
19    type Error = NulError;
20
21    fn more_try_from(value: &OsStr) -> Result<Self, Self::Error> {
22        CString::new(value.to_owned().into_vec())
23    }
24}
25
26// Ah, for Unix only!
27impl MoreTryFrom<&OsString> for CString {
28    type Error = NulError;
29
30    fn more_try_from(value: &OsString) -> Result<Self, Self::Error> {
31        CString::new(value.to_owned().into_vec())
32    }
33}
34
35// Ah, for Unix only!
36impl MoreTryFrom<OsString> for CString {
37    type Error = NulError;
38
39    fn more_try_from(value: OsString) -> Result<Self, Self::Error> {
40        CString::new(value.into_vec())
41    }
42}
43
44// Ah, for Unix only!
45impl MoreTryFrom<&Path> for CString {
46    type Error = NulError;
47
48    fn more_try_from(value: &Path) -> Result<Self, Self::Error> {
49        CString::more_try_from(OsString::from(value))
50    }
51}
52
53// Ah, for Unix only!
54impl MoreTryFrom<&PathBuf> for CString {
55    type Error = NulError;
56
57    fn more_try_from(value: &PathBuf) -> Result<Self, Self::Error> {
58        CString::more_try_from(OsString::from(value))
59    }
60}
61
62// Ah, for Unix only!
63impl MoreTryFrom<PathBuf> for CString {
64    type Error = NulError;
65
66    fn more_try_from(value: PathBuf) -> Result<Self, Self::Error> {
67        CString::more_try_from(OsString::from(value))
68    }
69}
70
71pub trait MoreFrom<T>: Sized {
72    fn more_from(value: T) -> Self;
73}
74
75// Ah, for Unix only, going via bytes assuming UTF-8!
76impl<'t> MoreFrom<&'t CStr> for &'t OsStr {
77    fn more_from(value: &'t CStr) -> Self {
78        OsStr::from_bytes(value.to_bytes())
79    }
80}
81
82// Ah, for Unix only, going via bytes assuming UTF-8!
83impl<'t> MoreFrom<&'t CStr> for &'t Path {
84    fn more_from(value: &'t CStr) -> Self {
85        Path::new(OsStr::from_bytes(value.to_bytes()))
86    }
87}
88
89// Ah, for Unix only, going via bytes assuming UTF-8!
90impl MoreFrom<&CStr> for PathBuf {
91    fn more_from(value: &CStr) -> Self {
92        Path::new(OsStr::from_bytes(value.to_bytes())).into()
93    }
94}