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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
//! Structs to handle abstraction over a path in JSON

use crate::error;
use std::{cmp::Ordering, convert::TryFrom, fmt, hash::Hash};

/// An element of the path
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Element {
    Key(String),
    Index(usize),
}

impl Element {
    pub fn is_key(&self) -> bool {
        matches!(self, Element::Key(_))
    }

    pub fn is_index(&self) -> bool {
        matches!(self, Element::Index(_))
    }
}

impl PartialOrd for Element {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Element {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (Element::Key(this_key), Element::Key(other_key)) => this_key.cmp(other_key),
            (Element::Index(this_idx), Element::Index(other_idx)) => this_idx.cmp(other_idx),
            (Element::Key(_), Element::Index(_)) => Ordering::Less,
            (Element::Index(_), Element::Key(_)) => Ordering::Greater,
        }
    }
}

impl fmt::Display for Element {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Key(string) => write!(f, "{{\"{}\"}}", string),
            Self::Index(idx) => write!(f, "[{}]", idx),
        }
    }
}

/// Represents the path in a json
/// e.g. {"users"}[0]
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct Path {
    path: Vec<Element>,
}

impl Path {
    pub fn new() -> Self {
        Self::default()
    }

    /// Removes last path element
    pub fn pop(&mut self) -> Option<Element> {
        self.path.pop()
    }

    /// Appends path element
    pub fn push(&mut self, element: Element) {
        self.path.push(element);
    }

    /// Returns the path depth
    pub fn depth(&self) -> usize {
        self.path.len()
    }

    /// Returns the actual path
    pub fn get_path(&self) -> &[Element] {
        &self.path
    }
}

/// Path parsing state
#[derive(Debug, PartialEq)]
enum PathState {
    ElementStart,
    Array,
    ObjectStart,
    Object(bool),
    ObjectEnd,
}

impl TryFrom<&str> for Path {
    type Error = error::Path;

    fn try_from(path_str: &str) -> Result<Self, Self::Error> {
        let mut state = PathState::ElementStart;
        let mut path = Self::new();
        let mut buffer = vec![];
        for chr in path_str.chars() {
            state = match state {
                PathState::ElementStart => match chr {
                    '[' => PathState::Array,
                    '{' => PathState::ObjectStart,
                    _ => return Err(error::Path::new(path_str)),
                },
                PathState::Array => match chr {
                    '0'..='9' => {
                        buffer.push(chr);
                        PathState::Array
                    }
                    ']' => {
                        let idx: usize = buffer.drain(..).collect::<String>().parse().unwrap();
                        path.push(Element::Index(idx));
                        PathState::ElementStart
                    }
                    _ => return Err(error::Path::new(path_str)),
                },
                PathState::ObjectStart => {
                    if chr == '"' {
                        PathState::Object(false)
                    } else {
                        return Err(error::Path::new(path_str));
                    }
                }
                PathState::Object(escaped) => {
                    if escaped {
                        buffer.push(chr);
                        PathState::Object(false)
                    } else {
                        match chr {
                            '\\' => {
                                buffer.push(chr);
                                PathState::Object(true)
                            }
                            '"' => PathState::ObjectEnd,
                            _ => {
                                buffer.push(chr);
                                PathState::Object(false)
                            }
                        }
                    }
                }
                PathState::ObjectEnd => {
                    if chr == '}' {
                        let key: String = buffer.drain(..).collect();
                        path.push(Element::Key(key));
                        PathState::ElementStart
                    } else {
                        return Err(error::Path::new(path_str));
                    }
                }
            };
        }
        if state == PathState::ElementStart {
            Ok(path)
        } else {
            Err(error::Path::new(path_str))
        }
    }
}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for element in &self.path {
            write!(f, "{}", element)?;
        }
        Ok(())
    }
}

impl Ord for Path {
    fn cmp(&self, other: &Self) -> Ordering {
        for (a, b) in self.path.iter().zip(other.path.iter()) {
            let res = a.cmp(b);
            if res != Ordering::Equal {
                return res;
            }
        }
        match (self.path.len(), other.path.len()) {
            (a_len, b_len) if a_len < b_len => Ordering::Less,
            (a_len, b_len) if a_len == b_len => Ordering::Equal,
            (a_len, b_len) if a_len > b_len => Ordering::Greater,
            (_, _) => unreachable!(),
        }
    }
}

impl PartialOrd for Path {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

#[cfg(test)]
mod tests {
    use super::{Element, Path};
    use std::convert::TryFrom;

    #[test]
    fn test_path_from_string_empty() {
        assert!(Path::try_from("").is_ok());
    }

    #[test]
    fn test_path_from_string_array() {
        let mut path = Path::new();
        path.push(Element::Index(0));
        assert_eq!(Path::try_from("[0]").unwrap(), path);
    }

    #[test]
    fn test_path_from_string_object() {
        let mut path = Path::new();
        path.push(Element::Key(r#"my-ke\\y\" "#.into()));
        assert_eq!(Path::try_from(r#"{"my-ke\\y\" "}"#).unwrap(), path);
    }
}