Skip to main content

fuck_backslash/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(clippy::cargo)]
3
4use std::{ffi::OsString, path::PathBuf};
5
6pub trait FuckBackslash {
7    /// Replaces the windows separator `\` with the unix separator `/`.
8    fn fuck_backslash(self) -> Self;
9}
10
11impl FuckBackslash for PathBuf {
12    fn fuck_backslash(self) -> Self {
13        unsafe {
14            let mut encodded = self.into_os_string().into_encoded_bytes();
15            for byte in encodded.iter_mut() {
16                if *byte == b'\\' {
17                    *byte = b'/';
18                }
19            }
20            PathBuf::from(OsString::from_encoded_bytes_unchecked(encodded))
21        }
22    }
23}
24
25#[cfg(test)]
26mod tests {
27    use super::*;
28
29    #[test]
30    fn it_works() {
31        let testcase = [
32            ("./../tmp/asd", "./../tmp/asd"),
33            (
34                r"C:\Users\xxx\Desktop\test.txt",
35                "C:/Users/xxx/Desktop/test.txt",
36            ),
37            (r"/tmp\aasd", "/tmp/aasd"),
38            (
39                "C:\\一些中文名字\\とある日本語目録\\.\\\r\t",
40                "C:/一些中文名字/とある日本語目録/./\r\t",
41            ),
42        ]
43        .map(|(input, output)| (PathBuf::from(input), PathBuf::from(output)));
44
45        for (input, output) in testcase {
46            let replaced = input.fuck_backslash();
47            assert_eq!(replaced, output);
48        }
49    }
50}