Skip to main content

geocoder_core/readers/
mod.rs

1//! Data sources converted into addok's document format.
2//!
3//! addok's own format and BANO are read line by line. Address registers
4//! (Luxembourg, Belgium) list one address per row: they are read whole and
5//! grouped into street, locality and municipality documents
6//! (see [`grouped`]).
7
8pub mod ban;
9pub mod bano;
10pub mod be;
11pub mod cedex;
12pub mod grouped;
13pub mod lu;
14
15use std::fs::File;
16use std::io::{BufReader, Read};
17use std::path::Path;
18
19use flate2::read::MultiGzDecoder;
20
21use crate::doc::Document;
22use crate::error::GeocoderError;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Source {
26    /// addok's own format, e.g. the BAN `adresses-addok-*.ndjson.gz` exports.
27    Addok,
28    /// BANO (`bano-XX.json.gz`), OpenStreetMap based.
29    Bano,
30    /// Luxembourg's BD-Adresses (`addresses.csv`).
31    Lu,
32    /// Belgium's BeST Address (`openaddress-be*.zip`, one per region).
33    Be,
34}
35
36impl Source {
37    pub fn from_name(name: &str) -> Option<Self> {
38        match name {
39            "addok" | "ban" => Some(Self::Addok),
40            "bano" => Some(Self::Bano),
41            "lu" | "bd-adresses" => Some(Self::Lu),
42            "be" | "best" => Some(Self::Be),
43            _ => None,
44        }
45    }
46
47    pub fn name(self) -> &'static str {
48        match self {
49            Self::Addok => "addok",
50            Self::Bano => "bano",
51            Self::Lu => "lu",
52            Self::Be => "be",
53        }
54    }
55
56    /// One document per line, or a register to group.
57    pub fn is_line_based(self) -> bool {
58        matches!(self, Self::Addok | Self::Bano)
59    }
60
61    /// Parse one line of a line based source; `None` for blank lines.
62    pub fn parse(self, line: &str) -> Result<Option<Document>, GeocoderError> {
63        if line.trim().is_empty() {
64            return Ok(None);
65        }
66        match self {
67            Source::Addok => ban::parse_line(line).map(Some),
68            Source::Bano => bano::parse_line(line).map(Some),
69            Source::Lu | Source::Be => Err(GeocoderError::InvalidIndex(
70                "a register is not read line by line",
71            )),
72        }
73    }
74}
75
76/// Run `f` on each data file of `path`, decompressed: the file itself, or
77/// every entry of a `.zip`; `.gz` files are gunzipped.
78pub fn for_each_input(
79    path: &Path,
80    mut f: impl FnMut(&mut dyn Read) -> Result<(), GeocoderError>,
81) -> Result<(), GeocoderError> {
82    let name = path.to_string_lossy().to_lowercase();
83    let file = File::open(path)?;
84    if name.ends_with(".zip") {
85        let mut archive = zip::ZipArchive::new(file).map_err(zip_error)?;
86        for i in 0..archive.len() {
87            let entry = archive.by_index(i).map_err(zip_error)?;
88            if entry.is_dir() {
89                continue;
90            }
91            f(&mut BufReader::with_capacity(1 << 20, entry))?;
92        }
93        Ok(())
94    } else if name.ends_with(".gz") {
95        f(&mut BufReader::with_capacity(
96            1 << 20,
97            MultiGzDecoder::new(file),
98        ))
99    } else {
100        f(&mut BufReader::with_capacity(1 << 20, file))
101    }
102}
103
104fn zip_error(e: zip::result::ZipError) -> GeocoderError {
105    GeocoderError::Io(std::io::Error::other(e))
106}
107
108/// Drop a leading UTF-8 byte order mark.
109pub fn skip_bom<R: Read>(reader: R) -> impl Read {
110    let mut reader = BufReader::new(reader);
111    let mut bom = [0u8; 3];
112    let mut read = 0;
113    while read < 3 {
114        match reader.read(&mut bom[read..]) {
115            Ok(0) => break,
116            Ok(n) => read += n,
117            Err(_) => break,
118        }
119    }
120    let head = if bom[..read] == [0xEF, 0xBB, 0xBF] {
121        Vec::new()
122    } else {
123        bom[..read].to_vec()
124    };
125    std::io::Cursor::new(head).chain(reader)
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn skips_the_bom_only() {
134        let mut out = String::new();
135        skip_bom("\u{feff}a;b".as_bytes())
136            .read_to_string(&mut out)
137            .unwrap();
138        assert_eq!(out, "a;b");
139        out.clear();
140        skip_bom("ab".as_bytes()).read_to_string(&mut out).unwrap();
141        assert_eq!(out, "ab");
142    }
143}