Skip to main content

rmv_core/
modes.rs

1//! Modes, like `SUBURBAN`, and the product classes of RMV. A product class
2//! is a bit; a search takes the sum of the classes it wants as `products`.
3
4use crate::Error;
5
6/// The modes and their classes. `BUS` has two: regional and city buses.
7pub const MODES: &[(&str, u32)] = &[
8    ("HIGHSPEED_RAIL", 1),
9    ("LONG_DISTANCE", 2),
10    ("REGIONAL_RAIL", 4),
11    ("SUBURBAN", 8),
12    ("SUBWAY", 16),
13    ("TRAM", 32),
14    ("BUS", 64 | 128),
15    ("ODM", 512),
16];
17
18/// A mode for all trains: `HIGHSPEED_RAIL`, `LONG_DISTANCE`,
19/// `REGIONAL_RAIL` and `SUBURBAN`.
20pub const RAIL: (&str, u32) = ("RAIL", 1 | 2 | 4 | 8);
21
22/// The mode of a product class no mode covers.
23pub const OTHER: &str = "OTHER";
24
25/// The mode of a class.
26pub fn of_class(class: Option<u32>) -> &'static str {
27    class
28        .and_then(|class| {
29            MODES
30                .iter()
31                .find(|(_, bits)| bits & class != 0)
32                .map(|(name, _)| *name)
33        })
34        .unwrap_or(OTHER)
35}
36
37/// The modes of a sum of classes, like the products of a stop.
38pub fn of_mask(mask: u32) -> Vec<String> {
39    let known = MODES.iter().fold(0, |all, (_, bits)| all | bits);
40    let mut modes: Vec<String> = MODES
41        .iter()
42        .filter(|(_, bits)| mask & bits != 0)
43        .map(|(name, _)| (*name).to_owned())
44        .collect();
45    if mask & !known != 0 {
46        modes.push(OTHER.to_owned());
47    }
48    modes
49}
50
51/// The `products` for `modes`, `None` for all. An unknown mode is an error.
52pub fn products(modes: &[String]) -> Result<Option<u32>, Error> {
53    let mut sum = 0;
54    for mode in modes {
55        let wanted = mode.trim().to_ascii_uppercase();
56        let bits = MODES
57            .iter()
58            .chain([&RAIL])
59            .find(|(name, _)| *name == wanted)
60            .map(|(_, bits)| *bits)
61            .ok_or_else(|| Error::BadRequest {
62                message: format!("unknown mode {wanted:?}, known: {}", names().join(", ")),
63            })?;
64        sum |= bits;
65    }
66    Ok((sum != 0).then_some(sum))
67}
68
69/// The modes a search takes.
70pub fn names() -> Vec<&'static str> {
71    MODES.iter().chain([&RAIL]).map(|(name, _)| *name).collect()
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    fn modes(names: &[&str]) -> Vec<String> {
79        names.iter().map(|name| (*name).to_owned()).collect()
80    }
81
82    #[test]
83    fn names_the_classes() {
84        assert_eq!(of_class(Some(8)), "SUBURBAN");
85        assert_eq!(of_class(Some(32)), "TRAM");
86        assert_eq!(of_class(Some(64)), "BUS");
87        assert_eq!(of_class(Some(128)), "BUS");
88        assert_eq!(of_class(Some(256)), OTHER);
89        assert_eq!(of_class(None), OTHER);
90    }
91
92    #[test]
93    fn lists_the_modes_of_a_stop() {
94        assert_eq!(of_mask(8 | 32 | 128), modes(&["SUBURBAN", "TRAM", "BUS"]));
95        assert_eq!(of_mask(256), modes(&[OTHER]));
96        assert_eq!(of_mask(0), Vec::<String>::new());
97    }
98
99    #[test]
100    fn sums_the_modes() {
101        assert_eq!(products(&[]).unwrap(), None);
102        assert_eq!(products(&modes(&["suburban", "BUS"])).unwrap(), Some(200));
103        assert_eq!(products(&modes(&["RAIL", "SUBURBAN"])).unwrap(), Some(15));
104        let error = products(&modes(&["FERRY"])).unwrap_err();
105        assert_eq!(error.status(), "bad_request");
106        assert!(error.to_string().contains("SUBWAY"), "{error}");
107    }
108}