1use std::collections::{BTreeMap, BTreeSet};
10use std::io::{Read, Write};
11
12use flate2::Compression;
13use flate2::read::ZlibDecoder;
14use flate2::write::ZlibEncoder;
15
16use crate::error::GeocoderError;
17
18const MAX_TABLE_BYTES: u64 = 16 << 20;
20
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
23pub struct CedexTable {
24 codes: BTreeMap<String, Vec<String>>,
25 localities: BTreeMap<String, Vec<String>>,
26}
27
28impl CedexTable {
29 pub fn by_code(&self, code: &str) -> &[String] {
31 self.codes.get(code).map_or(&[], Vec::as_slice)
32 }
33
34 pub fn by_locality(&self, locality: &str) -> &[String] {
37 self.localities
38 .get(&locality_key(locality))
39 .map_or(&[], Vec::as_slice)
40 }
41
42 pub fn codes(&self) -> usize {
43 self.codes.len()
44 }
45
46 pub fn localities(&self) -> usize {
47 self.localities.len()
48 }
49
50 pub fn is_empty(&self) -> bool {
51 self.codes.is_empty()
52 }
53
54 pub fn to_bytes(&self) -> Result<Vec<u8>, GeocoderError> {
57 let mut out = ZlibEncoder::new(Vec::new(), Compression::best());
58 for (code, insee) in &self.codes {
59 writeln!(out, "{code} {}", insee.join(" "))?;
60 }
61 for (locality, insee) in &self.localities {
62 writeln!(out, "={locality}\t{}", insee.join(" "))?;
63 }
64 Ok(out.finish()?)
65 }
66
67 pub fn from_bytes(bytes: &[u8]) -> Result<Self, GeocoderError> {
69 let mut text = String::new();
70 ZlibDecoder::new(bytes)
71 .take(MAX_TABLE_BYTES + 1)
72 .read_to_string(&mut text)?;
73 if text.len() as u64 > MAX_TABLE_BYTES {
74 return Err(GeocoderError::InvalidIndex("postal table too large"));
75 }
76 let mut table = Self::default();
77 for line in text.lines() {
78 if let Some(rest) = line.strip_prefix('=') {
79 let Some((locality, insee)) = rest.split_once('\t') else {
80 continue;
81 };
82 table.localities.insert(locality.to_string(), words(insee));
83 } else if let Some((code, insee)) = line.split_once(' ') {
84 table.codes.insert(code.to_string(), words(insee));
85 }
86 }
87 Ok(table)
88 }
89}
90
91fn words(text: &str) -> Vec<String> {
92 text.split_whitespace().map(str::to_string).collect()
93}
94
95#[derive(Debug, Default)]
97pub struct CedexTableBuilder {
98 codes: BTreeMap<String, BTreeSet<String>>,
99 localities: BTreeMap<String, BTreeSet<String>>,
100}
101
102impl CedexTableBuilder {
103 pub fn new() -> Self {
104 Self::default()
105 }
106
107 pub fn add(&mut self, code: &str, label: &str, insee: &str) -> bool {
112 let (code, insee) = (code.trim(), insee.trim().to_uppercase());
113 let valid_code = code.len() == 5 && code.bytes().all(|b| b.is_ascii_digit());
114 let valid_insee = insee.len() == 5
115 && insee
116 .bytes()
117 .all(|b| b.is_ascii_digit() || b == b'A' || b == b'B');
118 if !valid_code || !valid_insee || department(code) != department(&insee) {
119 return false;
120 }
121 self.codes
122 .entry(code.to_string())
123 .or_default()
124 .insert(insee);
125 let locality = locality_key(label);
126 if !locality.is_empty() {
127 self.localities
128 .entry(locality)
129 .or_default()
130 .insert(code.to_string());
131 }
132 true
133 }
134
135 pub fn codes(&self) -> usize {
136 self.codes.len()
137 }
138
139 pub fn build(self) -> CedexTable {
141 let localities = self
142 .localities
143 .iter()
144 .map(|(locality, codes)| {
145 let insee: BTreeSet<&String> = codes
146 .iter()
147 .filter_map(|c| self.codes.get(c))
148 .flatten()
149 .collect();
150 (
151 locality.clone(),
152 insee.into_iter().cloned().collect::<Vec<_>>(),
153 )
154 })
155 .collect();
156 CedexTable {
157 codes: self
158 .codes
159 .into_iter()
160 .map(|(code, insee)| (code, insee.into_iter().collect()))
161 .collect(),
162 localities,
163 }
164 }
165}
166
167fn department(code: &str) -> &str {
170 if code.starts_with("97") || code.starts_with("98") {
171 &code[..3]
172 } else if code.starts_with("2A") || code.starts_with("2B") {
173 "20"
174 } else {
175 &code[..2]
176 }
177}
178
179pub fn locality_key(label: &str) -> String {
183 let upper = crate::text::ascii(label).to_uppercase();
184 let mut words = Vec::new();
185 for word in upper
186 .split(|c: char| !c.is_ascii_alphanumeric())
187 .filter(|w| !w.is_empty())
188 {
189 match word {
190 "CEDEX" => break,
191 "ST" => words.push("SAINT"),
192 "STE" => words.push("SAINTE"),
193 w => words.push(w),
194 }
195 }
196 words.join(" ")
197}
198
199pub fn is_cedex(label: &str) -> bool {
201 crate::text::ascii(label)
202 .to_uppercase()
203 .split(|c: char| !c.is_ascii_alphanumeric())
204 .any(|w| w == "CEDEX")
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210
211 fn table() -> CedexTable {
212 let mut b = CedexTableBuilder::new();
213 assert!(b.add("92074", "PARIS LA DEFENSE CEDEX", "92062"));
214 assert!(b.add("92081", "Paris-La-Défense Cedex 08", "92026"));
215 assert!(!b.add("92081", "PARIS LA DEFENSE CEDEX", "75112"));
217 assert!(b.add("20186", "AJACCIO CEDEX 2", "2A004"));
218 assert!(!b.add("9207", "X CEDEX", "92062"));
219 b.build()
220 }
221
222 #[test]
223 fn codes_and_localities() {
224 let t = table();
225 assert_eq!(t.by_code("92074"), ["92062"]);
226 assert_eq!(t.by_code("92081"), ["92026"]);
227 assert_eq!(t.by_locality("Paris La Défense"), ["92026", "92062"]);
228 assert_eq!(t.by_code("20186"), ["2A004"]);
229 assert!(t.by_code("99999").is_empty());
230 }
231
232 #[test]
233 fn round_trip() {
234 let t = table();
235 assert_eq!(CedexTable::from_bytes(&t.to_bytes().unwrap()).unwrap(), t);
236 }
237
238 #[test]
239 fn locality_keys() {
240 assert_eq!(
241 locality_key("Saint-Quentin-en-Yvelines Cedex 3"),
242 locality_key("ST QUENTIN EN YVELINES")
243 );
244 assert_eq!(locality_key("Paris-La-Défense Cedex"), "PARIS LA DEFENSE");
245 assert!(is_cedex("Cannes Cedex") && !is_cedex("Cedexiens"));
246 }
247}