geocoder_core/text/
synonyms.rs1use std::collections::HashMap;
2
3use super::Token;
4
5#[derive(Debug, Default, Clone)]
8pub struct Synonyms {
9 map: HashMap<String, String>,
10}
11
12impl Synonyms {
13 pub fn parse(source: &str) -> Self {
15 let mut map = HashMap::new();
16 for line in source.lines() {
17 if line.starts_with('#') {
18 continue;
19 }
20 let Some((synonyms, wanted)) = line.split_once("=>") else {
21 continue;
22 };
23 let wanted = wanted.trim();
24 for synonym in synonyms.split(',') {
25 let synonym = synonym.trim();
26 if !synonym.is_empty() {
27 map.insert(synonym.to_string(), wanted.to_string());
28 }
29 }
30 }
31 Self { map }
32 }
33
34 pub fn apply(&self, tokens: Vec<Token>) -> Vec<Token> {
37 let mut out = Vec::with_capacity(tokens.len());
38 for token in tokens {
39 let replacement = self
40 .map
41 .get(&token.value)
42 .map(String::as_str)
43 .unwrap_or(&token.value);
44 for (position, word) in replacement.split_whitespace().enumerate() {
45 out.push(token.with_value_at(word.to_string(), position));
46 }
47 }
48 out
49 }
50
51 pub fn get(&self, token: &str) -> Option<&str> {
52 self.map.get(token).map(String::as_str)
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59
60 #[test]
61 fn parses_addok_format() {
62 let s = Synonyms::parse("# comment\nbd,bld, bvd => boulevard\ncr => chemin rural\n");
63 assert_eq!(s.get("bld"), Some("boulevard"));
64 let tokens = s.apply(vec![Token::new("cr".into(), 0)]);
65 assert_eq!(
66 tokens.iter().map(|t| t.value.as_str()).collect::<Vec<_>>(),
67 ["chemin", "rural"]
68 );
69 }
70}