Skip to main content

laser_wire/filter/
path.rs

1use crate::error::InvalidError;
2use crate::limits::{MAX_FILTER_PATH_BYTES, MAX_FILTER_PATH_SEGMENTS};
3use serde::de::Error as _;
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use std::fmt;
6
7/// One step of a [`FieldPath`]: an object key or an array index.
8#[derive(Clone, Debug, PartialEq, Eq, Hash)]
9pub enum PathSegment {
10    Key(String),
11    Index(u32),
12}
13
14/// A validated location inside a decoded payload.
15///
16/// The text form separates object keys with `.` and selects array elements
17/// with `[n]`, so `after.ground_stations[0]` reads the first ground station. A
18/// literal `.`, `[`, `]`, or `\` inside a key is escaped with `\`. A digit-only
19/// key stays a key (`codes.200`), only brackets select an index. There is one
20/// text form per path, so the rendered string is also the canonical encoding
21/// the filter digest covers.
22#[derive(Clone, Debug, PartialEq, Eq, Hash)]
23pub struct FieldPath {
24    segments: Vec<PathSegment>,
25}
26
27impl FieldPath {
28    /// Parse the text form. Rejects empty keys, unterminated escapes or
29    /// brackets, non-canonical indexes, and paths over the segment or byte caps.
30    pub fn parse(text: &str) -> Result<Self, InvalidError> {
31        if text.is_empty() {
32            return Err(InvalidError::new("field path must not be empty"));
33        }
34        if text.len() > MAX_FILTER_PATH_BYTES {
35            return Err(InvalidError::new(format!(
36                "field path is {}B, exceeds cap {MAX_FILTER_PATH_BYTES}B",
37                text.len()
38            )));
39        }
40        let mut parser = PathParser {
41            bytes: text.as_bytes(),
42            position: 0,
43            text,
44        };
45        let segments = parser.segments()?;
46        if segments.len() > MAX_FILTER_PATH_SEGMENTS {
47            return Err(InvalidError::new(format!(
48                "field path `{text}` has {} segments, exceeds cap {MAX_FILTER_PATH_SEGMENTS}",
49                segments.len()
50            )));
51        }
52        Ok(Self { segments })
53    }
54
55    pub fn segments(&self) -> &[PathSegment] {
56        &self.segments
57    }
58}
59
60impl fmt::Display for FieldPath {
61    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
62        for (position, segment) in self.segments.iter().enumerate() {
63            match segment {
64                PathSegment::Key(key) => {
65                    if position > 0 {
66                        formatter.write_str(".")?;
67                    }
68                    for character in key.chars() {
69                        if matches!(character, '.' | '[' | ']' | '\\') {
70                            formatter.write_str("\\")?;
71                        }
72                        write!(formatter, "{character}")?;
73                    }
74                }
75                PathSegment::Index(index) => write!(formatter, "[{index}]")?,
76            }
77        }
78        Ok(())
79    }
80}
81
82impl std::str::FromStr for FieldPath {
83    type Err = InvalidError;
84
85    fn from_str(text: &str) -> Result<Self, Self::Err> {
86        Self::parse(text)
87    }
88}
89
90#[cfg(feature = "schemars")]
91impl schemars::JsonSchema for FieldPath {
92    fn schema_name() -> std::borrow::Cow<'static, str> {
93        "FieldPath".into()
94    }
95
96    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
97        schemars::json_schema!({ "description": "A field path such as `order.total`", "type": "string" })
98    }
99}
100
101impl Serialize for FieldPath {
102    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
103        serializer.collect_str(self)
104    }
105}
106
107impl<'de> Deserialize<'de> for FieldPath {
108    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
109        let text = String::deserialize(deserializer)?;
110        Self::parse(&text).map_err(D::Error::custom)
111    }
112}
113
114struct PathParser<'a> {
115    bytes: &'a [u8],
116    position: usize,
117    text: &'a str,
118}
119
120impl PathParser<'_> {
121    fn segments(&mut self) -> Result<Vec<PathSegment>, InvalidError> {
122        let mut segments = Vec::new();
123        if self.peek() == Some(b'[') {
124            segments.push(self.index()?);
125        } else {
126            segments.push(self.key()?);
127        }
128        while let Some(byte) = self.peek() {
129            match byte {
130                b'.' => {
131                    self.position += 1;
132                    segments.push(self.key()?);
133                }
134                b'[' => segments.push(self.index()?),
135                _ => return Err(self.invalid("expected `.` or `[` after a segment")),
136            }
137        }
138        Ok(segments)
139    }
140
141    fn key(&mut self) -> Result<PathSegment, InvalidError> {
142        let mut key = String::new();
143        while let Some(byte) = self.peek() {
144            match byte {
145                b'.' | b'[' => break,
146                b']' => return Err(self.invalid("unescaped `]` inside a key")),
147                b'\\' => {
148                    self.position += 1;
149                    match self.peek() {
150                        Some(escaped @ (b'.' | b'[' | b']' | b'\\')) => {
151                            key.push(char::from(escaped));
152                            self.position += 1;
153                        }
154                        _ => return Err(self.invalid("`\\` must escape `.`, `[`, `]`, or `\\`")),
155                    }
156                }
157                _ => {
158                    let rest = &self.text[self.position..];
159                    let character = rest
160                        .chars()
161                        .next()
162                        .expect("a peeked byte starts a character");
163                    key.push(character);
164                    self.position += character.len_utf8();
165                }
166            }
167        }
168        if key.is_empty() {
169            return Err(self.invalid("empty key"));
170        }
171        Ok(PathSegment::Key(key))
172    }
173
174    fn index(&mut self) -> Result<PathSegment, InvalidError> {
175        self.position += 1;
176        let start = self.position;
177        while self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
178            self.position += 1;
179        }
180        let digits = &self.text[start..self.position];
181        if self.peek() != Some(b']') {
182            return Err(self.invalid("an index must be digits closed by `]`"));
183        }
184        self.position += 1;
185        if digits.is_empty() || (digits.len() > 1 && digits.starts_with('0')) {
186            return Err(self.invalid("an index must be a canonical decimal number"));
187        }
188        digits
189            .parse::<u32>()
190            .map(PathSegment::Index)
191            .map_err(|_| self.invalid("an index must fit in 32 bits"))
192    }
193
194    fn peek(&self) -> Option<u8> {
195        self.bytes.get(self.position).copied()
196    }
197
198    fn invalid(&self, reason: &str) -> InvalidError {
199        InvalidError::new(format!(
200            "field path `{}` is invalid at byte {}: {reason}",
201            self.text, self.position
202        ))
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    fn round_trip(text: &str) -> Vec<PathSegment> {
211        let path = FieldPath::parse(text).expect("the path parses");
212        assert_eq!(path.to_string(), text, "the text form is canonical");
213        path.segments().to_vec()
214    }
215
216    #[test]
217    fn given_dotted_keys_when_parsed_then_should_split_on_dots() {
218        assert_eq!(
219            round_trip("after.orbit.kind"),
220            vec![
221                PathSegment::Key("after".to_owned()),
222                PathSegment::Key("orbit".to_owned()),
223                PathSegment::Key("kind".to_owned()),
224            ]
225        );
226    }
227
228    #[test]
229    fn given_brackets_when_parsed_then_should_select_indexes() {
230        assert_eq!(
231            round_trip("[0].ground_stations[12]"),
232            vec![
233                PathSegment::Index(0),
234                PathSegment::Key("ground_stations".to_owned()),
235                PathSegment::Index(12),
236            ]
237        );
238    }
239
240    #[test]
241    fn given_a_digit_key_when_parsed_then_should_stay_a_key() {
242        assert_eq!(
243            round_trip("codes.200"),
244            vec![
245                PathSegment::Key("codes".to_owned()),
246                PathSegment::Key("200".to_owned()),
247            ]
248        );
249    }
250
251    #[test]
252    fn given_escaped_characters_when_parsed_then_should_keep_them_in_the_key() {
253        assert_eq!(
254            round_trip(r"a\.b.c\[d\]\\"),
255            vec![
256                PathSegment::Key("a.b".to_owned()),
257                PathSegment::Key(r"c[d]\".to_owned()),
258            ]
259        );
260    }
261
262    #[test]
263    fn given_malformed_paths_when_parsed_then_should_be_rejected() {
264        for text in [
265            "",
266            "a..b",
267            ".a",
268            "a.",
269            "a[",
270            "a[]",
271            "a[01]",
272            "a[x]",
273            "a]",
274            r"a\b",
275            r"a\",
276            "a[1]b",
277            "a[4294967296]",
278        ] {
279            assert!(FieldPath::parse(text).is_err(), "`{text}` must be rejected");
280        }
281    }
282
283    #[test]
284    fn given_too_many_segments_when_parsed_then_should_be_rejected() {
285        let text = vec!["a"; MAX_FILTER_PATH_SEGMENTS + 1].join(".");
286        assert!(FieldPath::parse(&text).is_err());
287        let text = vec!["a"; MAX_FILTER_PATH_SEGMENTS].join(".");
288        assert!(FieldPath::parse(&text).is_ok());
289    }
290
291    #[test]
292    fn given_a_path_when_serialized_then_should_be_its_text_form() {
293        let path = FieldPath::parse("fields.mode").expect("parses");
294        let json = serde_json::to_string(&path).expect("serializes");
295        assert_eq!(json, r#""fields.mode""#);
296        let back: FieldPath = serde_json::from_str(&json).expect("deserializes");
297        assert_eq!(back, path);
298        assert!(serde_json::from_str::<FieldPath>(r#""a..b""#).is_err());
299    }
300}