use hafas::StopLocation;
use crate::Error;
use crate::model::StopMatch;
pub const MAX_CANDIDATES: usize = 10;
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=")
}
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))
}
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);
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(),
})
}
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)
}
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 { .. })
));
}
}