Skip to main content

ps_str/utf8_encoder/
mod.rs

1mod variants;
2
3use std::path::PathBuf;
4
5pub trait Utf8Encoder {
6    /// Converts a byte sequence into a UTF-8 string, replacing invalid bytes
7    /// with fallback characters from the [`CHARS`](crate::CHARS) table.
8    fn to_utf8_string(&self) -> String;
9
10    /// Converts a byte sequence into a [`PathBuf`] using the same decoding rules
11    /// as [`Self::to_utf8_string`].
12    ///
13    /// Valid UTF-8 runs pass through unchanged; other bytes are
14    /// mapped through the [`CHARS`](crate::CHARS) fallback table. This is **lossy**
15    /// for paths containing non-UTF-8 bytes.
16    ///
17    /// To preserve the original bytes exactly (e.g. when opening an existing
18    /// file with a non-UTF-8 name on Unix), do not use this method. Convert
19    /// the bytes directly into an [`OsString`](std::ffi::OsString) via a platform-specific API
20    /// such as `std::os::unix::ffi::OsStringExt::from_vec`, then into a
21    /// [`PathBuf`].
22    ///
23    /// # Example
24    ///
25    /// ```
26    /// use std::path::PathBuf;
27    /// use ps_str::Utf8Encoder;
28    ///
29    /// let bytes = b"hello.txt";
30    ///
31    /// assert_eq!(bytes.to_utf8_path(), PathBuf::from("hello.txt"));
32    /// ```
33    fn to_utf8_path(&self) -> PathBuf {
34        self.to_utf8_string().into()
35    }
36}