use crate::Error;
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),
];
pub const RAIL: (&str, u32) = ("RAIL", 1 | 2 | 4 | 8);
pub const OTHER: &str = "OTHER";
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)
}
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
}
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))
}
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}");
}
}