Skip to main content

ps_str/
path.rs

1use crate::Utf8Encoder;
2
3/// Extension trait for encoding paths to UTF-8 strings.
4///
5/// This is a separate trait from `Utf8Encoder` due to Rust's coherence rules
6/// preventing blanket implementations from coexisting with specific type implementations.
7pub trait PathUtf8Encoder {
8    /// Converts a path to a UTF-8 string, replacing invalid bytes with fallback characters.
9    ///
10    /// # Example
11    ///
12    /// ```
13    /// use ps_str::PathUtf8Encoder;
14    /// use std::path::Path;
15    ///
16    /// let path = Path::new("hello.txt");
17    /// let encoded = path.to_utf8_string();
18    /// assert_eq!(encoded, "hello.txt");
19    /// ```
20    fn to_utf8_string(&self) -> String;
21}
22
23impl PathUtf8Encoder for std::path::Path {
24    fn to_utf8_string(&self) -> String {
25        self.as_os_str().as_encoded_bytes().to_utf8_string()
26    }
27}
28
29impl PathUtf8Encoder for std::path::PathBuf {
30    fn to_utf8_string(&self) -> String {
31        self.as_path().to_utf8_string()
32    }
33}