sumo-types 0.3.0

Reads and writes SUMO (Eclipse SUMO) .net.xml, .rou.xml and .add.xml files as well-typed Rust structs
Documentation
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Conversion from layer 1 (the private `schema` module, generated by
//! xsd-parser from
//! the SUMO XSDs) to layer 2 ([`crate::routes::domain`]).
//!
//! Mirrors `net`'s own `schema_mapper` in spirit — parsing the few fields
//! SUMO only restricts with a text pattern or union, translating enums —
//! but is independent code: `routes` doesn't require `net` to be enabled,
//! so it can't reuse `net`'s conversions even for a shared SUMO primitive
//! like `boolType` would be (`colorType` and `departType`, the ones this
//! module actually needs, aren't used by `net` at all).

use super::domain::{
    Color, Depart, EdgeRef, NamedColor, Person, PersonId, Route, RouteId, Routes, VClass, Vehicle,
    VehicleId, VehicleType, VehicleTypeId, Walk,
};
use crate::schema;
use crate::sumo::{parse_finite, split_ids};
use crate::{Error, Result};
use uom::si::f64::{Length, Time, Velocity};
use uom::si::length::meter;
use uom::si::time::second;
use uom::si::velocity::meter_per_second;

/// Generates every mechanical conversion between [`NamedColor`] and SUMO's
/// own named-color spellings from one table, instead of hand-writing the
/// same 12-way correspondence three times over: the read direction from
/// `schema::ColorType6Type` (the proper, pattern-checked enum) below, the
/// [`named_color`] raw-string matcher `TryFrom<schema::ColorType> for Color`
/// needs *instead* of that enum (see that impl's own docs for why), and —
/// under `write`, so it lives next to the two read-direction conversions
/// rather than needing this same table a second time in `schema_writer` —
/// the reverse `NamedColor -> schema::ColorType6Type` `schema_writer::write`
/// needs.
///
/// `$spelling`'s aliases cover SUMO accepting both `"grey"` and `"gray"` for
/// the same color on read; [`NamedColor::Grey`] doesn't remember which one a
/// document used, so the generated write direction only ever produces the
/// first (canonical) spelling — same reasoning as [`crate::sumo::format_bool`]
/// always writing `"true"`/`"false"` regardless of which of SUMO's ten
/// spellings it read.
macro_rules! named_colors {
    ($($variant:ident: $spelling:ident $(| $alias:ident)* => $str:literal $(| $str_alias:literal)*),+ $(,)?) => {
        impl From<schema::ColorType6Type> for NamedColor {
            fn from(value: schema::ColorType6Type) -> Self {
                use schema::ColorType6Type as S;
                match value {
                    $(S::$spelling $(| S::$alias)* => NamedColor::$variant,)+
                }
            }
        }

        /// Matches a raw color string against SUMO's named-color spellings,
        /// independent of `schema::ColorType6Type`'s own enum matching — see
        /// the `TryFrom<schema::ColorType> for Color` impl below for why
        /// this crate can't just rely on that instead.
        fn named_color(raw: &str) -> Option<NamedColor> {
            Some(match raw {
                $($str $(| $str_alias)* => NamedColor::$variant,)+
                _ => return None,
            })
        }

        #[cfg(feature = "write")]
        impl From<&NamedColor> for schema::ColorType6Type {
            fn from(value: &NamedColor) -> Self {
                match value {
                    $(NamedColor::$variant => schema::ColorType6Type::$spelling,)+
                }
            }
        }
    };
}

named_colors! {
    Red: red => "red",
    Green: green => "green",
    Blue: blue => "blue",
    Yellow: yellow => "yellow",
    Cyan: cyan => "cyan",
    Magenta: magenta => "magenta",
    Orange: orange => "orange",
    White: white => "white",
    Black: black => "black",
    Grey: grey | gray => "grey" | "gray",
    Invisible: invisible => "invisible",
    Random: random => "random",
}

/// Parses `colorType`'s numeric form: `"r,g,b"` or `"r,g,b,a"` (`a` defaults
/// to `1.0` when omitted), in either of the two scales SUMO accepts — see
/// [`Color::Rgba`] for why they aren't told apart here.
impl TryFrom<&str> for Color {
    type Error = Error;

    fn try_from(raw: &str) -> Result<Self> {
        let parts = raw
            .split(',')
            .map(|part| parse_finite(part, "SUMO color component"))
            .collect::<Result<Vec<_>>>()?;

        match *parts.as_slice() {
            [r, g, b] => Ok(Color::Rgba { r, g, b, a: 1.0 }),
            [r, g, b, a] => Ok(Color::Rgba { r, g, b, a }),
            _ => Err(Error::InvalidColor {
                value: raw.to_owned(),
            }),
        }
    }
}

impl TryFrom<schema::ColorType> for Color {
    type Error = Error;

    /// `colorType`'s `xsd:union` declares its numeric member
    /// (`ColorType4Type`) before its named-color one (`ColorType6Type`),
    /// and xsd-parser's generated `DeserializeBytes for ColorType` tries
    /// union members in that same declaration order — but `ColorType4Type`
    /// is `types/base.xsd`'s `xsd:string`-restricted-by-pattern numeric
    /// form rendered as a bare, unpatterned `String` (same reason
    /// `floatType` arrives as text for [`crate::sumo::parse_finite`] to
    /// validate: xsd-parser doesn't enforce `xsd:pattern`). A bare `String`
    /// deserializes successfully from *any* text, so the union always
    /// resolves to `ColorType4`, even for `color="grey"` — `ColorType6`
    /// (the proper, pattern-checked enum) is never actually reached. Every
    /// `ColorType4(raw)` is therefore checked against the named spellings
    /// here before falling back to numeric parsing, recovering the
    /// distinction the generated union deserializer can't make.
    fn try_from(value: schema::ColorType) -> Result<Self> {
        match value {
            schema::ColorType::ColorType4(raw) => match named_color(&raw) {
                Some(named) => Ok(Color::Named(named)),
                None => Color::try_from(raw.as_str()),
            },
            schema::ColorType::ColorType6(named) => Ok(Color::Named(NamedColor::from(named))),
        }
    }
}

/// Parses `timeType`'s text-pattern union member: `"H:M:S"` or
/// `"H:M:S:MS"`.
fn parse_clock_time(raw: &str) -> Result<Time> {
    let parts = raw
        .split(':')
        .map(|part| parse_finite(part, "SUMO clock time component"))
        .collect::<Result<Vec<_>>>()?;

    let seconds = match *parts.as_slice() {
        [h, m, s] => h * 3600.0 + m * 60.0 + s,
        [h, m, s, ms] => h * 3600.0 + m * 60.0 + s + ms / 1000.0,
        _ => {
            return Err(Error::InvalidClockTime {
                value: raw.to_owned(),
            });
        }
    };
    Ok(Time::new::<second>(seconds))
}

/// `schema::SumoTimeType` is `types/base.xsd`'s `timeType`, renamed at
/// build time (see `RENAMED_TYPES` in `build.rs`) to avoid colliding with
/// xsd-parser's generated `TimeType` primitive.
impl TryFrom<schema::SumoTimeType> for Time {
    type Error = Error;

    fn try_from(value: schema::SumoTimeType) -> Result<Self> {
        match value {
            schema::SumoTimeType::nonNegativeFloatType(seconds) => {
                Ok(Time::new::<second>(f64::from(seconds)))
            }
            schema::SumoTimeType::SumoTimeType9(raw) => parse_clock_time(&raw),
        }
    }
}

/// Matches a raw `sumoTimeType`/`SumoTimeType9` string against
/// `departType`'s trigger keywords, independent of `DepartType13Type`'s own
/// enum matching — see the `TryFrom<schema::DepartType> for Depart` impl
/// below for why this crate can't just rely on that instead.
fn depart_trigger(raw: &str) -> Option<Depart> {
    Some(match raw {
        "triggered" => Depart::Triggered,
        "containerTriggered" => Depart::ContainerTriggered,
        "split" => Depart::Split,
        "begin" => Depart::Begin,
        _ => return None,
    })
}

impl TryFrom<schema::DepartType> for Depart {
    type Error = Error;

    /// Same union-priority problem as `colorType`'s conversion above, one
    /// level deeper: `departType`'s first member, `sumoTimeType`
    /// (`timeType`), is itself a union whose second member
    /// (`SumoTimeType9`, `timeType`'s `"H:M:S"` text pattern) is an
    /// unpatterned `String` — so it absorbs `"triggered"`, `"begin"`, and
    /// the rest of `DepartType13Type`'s keywords before the outer union
    /// ever reaches that branch. Every `SumoTimeType9(raw)` is checked
    /// against those keywords via [`depart_trigger`] first, and only handed
    /// to [`Time`]'s own conversion (as clock-time text) when it doesn't
    /// match one.
    fn try_from(value: schema::DepartType) -> Result<Self> {
        if let schema::DepartType::sumoTimeType(schema::SumoTimeType::SumoTimeType9(raw)) = &value {
            if let Some(depart) = depart_trigger(raw) {
                return Ok(depart);
            }
        }

        match value {
            schema::DepartType::sumoTimeType(time) => Ok(Depart::Time(Time::try_from(time)?)),
            schema::DepartType::DepartType13(trigger) => {
                use schema::DepartType13Type as S;
                Ok(match trigger {
                    S::triggered => Depart::Triggered,
                    S::containerTriggered => Depart::ContainerTriggered,
                    S::split => Depart::Split,
                    S::begin => Depart::Begin,
                })
            }
        }
    }
}

impl TryFrom<schema::RouteType> for Route {
    type Error = Error;

    fn try_from(value: schema::RouteType) -> Result<Self> {
        Ok(Route {
            id: RouteId(value.id),
            edges: value.edges.as_deref().map(split_ids),
            color: value.color.map(Color::try_from).transpose()?,
        })
    }
}

impl TryFrom<schema::VTypeType> for VehicleType {
    type Error = Error;

    fn try_from(value: schema::VTypeType) -> Result<Self> {
        Ok(VehicleType {
            id: VehicleTypeId(value.id),
            vehicle_class: value
                .v_class
                .map(|raw| raw.parse::<VClass>().map_err(|_| Error::InvalidVehicleClass { value: raw }))
                .transpose()?,
            length: value.length.map(|l| Length::new::<meter>(f64::from(l))),
            max_speed: value
                .max_speed
                .map(|s| Velocity::new::<meter_per_second>(f64::from(s))),
            color: value.color.map(Color::try_from).transpose()?,
        })
    }
}

/// Converts SUMO's `vehicle` element (`schema::VehicleType`, an actual
/// vehicle instance) into [`Vehicle`] — not to be confused with
/// [`VehicleType`] (this crate's mapping of SUMO's `vType`/`vTypeType`, a
/// vehicle *class* definition). The naming clash is SUMO's own.
impl TryFrom<schema::VehicleType> for Vehicle {
    type Error = Error;

    fn try_from(value: schema::VehicleType) -> Result<Self> {
        Ok(Vehicle {
            id: VehicleId(value.id),
            vehicle_type: value.type_.map(VehicleTypeId),
            route: value.route.map(RouteId),
            depart: Depart::try_from(value.depart)?,
            color: value.color.map(Color::try_from).transpose()?,
        })
    }
}

/// Infallible: every attribute [`Walk`] reads from is a plain optional
/// string or string list, none of them SUMO's own restricted
/// number/enum/color syntax the way `Route`/`Vehicle`'s other attributes
/// are — nothing here can fail to parse. See [`Walk`]'s own docs for why
/// `edges` wins when a document sets it alongside `from`/`to`.
impl From<schema::PersonBaseTypeWalk> for Walk {
    fn from(value: schema::PersonBaseTypeWalk) -> Self {
        match (value.edges.as_deref().map(split_ids), value.from, value.to) {
            (Some(edges), ..) => Walk::Edges(edges),
            (None, Some(from), Some(to)) => Walk::Endpoints { from: EdgeRef(from), to: EdgeRef(to) },
            (None, _, _) => Walk::Unknown,
        }
    }
}

/// Keeps only `walk` children — `personTrip`/`ride`/`stop` are silently
/// dropped, same as [`Routes`] itself drops whole element kinds (see the
/// `domain` module docs, and this function's own for why).
impl From<schema::PersonType> for Person {
    fn from(value: schema::PersonType) -> Self {
        let walks = value
            .content
            .into_iter()
            .filter_map(|item| match item {
                schema::PersonTypeContent::walk(walk) => Some(Walk::from(walk)),
                _ => None,
            })
            .collect();

        Person {
            id: PersonId(value.id),
            walks,
        }
    }
}

impl TryFrom<schema::RoutesType> for Routes {
    type Error = Error;

    fn try_from(value: schema::RoutesType) -> Result<Self> {
        let mut routes = Routes::default();

        for item in value.content {
            match item {
                schema::RoutesTypeContent::vType(Some(v_type)) => {
                    routes.vehicle_types.push(VehicleType::try_from(v_type)?);
                }
                schema::RoutesTypeContent::route(Some(route)) => {
                    routes.routes.push(Route::try_from(route)?);
                }
                schema::RoutesTypeContent::vehicle(Some(vehicle)) => {
                    routes.vehicles.push(Vehicle::try_from(vehicle)?);
                }
                schema::RoutesTypeContent::person(Some(person)) => {
                    routes.persons.push(Person::from(person));
                }
                // Every other `routesType` element kind (`flow`, `trip`,
                // `personFlow`, `container`, `containerFlow`, `interval`,
                // `include`, `vTypeDistribution`, `routeDistribution`), and
                // any of the 4 above that showed up as `None` (shouldn't
                // happen per the XSD, but xsd-parser models each choice
                // branch as optional) — not modeled yet, see the `domain`
                // module docs.
                _ => {}
            }
        }

        Ok(routes)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::routes::domain::EdgeRef;

    #[test]
    fn reads_depart_triggers_even_though_the_union_always_offers_them_as_clock_time_text_first() {
        // Same regression shape as the named-color test below, one union
        // level deeper: `sumoTimeType`'s own `SumoTimeType9` text-pattern
        // member is what actually absorbs `"begin"` et al. before
        // `DepartType13` is ever reached.
        let raw = schema::DepartType::sumoTimeType(schema::SumoTimeType::SumoTimeType9(
            "begin".to_string(),
        ));
        assert!(matches!(Depart::try_from(raw).unwrap(), Depart::Begin));
    }

    #[test]
    fn reads_a_named_color_even_though_the_union_always_offers_it_as_color_type_4_first() {
        // Regression test: `schema::ColorType`'s generated union
        // deserializer always resolves to `ColorType4` (an unpatterned
        // `String`, so it "matches" anything) and never actually reaches
        // `ColorType6`, even for a real named color — see the `TryFrom`
        // impl's own doc comment. Exercise the full path a real `.rou.xml`
        // takes, not just the enum conversion directly.
        for raw in ["red", "grey", "gray", "invisible", "random"] {
            let color = Color::try_from(schema::ColorType::ColorType4(raw.to_string())).unwrap();
            assert!(
                matches!(color, Color::Named(_)),
                "{raw:?} should read as a named color, got {color:?}"
            );
        }
    }

    #[test]
    fn parses_numeric_rgb_color_defaulting_alpha() {
        let color = Color::try_from("0.8,0.1,0.1").unwrap();
        assert_eq!(
            color,
            Color::Rgba {
                r: 0.8,
                g: 0.1,
                b: 0.1,
                a: 1.0
            }
        );
    }

    #[test]
    fn parses_numeric_rgba_color() {
        let color = Color::try_from("0.8,0.1,0.1,0.5").unwrap();
        assert_eq!(
            color,
            Color::Rgba {
                r: 0.8,
                g: 0.1,
                b: 0.1,
                a: 0.5
            }
        );
    }

    #[test]
    fn rejects_malformed_color() {
        assert!(Color::try_from("not-a-color").is_err());
        assert!(Color::try_from("1,2").is_err());
        // A `NaN` component would poison whatever the color is blended
        // into, the same way a `NaN` coordinate poisons a position.
        assert!(Color::try_from("NaN,0,0").is_err());
    }

    #[test]
    fn maps_both_spellings_of_grey_to_the_same_named_color() {
        assert_eq!(
            NamedColor::from(schema::ColorType6Type::grey),
            NamedColor::Grey
        );
        assert_eq!(
            NamedColor::from(schema::ColorType6Type::gray),
            NamedColor::Grey
        );
    }

    #[test]
    fn parses_clock_time_without_milliseconds() {
        use uom::si::time::second;
        let time = parse_clock_time("1:02:03").unwrap();
        assert_eq!(time.get::<second>(), 3723.0);
    }

    #[test]
    fn parses_clock_time_with_milliseconds() {
        use uom::si::time::second;
        let time = parse_clock_time("0:00:01:500").unwrap();
        assert_eq!(time.get::<second>(), 1.5);
    }

    #[test]
    fn rejects_malformed_clock_time() {
        assert!(parse_clock_time("not-a-time").is_err());
        assert!(parse_clock_time("1:02").is_err());
        assert!(parse_clock_time("NaN:02:03").is_err());
    }

    #[test]
    fn splits_whitespace_separated_edge_list() {
        assert_eq!(
            split_ids::<EdgeRef>("e0 e1 e2"),
            vec![
                EdgeRef("e0".into()),
                EdgeRef("e1".into()),
                EdgeRef("e2".into())
            ]
        );
    }
}