test_path/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use std::fs::{create_dir_all, remove_dir_all};
use std::path::{Path, Component};
use std::env::{temp_dir};

pub fn is_valid(path: &str) -> bool {
    let p = Path::new(path);
    let mut t = temp_dir();

    if p.has_root() {
        for c in p.components() {
            match c {
                Component::Prefix(_p) => {
                    continue;
                }
                Component::RootDir => {
                    continue;
                }
                _ => {
                    t = t.join(c);
                }
            }
        }
    } else {
        t = t.join(p);
    }

    match create_dir_all(&t) {
        Err(_e) => return false,
        Ok(()) => {
            match remove_dir_all(&t) {
                Err(_e) => return false,
                Ok(()) => return true,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_valid() {
        assert_eq!(is_valid("1"), true);
        assert_eq!(is_valid("C:/测试"), true);
        assert_eq!(is_valid("C:/test"), true);
        assert_eq!(is_valid("X:/x/y/z"), true);
        assert_eq!(is_valid(r"C:/te|st"), false);
    }
}