geocoder_core/readers/
mod.rs1pub mod ban;
9pub mod bano;
10pub mod be;
11pub mod grouped;
12pub mod lu;
13
14use std::fs::File;
15use std::io::{BufReader, Read};
16use std::path::Path;
17
18use flate2::read::MultiGzDecoder;
19
20use crate::doc::Document;
21use crate::error::GeocoderError;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Source {
25 Addok,
27 Bano,
29 Lu,
31 Be,
33}
34
35impl Source {
36 pub fn from_name(name: &str) -> Option<Self> {
37 match name {
38 "addok" | "ban" => Some(Self::Addok),
39 "bano" => Some(Self::Bano),
40 "lu" | "bd-adresses" => Some(Self::Lu),
41 "be" | "best" => Some(Self::Be),
42 _ => None,
43 }
44 }
45
46 pub fn name(self) -> &'static str {
47 match self {
48 Self::Addok => "addok",
49 Self::Bano => "bano",
50 Self::Lu => "lu",
51 Self::Be => "be",
52 }
53 }
54
55 pub fn is_line_based(self) -> bool {
57 matches!(self, Self::Addok | Self::Bano)
58 }
59
60 pub fn parse(self, line: &str) -> Result<Option<Document>, GeocoderError> {
62 if line.trim().is_empty() {
63 return Ok(None);
64 }
65 match self {
66 Source::Addok => ban::parse_line(line).map(Some),
67 Source::Bano => bano::parse_line(line).map(Some),
68 Source::Lu | Source::Be => Err(GeocoderError::InvalidIndex(
69 "a register is not read line by line",
70 )),
71 }
72 }
73}
74
75pub fn for_each_input(
78 path: &Path,
79 mut f: impl FnMut(&mut dyn Read) -> Result<(), GeocoderError>,
80) -> Result<(), GeocoderError> {
81 let name = path.to_string_lossy().to_lowercase();
82 let file = File::open(path)?;
83 if name.ends_with(".zip") {
84 let mut archive = zip::ZipArchive::new(file).map_err(zip_error)?;
85 for i in 0..archive.len() {
86 let entry = archive.by_index(i).map_err(zip_error)?;
87 if entry.is_dir() {
88 continue;
89 }
90 f(&mut BufReader::with_capacity(1 << 20, entry))?;
91 }
92 Ok(())
93 } else if name.ends_with(".gz") {
94 f(&mut BufReader::with_capacity(
95 1 << 20,
96 MultiGzDecoder::new(file),
97 ))
98 } else {
99 f(&mut BufReader::with_capacity(1 << 20, file))
100 }
101}
102
103fn zip_error(e: zip::result::ZipError) -> GeocoderError {
104 GeocoderError::Io(std::io::Error::other(e))
105}
106
107pub fn skip_bom<R: Read>(reader: R) -> impl Read {
109 let mut reader = BufReader::new(reader);
110 let mut bom = [0u8; 3];
111 let mut read = 0;
112 while read < 3 {
113 match reader.read(&mut bom[read..]) {
114 Ok(0) => break,
115 Ok(n) => read += n,
116 Err(_) => break,
117 }
118 }
119 let head = if bom[..read] == [0xEF, 0xBB, 0xBF] {
120 Vec::new()
121 } else {
122 bom[..read].to_vec()
123 };
124 std::io::Cursor::new(head).chain(reader)
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130
131 #[test]
132 fn skips_the_bom_only() {
133 let mut out = String::new();
134 skip_bom("\u{feff}a;b".as_bytes())
135 .read_to_string(&mut out)
136 .unwrap();
137 assert_eq!(out, "a;b");
138 out.clear();
139 skip_bom("ab".as_bytes()).read_to_string(&mut out).unwrap();
140 assert_eq!(out, "ab");
141 }
142}