nc/
path.rs

1// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
2// Use of this source is governed by Apache-2.0 License that can be found
3// in the LICENSE file.
4
5#[cfg(not(feature = "std"))]
6use alloc::string::String;
7#[cfg(not(feature = "std"))]
8use alloc::vec::Vec;
9
10/// Reimplementation of `std::path::Path`.
11pub struct Path {
12    internal: [u8],
13}
14
15impl Path {
16    #[inline]
17    pub fn new<S: AsRef<[u8]> + ?Sized>(s: &S) -> &Self {
18        unsafe { &*(s.as_ref() as *const [u8] as *const Self) }
19    }
20
21    #[must_use]
22    #[inline]
23    pub const fn len(&self) -> usize {
24        self.internal.len()
25    }
26
27    #[must_use]
28    #[inline]
29    pub const fn is_empty(&self) -> bool {
30        self.internal.is_empty()
31    }
32}
33
34impl AsRef<Path> for str {
35    #[inline]
36    fn as_ref(&self) -> &Path {
37        Path::new(self)
38    }
39}
40
41impl AsRef<Path> for String {
42    #[inline]
43    fn as_ref(&self) -> &Path {
44        Path::new(self)
45    }
46}
47
48impl From<&Path> for Vec<u8> {
49    fn from(path: &Path) -> Self {
50        path.internal.to_vec()
51    }
52}
53
54#[cfg(feature = "std")]
55mod with_std {
56    use std::borrow::Cow;
57    use std::ffi::{OsStr, OsString};
58    use std::os::unix::ffi::OsStrExt;
59    use std::path;
60
61    use super::Path;
62
63    impl AsRef<Path> for OsStr {
64        #[inline]
65        fn as_ref(&self) -> &Path {
66            Path::new(self.as_bytes())
67        }
68    }
69    impl AsRef<Path> for Cow<'_, OsStr> {
70        #[inline]
71        fn as_ref(&self) -> &Path {
72            Path::new(self.as_bytes())
73        }
74    }
75    impl AsRef<Path> for OsString {
76        #[inline]
77        fn as_ref(&self) -> &Path {
78            Path::new(self.as_bytes())
79        }
80    }
81    impl AsRef<Path> for path::PathBuf {
82        fn as_ref(&self) -> &Path {
83            self.as_path().as_ref()
84        }
85    }
86    impl AsRef<Path> for path::Path {
87        #[inline]
88        fn as_ref(&self) -> &Path {
89            Path::new(self.as_os_str().as_bytes())
90        }
91    }
92}