re_uri/
fragment.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
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
218
219
220
221
222
223
use re_log_types::{DataPath, TimeCell, TimelineName};

/// We use the `#fragment` of the URI to point to a specific entity.
///
/// ```
/// # use re_uri::Fragment;
/// # let tests = [
///  "focus=/entity/path",
///  "focus=/entity/path[#42]",
///  "focus=/entity/path[#42]&when=log_tick@32",
///  "focus=/entity/path&when=log_time@2022-01-01T00:00:03.123456789Z",
///  "when=log_time@2022-01-01T00:00:03.123456789Z",
/// # ];
/// # for test in tests {
/// #     assert!(test.parse::<Fragment>().unwrap() != Fragment::default());
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct Fragment {
    pub focus: Option<DataPath>,

    /// Select this timeline and this time
    pub when: Option<(TimelineName, TimeCell)>,
}

impl std::fmt::Display for Fragment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Self { focus, when } = self;

        let mut did_write = false;

        if let Some(focus) = focus {
            write!(f, "focus={focus}")?;
            did_write = true;
        }

        if let Some((timeline, time_cell)) = when {
            if did_write {
                write!(f, "&")?;
            }
            write!(f, "when={timeline}@{time_cell}")?;
        }

        Ok(())
    }
}

impl std::str::FromStr for Fragment {
    type Err = String;

    fn from_str(fragment: &str) -> Result<Self, Self::Err> {
        let mut focus = None;
        let mut when = None;

        for part in split_on_unescaped_ampersand(fragment) {
            if let Some((key, value)) = split_at_first_unescaped_equals(part) {
                match key {
                    "focus" => match value.parse() {
                        Ok(path) => {
                            if focus.is_some() {
                                re_log::warn_once!(
                                    "Multiple paths set in uri #fragment {fragment:?}. Ignoring all but last."
                                );
                            }
                            focus = Some(path);
                        }
                        Err(err) => {
                            return Err(format!("Bad data path {part:?}: {err}"));
                        }
                    },
                    "when" => {
                        if let Some((timeline, time)) = value.split_once('@') {
                            let timeline = TimelineName::from(timeline);
                            match time.parse::<TimeCell>() {
                                Ok(time_cell) => {
                                    if when.is_some() {
                                        re_log::warn_once!(
                                            "Multiple times set in uri #fragment {fragment:?}. Ignoring all but last."
                                        );
                                    }
                                    when = Some((timeline, time_cell));
                                }
                                Err(err) => {
                                    return Err(format!("Bad time value {time:?}: {err}"));
                                }
                            }
                        }
                    }
                    _ => {
                        return Err(format!(
                            "Unknown key {key:?}. Expected either 'focus' or 'time'"
                        ));
                    }
                }
            } else {
                re_log::warn_once!("Contained a part {part:?} without any equal sign in it");
            }
        }

        Ok(Self { focus, when })
    }
}

impl Fragment {
    /// Parse fragment, excluding hash
    pub fn parse_forgiving(fragment: &str) -> Self {
        match fragment.parse() {
            Ok(fragment) => fragment,
            Err(err) => {
                re_log::warn_once!("Failed to parse #fragment {fragment:?}: {err}");
                Self::default()
            }
        }
    }
}

/// Split on all '&' that is not immediately proceeded by '\':
fn split_on_unescaped_ampersand(str: &str) -> Vec<&str> {
    if str.is_empty() {
        return Vec::new();
    }

    let mut result = Vec::new();
    let mut start = 0;
    let bytes = str.as_bytes();

    for i in 0..bytes.len() {
        if bytes[i] == b'&' && (i == 0 || bytes[i - 1] != b'\\') {
            result.push(&str[start..i]);
            start = i + 1;
        }
    }

    result.push(&str[start..]);

    result
}

#[test]
fn test_split_on_unescaped_ampersand() {
    assert_eq!(split_on_unescaped_ampersand(""), Vec::<&str>::default());
    assert_eq!(split_on_unescaped_ampersand("foo"), vec!["foo"]);
    assert_eq!(split_on_unescaped_ampersand("a&b&c"), vec!["a", "b", "c"]);
    assert_eq!(split_on_unescaped_ampersand(r"a\&b&c"), vec![r"a\&b", "c"]);
    assert_eq!(
        split_on_unescaped_ampersand(r"a&b\&c&d"),
        vec!["a", r"b\&c", "d"]
    );
    assert_eq!(split_on_unescaped_ampersand(r"a\&b\&c"), vec![r"a\&b\&c"]);
    assert_eq!(split_on_unescaped_ampersand("a&&b"), vec!["a", "", "b"]);
    assert_eq!(split_on_unescaped_ampersand(r"a\&&b"), vec![r"a\&", "b"]);
}

/// Split a string at the first '=' that is not immediately preceded by '\'.
/// Returns `None` if no unescaped equals sign is found.
fn split_at_first_unescaped_equals(s: &str) -> Option<(&str, &str)> {
    let bytes = s.as_bytes();

    for i in 0..bytes.len() {
        if bytes[i] == b'=' && (i == 0 || bytes[i - 1] != b'\\') {
            return Some((&s[0..i], &s[i + 1..]));
        }
    }

    None
}

#[test]
fn test_split_underscore() {
    let test_cases = [
        ("key=value", Some(("key", "value"))),
        ("no_equals", None),
        ("escaped\\=equals", None),
        (
            "key\\=with_escape=value",
            Some(("key\\=with_escape", "value")),
        ),
        ("=", Some(("", ""))),
    ];

    for (s, expected) in test_cases {
        assert_eq!(split_at_first_unescaped_equals(s), expected);
    }
}

#[test]
fn test_parse_fragment() {
    let test_cases = [
        ("", Fragment::default()),
        (
            "focus=/entity/path",
            Fragment {
                focus: Some("/entity/path".parse().unwrap()),
                when: None,
            },
        ),
        (
            "focus=/entity/path&when=log_time@2022-01-01T00:00:03.123456789Z",
            Fragment {
                focus: Some("/entity/path".parse().unwrap()),
                when: Some((
                    "log_time".into(),
                    "2022-01-01T00:00:03.123456789Z".parse().unwrap(),
                )),
            },
        ),
        (
            "when=log_time@2022-01-01T00:00:03.123456789Z",
            Fragment {
                focus: None,
                when: Some((
                    "log_time".into(),
                    "2022-01-01T00:00:03.123456789Z".parse().unwrap(),
                )),
            },
        ),
    ];

    for (string, fragment) in test_cases {
        assert_eq!(fragment.to_string(), string);
        assert_eq!(string.parse::<Fragment>().unwrap(), fragment);
    }
}