pth/as_path.rs
1/// Define a private namespace for all its items.
2mod private
3{
4 #[ allow( unused_imports, clippy::wildcard_imports ) ]
5 use crate::*;
6 #[ cfg( feature = "no_std" ) ]
7 extern crate std;
8
9 use std::path::Path;
10
11 /// A trait for converting various types into a reference to a `Path`.
12 ///
13 /// This trait is used to avoid redundant allocation of memory by providing a reference to a `Path`.
14 /// It is implemented only for types that can either be referenced or are references to `Path` itself.
15 /// Unlike `TryIntoPath`, it does not allocate memory on the heap. However, `TryIntoPath` is implemented for a wider range of types because it is not restricted from allocating memory.
16 /// Unlike `AsRef<Path>`, `AsPath` is implemented for a wider number of types, including those that are not directly convertible to a `Path` using `AsRef`.
17 /// This is because `AsPath` is designed to provide a more flexible interface for path-like types, accommodating various representations that can logically be treated as paths.
18 pub trait AsPath
19 {
20 /// Converts the implementing type into a reference to a `Path`.
21 ///
22 /// # Returns
23 ///
24 /// A reference to a `Path`.
25 fn as_path( &self ) -> &Path;
26 }
27
28 /// Implementation of `AsPath` for `str`.
29 impl AsPath for str
30 {
31 fn as_path( &self ) -> &Path
32 {
33 Path::new( self )
34 }
35 }
36
37 /// Implementation of `AsPath` for `Path`.
38 impl AsPath for Path
39 {
40 fn as_path( &self ) -> &Path
41 {
42 self
43 }
44 }
45
46 /// Implementation of `AsPath` for `Utf8Path`.
47 #[ cfg( feature = "path_utf8" ) ]
48 impl AsPath for Utf8Path
49 {
50 fn as_path( &self ) -> &Path
51 {
52 self.as_std_path()
53 }
54 }
55
56 /// Blanket implementation of `AsPath` for all types that implement `AsRef<Path>`.
57 impl< T > AsPath for T
58 where
59 T : AsRef< Path >,
60 {
61 fn as_path( &self ) -> &Path
62 {
63 self.as_ref()
64 }
65 }
66}
67
68crate::mod_interface!
69{
70 orphan use AsPath;
71}