rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
//! From what the caller typed to a stop ID: an ID is used as it is, a name
//! only if it names one stop. A wrong stop gives wrong connections that look
//! right, so a doubtful name is an error with the candidates, never a guess.
//!
//! Only the names count: a match whose name is the query (ignoring case,
//! punctuation and spacing), else the only match that contains every word
//! of the query. Matches with the same name count as one.

use hafas::StopLocation;

use crate::Error;
use crate::model::StopMatch;

/// The most candidates an [`Error::AmbiguousStop`] lists.
pub const MAX_CANDIDATES: usize = 10;

/// Whether the input is a stop ID rather than a name: an external ID like
/// `3000010`, or a HAFAS ID like `A=1@O=Frankfurt (Main) Hbf@L=3000010@`.
pub fn is_stop_id(input: &str) -> bool {
    let input = input.trim();
    (!input.is_empty() && input.chars().all(|c| c.is_ascii_digit()))
        || input.starts_with("A=")
        || input.contains("@L=")
}

/// Coordinates `LAT,LON`, which a trip search accepts as a place.
pub fn coordinates(input: &str) -> Option<(f64, f64)> {
    let (lat, lon) = input.split_once(',')?;
    let lat: f64 = lat.trim().parse().ok()?;
    let lon: f64 = lon.trim().parse().ok()?;
    ((-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&lon)).then_some((lat, lon))
}

/// The stop `query` names among the `stops` found for it.
pub fn choose<'a>(query: &str, stops: &[&'a StopLocation]) -> Result<&'a StopLocation, Error> {
    if stops.is_empty() {
        return Err(Error::StopNotFound {
            query: query.to_owned(),
        });
    }
    let wanted = normalize(query);
    // Matches with the name of the query all have the same name.
    if let Some(found) = stops.iter().find(|found| normalize(&found.name) == wanted) {
        return Ok(found);
    }
    let words: Vec<&str> = wanted.split(' ').collect();
    let containing: Vec<&StopLocation> = stops
        .iter()
        .copied()
        .filter(|found| {
            let name = normalize(&found.name);
            let name: Vec<&str> = name.split(' ').collect();
            words.iter().all(|word| name.contains(word))
        })
        .collect();
    if let Some(found) = single(&containing) {
        return Ok(found);
    }
    Err(Error::AmbiguousStop {
        query: query.to_owned(),
        candidates: stops
            .iter()
            .copied()
            .take(MAX_CANDIDATES)
            .map(StopMatch::from)
            .collect(),
    })
}

/// The first match, if all have the same name.
fn single<'a>(matches: &[&'a StopLocation]) -> Option<&'a StopLocation> {
    let first = *matches.first()?;
    let key = normalize(&first.name);
    matches
        .iter()
        .all(|found| normalize(&found.name) == key)
        .then_some(first)
}

/// Lowercase letters and digits, words separated by one space.
fn normalize(text: &str) -> String {
    text.chars()
        .map(|c| {
            if c.is_alphanumeric() {
                c.to_lowercase().next().unwrap_or(c)
            } else {
                ' '
            }
        })
        .collect::<String>()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

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

    fn stop(id: &str, name: &str) -> StopLocation {
        StopLocation {
            id: format!("A=1@O={name}@L={id}@"),
            ext_id: id.into(),
            name: name.into(),
            ..StopLocation::default()
        }
    }

    fn chosen(query: &str, stops: &[StopLocation]) -> String {
        let stops: Vec<&StopLocation> = stops.iter().collect();
        choose(query, &stops).unwrap().ext_id.clone()
    }

    fn candidates(query: &str, stops: &[StopLocation]) -> Vec<String> {
        let stops: Vec<&StopLocation> = stops.iter().collect();
        let error = choose(query, &stops).unwrap_err();
        assert_eq!(error.status(), "ambiguous_stop");
        error.body().candidates.into_iter().map(|c| c.id).collect()
    }

    #[test]
    fn tells_ids_from_names() {
        assert!(is_stop_id("3000010"));
        assert!(is_stop_id(" 3000010 "));
        assert!(is_stop_id(
            "A=1@O=Frankfurt (Main) Hbf@X=8662653@L=3000010@"
        ));
        assert!(is_stop_id("A=1@L=3000010@"));
        assert!(!is_stop_id("Hauptwache"));
        assert!(!is_stop_id("Frankfurt (Main) Hbf"));
        assert!(!is_stop_id("Haltestelle 7"));
        assert!(!is_stop_id(""));
    }

    #[test]
    fn reads_coordinates() {
        assert_eq!(coordinates("50.11, 8.68"), Some((50.11, 8.68)));
        assert_eq!(coordinates("-33.9,151.2"), Some((-33.9, 151.2)));
        assert_eq!(coordinates("91,0"), None);
        assert_eq!(coordinates("0,181"), None);
        assert_eq!(coordinates("Hauptwache"), None);
        assert_eq!(coordinates("a,1"), None);
        assert_eq!(coordinates("1,b"), None);
    }

    #[test]
    fn takes_the_exact_name() {
        let stops = [
            stop("1", "Frankfurt (Main) Hauptwache"),
            stop("2", "Frankfurt (Main) Freßgass/Hauptwache"),
        ];
        assert_eq!(chosen("frankfurt main  HAUPTWACHE", &stops), "1");
    }

    #[test]
    fn the_same_name_twice_counts_as_one() {
        let stops = [stop("1", "Hauptwache"), stop("2", "Hauptwache")];
        assert_eq!(chosen("Hauptwache", &stops), "1");
    }

    #[test]
    fn takes_the_only_match_with_every_word() {
        let stops = [
            stop("1", "Frankfurt (Main) Hauptbahnhof"),
            stop("2", "Frankfurt (Oder) Bahnhof"),
        ];
        assert_eq!(chosen("Frankfurt Hauptbahnhof", &stops), "1");
    }

    #[test]
    fn several_matches_with_every_word_are_ambiguous() {
        let stops = [
            stop("1", "Frankfurt (Main) Hauptwache"),
            stop("2", "Frankfurt (Main) Freßgass/Hauptwache"),
        ];
        assert_eq!(candidates("Hauptwache", &stops), ["1", "2"]);
    }

    #[test]
    fn a_single_fuzzy_match_is_not_taken() {
        let stops = [stop("1", "Hauptbahnhof")];
        assert_eq!(candidates("Hauptbanhof", &stops), ["1"]);
    }

    #[test]
    fn lists_at_most_ten_candidates() {
        let stops: Vec<StopLocation> = (0..15)
            .map(|i| stop(&i.to_string(), &format!("Bahnhof {i}")))
            .collect();
        assert_eq!(candidates("Bahnhof", &stops).len(), MAX_CANDIDATES);
    }

    #[test]
    fn nothing_found_is_not_found() {
        assert!(matches!(
            choose("Hauptwache", &[]),
            Err(Error::StopNotFound { .. })
        ));
    }
}