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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use crate::{EntityPathPart, Index};

#[derive(thiserror::Error, Debug, PartialEq, Eq)]
pub enum PathParseError {
    #[error("Expected path, found empty string")]
    EmptyString,

    #[error("Path had leading slash")]
    LeadingSlash,

    #[error("Missing closing quote (\")")]
    UnterminatedString,

    #[error("Bad escape sequence: {details}")]
    BadEscape { details: &'static str },

    #[error("Double-slashes with no part between")]
    DoubleSlash,

    #[error("Invalid sequence: {0:?} (expected positive integer)")]
    InvalidSequence(String),

    #[error("Missing slash (/)")]
    MissingSlash,
}

/// Parses an entity path, e.g. `foo/bar/#1234/5678/"string index"/a6a5e96c-fd52-4d21-a394-ffbb6e5def1d`
pub fn parse_entity_path(path: &str) -> Result<Vec<EntityPathPart>, PathParseError> {
    if path.is_empty() {
        return Err(PathParseError::EmptyString);
    }

    if path == "/" {
        return Ok(vec![]); // special-case root entity
    }

    if path.starts_with('/') {
        return Err(PathParseError::LeadingSlash);
    }

    let mut bytes = path.as_bytes();

    let mut parts = vec![];

    while let Some(c) = bytes.first() {
        if *c == b'"' {
            // Look for the terminating quote ignoring escaped quotes (\"):
            let mut i = 1;
            loop {
                if i == bytes.len() {
                    return Err(PathParseError::UnterminatedString);
                } else if bytes[i] == b'\\' && i + 1 < bytes.len() {
                    i += 2; // consume escape and what was escaped
                } else if bytes[i] == b'"' {
                    break;
                } else {
                    i += 1;
                }
            }

            let unescaped = unescape_string(std::str::from_utf8(&bytes[1..i]).unwrap())
                .map_err(|details| PathParseError::BadEscape { details })?;

            parts.push(EntityPathPart::Index(Index::String(unescaped)));

            bytes = &bytes[i + 1..]; // skip the closing quote

            match bytes.first() {
                None => {
                    break;
                }
                Some(b'/') => {
                    bytes = &bytes[1..];
                }
                _ => {
                    return Err(PathParseError::MissingSlash);
                }
            }
        } else {
            let end = bytes.iter().position(|&b| b == b'/').unwrap_or(bytes.len());
            parts.push(parse_part(std::str::from_utf8(&bytes[0..end]).unwrap())?);
            if end == bytes.len() {
                break;
            } else {
                bytes = &bytes[end + 1..]; // skip the /
            }
        }
    }

    Ok(parts)
}

fn parse_part(s: &str) -> Result<EntityPathPart, PathParseError> {
    use std::str::FromStr as _;

    if s.is_empty() {
        Err(PathParseError::DoubleSlash)
    } else if let Some(s) = s.strip_prefix('#') {
        if let Ok(sequence) = u64::from_str(s) {
            Ok(EntityPathPart::Index(Index::Sequence(sequence)))
        } else {
            Err(PathParseError::InvalidSequence(s.into()))
        }
    } else if let Ok(integer) = i128::from_str(s) {
        Ok(EntityPathPart::Index(Index::Integer(integer)))
    } else if let Ok(uuid) = uuid::Uuid::parse_str(s) {
        Ok(EntityPathPart::Index(Index::Uuid(uuid)))
    } else {
        Ok(EntityPathPart::Name(s.into()))
    }
}

fn unescape_string(input: &str) -> Result<String, &'static str> {
    let mut output = String::with_capacity(input.len());
    let mut chars = input.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            if let Some(c) = chars.next() {
                output.push(match c {
                    'n' => '\n',
                    'r' => '\r',
                    't' => '\t',
                    '\"' | '\\' => c,
                    _ => {
                        return Err("Unknown escape sequence (\\)");
                    }
                });
            } else {
                return Err("Trailing escape (\\)");
            }
        } else {
            output.push(c);
        }
    }
    Ok(output)
}

#[test]
fn test_unescape_string() {
    let input = r#"Hello \"World\" /  \\ \n\r\t"#;
    let unescaped = unescape_string(input).unwrap();
    assert_eq!(unescaped, "Hello \"World\" /  \\ \n\r\t");
}

#[test]
fn test_parse_path() {
    use crate::entity_path_vec;

    assert_eq!(parse_entity_path(""), Err(PathParseError::EmptyString));
    assert_eq!(parse_entity_path("/"), Ok(entity_path_vec!()));
    assert_eq!(parse_entity_path("foo"), Ok(entity_path_vec!("foo")));
    assert_eq!(parse_entity_path("/foo"), Err(PathParseError::LeadingSlash));
    assert_eq!(
        parse_entity_path("foo/bar"),
        Ok(entity_path_vec!("foo", "bar"))
    );
    assert_eq!(
        parse_entity_path("foo//bar"),
        Err(PathParseError::DoubleSlash)
    );
    assert_eq!(
        parse_entity_path(r#"foo/"bar"/#123/-1234/6d046bf4-e5d3-4599-9153-85dd97218cb3"#),
        Ok(entity_path_vec!(
            "foo",
            Index::String("bar".into()),
            Index::Sequence(123),
            Index::Integer(-1234),
            Index::Uuid(uuid::Uuid::parse_str("6d046bf4-e5d3-4599-9153-85dd97218cb3").unwrap())
        ))
    );
    assert_eq!(
        parse_entity_path(r#"foo/"bar""baz""#),
        Err(PathParseError::MissingSlash)
    );
}