1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
//! Parsing utilities for postal addresses.
//!
//! # Examples
//!
//! ```
//! use rustpostal::{address, LibModules};
//! use rustpostal::error::RuntimeError;
//!
//! fn main() -> Result<(), RuntimeError> {
//!     let postal_module = LibModules::Address;
//!     postal_module.setup()?;
//!
//!     let address = "St Johns Centre, Rope Walk, Bedford, Bedfordshire, MK42 0XE, United Kingdom";
//!
//!     let labeled_tokens = address::parse_address(address, None, None)?;
//!
//!     for (label, token) in &labeled_tokens {
//!         println!("{}: {}", label, token);
//!     }
//!     Ok(())
//! }
//! ```
use std::collections::HashMap;
use std::ffi::{CStr, CString, NulError};
use std::slice::Iter;
use std::vec::IntoIter;

use crate::ffi;

/// Represents the parsing result.
#[derive(Clone, Default, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct AddressParserResponse {
    tokens: Vec<String>,
    labels: Vec<String>,
}

impl AddressParserResponse {
    /// Create a new value.
    pub fn new() -> AddressParserResponse {
        Default::default()
    }
}

impl IntoIterator for AddressParserResponse {
    type Item = (String, String);
    type IntoIter = std::iter::Zip<IntoIter<String>, IntoIter<String>>;

    /// Iterates over `(label, token)` pairs by consuming the value.
    fn into_iter(self) -> Self::IntoIter {
        self.labels.into_iter().zip(self.tokens.into_iter())
    }
}

impl<'a> IntoIterator for &'a AddressParserResponse {
    type Item = (&'a String, &'a String);
    type IntoIter = std::iter::Zip<Iter<'a, String>, Iter<'a, String>>;

    /// Iterates over `(label, token)` pairs.
    fn into_iter(self) -> Self::IntoIter {
        self.labels[..].iter().zip(self.tokens[..].iter())
    }
}

/// Parsing options.
#[derive(Clone, Default, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct AddressParserOptions {
    language: Option<CString>,
    country: Option<CString>,
}

impl AddressParserOptions {
    /// Create options for the address parser.
    ///
    /// # Examples
    ///
    /// ```
    /// use rustpostal::address;
    ///
    /// fn main() -> Result<(), std::ffi::NulError> {
    ///     let options = address::AddressParserOptions::new(Some("en"), Some("en"))?;
    ///     Ok(())
    /// }
    /// ```
    pub fn new(
        language: Option<&str>,
        country: Option<&str>,
    ) -> Result<AddressParserOptions, NulError> {
        let mut options = AddressParserOptions::default();
        if let Some(s) = language {
            let c_lang = CString::new(s)?;
            options.language = Some(c_lang);
        }
        if let Some(s) = country {
            let c_country = CString::new(s)?;
            options.country = Some(c_country);
        }
        Ok(options)
    }

    /// Get the language option.
    pub fn language(&self) -> Option<&str> {
        if let Some(language) = &self.language {
            return Some(language.to_str().unwrap());
        }
        None
    }

    /// Get the country option.
    pub fn country(&self) -> Option<&str> {
        if let Some(country) = &self.country {
            return Some(country.to_str().unwrap());
        }
        None
    }

    fn update_ffi_language(&self, options: &mut ffi::libpostal_address_parser_options) {
        if let Some(language) = &self.language {
            options.language = language.as_ptr();
        };
    }

    fn update_ffi_country(&self, options: &mut ffi::libpostal_address_parser_options) {
        if let Some(country) = &self.country {
            options.country = country.as_ptr();
        };
    }

    /// Parse a postal address and derive labeled tokens using `libpostal`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rustpostal::error::RuntimeError;
    /// use rustpostal::{address, LibModules};
    ///
    /// fn main() -> Result<(), RuntimeError> {
    ///     let postal_module = LibModules::Address;
    ///     postal_module.setup()?;
    ///     
    ///     let options = address::AddressParserOptions::new(None, None)?;
    ///     let address = "St Johns Centre, Rope Walk, Bedford, Bedfordshire, MK42 0XE, United Kingdom";
    ///     let labels_tokens = options.parse(address)?;
    ///
    ///     for (label, token) in &labels_tokens {
    ///         println!("{}: {}", label, token);
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// It will return an error if the address contains an internal null byte.
    pub fn parse<'b>(&self, address: &'b str) -> Result<AddressParserResponse, NulError> {
        let c_address = CString::new(address)?;
        let mut response = AddressParserResponse::new();
        let ptr = c_address.into_raw();

        let mut ffi_options = unsafe { ffi::libpostal_get_address_parser_default_options() };
        self.update_ffi_language(&mut ffi_options);
        self.update_ffi_country(&mut ffi_options);

        let raw = unsafe { ffi::libpostal_parse_address(ptr, ffi_options) };
        if let Some(parsed) = unsafe { raw.as_ref() } {
            for i in 0..parsed.num_components {
                let component = unsafe { CStr::from_ptr(*parsed.components.add(i)) };
                let label = unsafe { CStr::from_ptr(*parsed.labels.add(i)) };
                response
                    .tokens
                    .push(String::from(component.to_str().unwrap()));
                response.labels.push(String::from(label.to_str().unwrap()));
            }
        };
        unsafe {
            ffi::libpostal_address_parser_response_destroy(raw);
        }
        let _c_address = unsafe { CString::from_raw(ptr) };
        Ok(response)
    }
}

/// Analyze address into labeled tokens.
///
/// * `address`: The postal address to parse.
/// * `language`: A language code.
/// * `country`: A country code.
///
/// The function wraps [`AddressParserOptions::parse`].
pub fn parse_address(
    address: &str,
    language: Option<&str>,
    country: Option<&str>,
) -> Result<AddressParserResponse, NulError> {
    let options = AddressParserOptions::new(language, country)?;
    options.parse(address)
}

/// A parsed address backed by a `HashMap`.
/// The only way to make one is from an `AddressParserResponse`.
/// It implements a getter method for each label that might
/// be included in the `AddressParserResponse`.
#[derive(Clone, Default, Debug, Eq, PartialEq)]
pub struct ParsedAddress {
    label_to_token: HashMap<String, String>,
}

impl ParsedAddress {
    pub fn house(&self) -> Option<String> {
        self.label_to_token.get("house").cloned()
    }

    pub fn house_number(&self) -> Option<String> {
        self.label_to_token.get("house_number").cloned()
    }

    pub fn po_box(&self) -> Option<String> {
        self.label_to_token.get("po_box").cloned()
    }

    pub fn building(&self) -> Option<String> {
        self.label_to_token.get("building").cloned()
    }

    pub fn entrance(&self) -> Option<String> {
        self.label_to_token.get("entrance").cloned()
    }

    pub fn staircase(&self) -> Option<String> {
        self.label_to_token.get("staircase").cloned()
    }

    pub fn level(&self) -> Option<String> {
        self.label_to_token.get("level").cloned()
    }

    pub fn unit(&self) -> Option<String> {
        self.label_to_token.get("unit").cloned()
    }

    pub fn road(&self) -> Option<String> {
        self.label_to_token.get("road").cloned()
    }

    pub fn metro_station(&self) -> Option<String> {
        self.label_to_token.get("metro_station").cloned()
    }

    pub fn suburb(&self) -> Option<String> {
        self.label_to_token.get("suburb").cloned()
    }

    pub fn city_district(&self) -> Option<String> {
        self.label_to_token.get("city_district").cloned()
    }

    pub fn city(&self) -> Option<String> {
        self.label_to_token.get("city").cloned()
    }

    pub fn state_district(&self) -> Option<String> {
        self.label_to_token.get("state_district").cloned()
    }

    pub fn island(&self) -> Option<String> {
        self.label_to_token.get("island").cloned()
    }

    pub fn state(&self) -> Option<String> {
        self.label_to_token.get("state").cloned()
    }

    // postcode may be referred to as postal_code somewheres
    // https://github.com/openvenues/libpostal/blob/9c975972985b54491e756efd70e416f18ff97958/src/address_parser.h#L122
    pub fn postcode(&self) -> Option<String> {
        self.label_to_token.get("postcode").cloned()
    }

    pub fn country_region(&self) -> Option<String> {
        self.label_to_token.get("country_region").cloned()
    }

    pub fn country(&self) -> Option<String> {
        self.label_to_token.get("country").cloned()
    }

    pub fn world_region(&self) -> Option<String> {
        self.label_to_token.get("world_region").cloned()
    }

    pub fn website(&self) -> Option<String> {
        self.label_to_token.get("website").cloned()
    }

    pub fn telephone(&self) -> Option<String> {
        self.label_to_token.get("telephone").cloned()
    }
}

impl From<AddressParserResponse> for ParsedAddress {
    /// Create a new `ParsedAddress` from an `AddressParserResponse`.
    fn from(response: AddressParserResponse) -> Self {
        let mut parsed_address = ParsedAddress::default();
        for (label, token) in response {
            parsed_address.label_to_token.insert(label, token);
        }
        parsed_address
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::RuntimeError;
    use crate::LibModules;

    #[test]
    fn default_address_parser_options() -> Result<(), NulError> {
        let options = AddressParserOptions::new(None, None)?;
        assert_eq!(options.language(), None);
        assert_eq!(options.country(), None);
        let options = AddressParserOptions::new(None, Some("EN"))?;
        assert_eq!(options.language(), None);
        assert_eq!(options.country(), Some("EN"));
        Ok(())
    }

    #[test]
    fn address_parser_options_parse() -> Result<(), RuntimeError> {
        let postal_module = LibModules::Address;
        postal_module.setup()?;

        let options = AddressParserOptions::new(None, None)?;
        let address = "St Johns Centre, Rope Walk, Bedford, Bedfordshire, MK42 0XE, United Kingdom";

        let labeled_tokens = options.parse(address)?;

        for (label, token) in &labeled_tokens {
            println!("{}: {}", label, token);
        }
        Ok(())
    }

    #[test]
    fn test_parsed_address_default() {
        let parsed_address = ParsedAddress::default();
        assert_eq!(parsed_address.house(), None);
        assert_eq!(parsed_address.house_number(), None);
        assert_eq!(parsed_address.po_box(), None);
        assert_eq!(parsed_address.building(), None);
        assert_eq!(parsed_address.entrance(), None);
        assert_eq!(parsed_address.staircase(), None);
        assert_eq!(parsed_address.level(), None);
        assert_eq!(parsed_address.unit(), None);
        assert_eq!(parsed_address.road(), None);
        assert_eq!(parsed_address.metro_station(), None);
        assert_eq!(parsed_address.suburb(), None);
        assert_eq!(parsed_address.city_district(), None);
        assert_eq!(parsed_address.city(), None);
        assert_eq!(parsed_address.state_district(), None);
        assert_eq!(parsed_address.island(), None);
        assert_eq!(parsed_address.state(), None);
        assert_eq!(parsed_address.postcode(), None);
        assert_eq!(parsed_address.country_region(), None);
        assert_eq!(parsed_address.country(), None);
        assert_eq!(parsed_address.world_region(), None);
        assert_eq!(parsed_address.website(), None);
        assert_eq!(parsed_address.telephone(), None);
    }
}