rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
//! Modes, like `SUBURBAN`, and the product classes of RMV. A product class
//! is a bit; a search takes the sum of the classes it wants as `products`.

use crate::Error;

/// The modes and their classes. `BUS` has two: regional and city buses.
pub const MODES: &[(&str, u32)] = &[
    ("HIGHSPEED_RAIL", 1),
    ("LONG_DISTANCE", 2),
    ("REGIONAL_RAIL", 4),
    ("SUBURBAN", 8),
    ("SUBWAY", 16),
    ("TRAM", 32),
    ("BUS", 64 | 128),
    ("ODM", 512),
];

/// A mode for all trains: `HIGHSPEED_RAIL`, `LONG_DISTANCE`,
/// `REGIONAL_RAIL` and `SUBURBAN`.
pub const RAIL: (&str, u32) = ("RAIL", 1 | 2 | 4 | 8);

/// The mode of a product class no mode covers.
pub const OTHER: &str = "OTHER";

/// The mode of a class.
pub fn of_class(class: Option<u32>) -> &'static str {
    class
        .and_then(|class| {
            MODES
                .iter()
                .find(|(_, bits)| bits & class != 0)
                .map(|(name, _)| *name)
        })
        .unwrap_or(OTHER)
}

/// The modes of a sum of classes, like the products of a stop.
pub fn of_mask(mask: u32) -> Vec<String> {
    let known = MODES.iter().fold(0, |all, (_, bits)| all | bits);
    let mut modes: Vec<String> = MODES
        .iter()
        .filter(|(_, bits)| mask & bits != 0)
        .map(|(name, _)| (*name).to_owned())
        .collect();
    if mask & !known != 0 {
        modes.push(OTHER.to_owned());
    }
    modes
}

/// The `products` for `modes`, `None` for all. An unknown mode is an error.
pub fn products(modes: &[String]) -> Result<Option<u32>, Error> {
    let mut sum = 0;
    for mode in modes {
        let wanted = mode.trim().to_ascii_uppercase();
        let bits = MODES
            .iter()
            .chain([&RAIL])
            .find(|(name, _)| *name == wanted)
            .map(|(_, bits)| *bits)
            .ok_or_else(|| Error::BadRequest {
                message: format!("unknown mode {wanted:?}, known: {}", names().join(", ")),
            })?;
        sum |= bits;
    }
    Ok((sum != 0).then_some(sum))
}

/// The modes a search takes.
pub fn names() -> Vec<&'static str> {
    MODES.iter().chain([&RAIL]).map(|(name, _)| *name).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn modes(names: &[&str]) -> Vec<String> {
        names.iter().map(|name| (*name).to_owned()).collect()
    }

    #[test]
    fn names_the_classes() {
        assert_eq!(of_class(Some(8)), "SUBURBAN");
        assert_eq!(of_class(Some(32)), "TRAM");
        assert_eq!(of_class(Some(64)), "BUS");
        assert_eq!(of_class(Some(128)), "BUS");
        assert_eq!(of_class(Some(256)), OTHER);
        assert_eq!(of_class(None), OTHER);
    }

    #[test]
    fn lists_the_modes_of_a_stop() {
        assert_eq!(of_mask(8 | 32 | 128), modes(&["SUBURBAN", "TRAM", "BUS"]));
        assert_eq!(of_mask(256), modes(&[OTHER]));
        assert_eq!(of_mask(0), Vec::<String>::new());
    }

    #[test]
    fn sums_the_modes() {
        assert_eq!(products(&[]).unwrap(), None);
        assert_eq!(products(&modes(&["suburban", "BUS"])).unwrap(), Some(200));
        assert_eq!(products(&modes(&["RAIL", "SUBURBAN"])).unwrap(), Some(15));
        let error = products(&modes(&["FERRY"])).unwrap_err();
        assert_eq!(error.status(), "bad_request");
        assert!(error.to_string().contains("SUBWAY"), "{error}");
    }
}