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
//! [`libpostal`][libpostal] bindings for the Rust programming language.
//!
//! # Examples
//!
//! ```
//! use rustpostal::address;
//! use rustpostal::expand;
//! use rustpostal::LibModules;
//!
//! fn main() -> Result<(), rustpostal::error::RuntimeError> {
//!     let postal_module = LibModules::All;
//!     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 (token, label) in &labeled_tokens {
//!         println!("{}: {}", token, label);
//!     }
//!
//!     let expanded = expand::expand_address_with_options(address, Some(["en"].iter()))?;
//!
//!     for expansion in &expanded {
//!         println!("{}", expansion);
//!     }
//!     Ok(())
//! }
//! ```
//!
//! [libpostal]: https://github.com/openvenues/libpostal

use std::process;

use self::LibModules::*;

pub mod address;
pub mod error;
pub mod expand;
mod ffi;

use error::SetupError;

/// Library modules to setup and teardown, at the start
/// and at the end of our program.
#[derive(Clone, Debug, Hash, Ord, PartialOrd, Eq, PartialEq)]
pub enum LibModules {
    Address,
    Expand,
    All,
}

unsafe fn setup_parser() {
    if !ffi::libpostal_setup_parser() {
        process::exit(1)
    };
}

unsafe fn setup_classifier() {
    if !ffi::libpostal_setup_language_classifier() {
        process::exit(1)
    };
}

unsafe fn teardown_parser() {
    ffi::libpostal_teardown_parser();
}

unsafe fn teardown_classifier() {
    ffi::libpostal_teardown_language_classifier();
}

impl LibModules {
    /// Setup the necessary `libpostal` resources.
    ///
    /// # Examples
    /// ```
    /// use rustpostal::error::SetupError;
    /// use rustpostal::LibModules;
    ///
    /// fn main() -> Result<(), SetupError> {
    ///     let postal_module = LibModules::Expand;
    ///     postal_module.setup()?;
    ///     Ok(())
    /// }
    /// ```
    pub fn setup(&self) -> Result<(), SetupError> {
        if unsafe { !ffi::libpostal_setup() } {
            return Err(SetupError);
        }
        match self {
            Expand => unsafe {
                setup_classifier();
            },
            Address => unsafe {
                setup_parser();
            },
            All => unsafe {
                setup_parser();
                setup_classifier();
            },
        }
        Ok(())
    }
}

impl Drop for LibModules {
    /// Tear down the ffi resources that were initialized during setup.
    fn drop(&mut self) {
        unsafe { ffi::libpostal_teardown() };
        match self {
            Expand => unsafe { teardown_classifier() },
            Address => unsafe { teardown_parser() },
            All => unsafe {
                teardown_parser();
                teardown_classifier();
            },
        }
    }
}

/// Setup the necessary `libpostal` components.
///
/// # Safety
///
/// The method should be complemented by [`teardown`](self::teardown)
/// to make the calling program safe.
#[deprecated(
    since = "0.2.0",
    note = "Please use the `setup` method in `LibModules` instead"
)]
pub unsafe fn setup(component: LibModules) {
    if !ffi::libpostal_setup() {
        process::exit(1);
    }
    match component {
        Expand => {
            setup_classifier();
        }
        Address => {
            setup_parser();
        }
        All => {
            setup_parser();
            setup_classifier();
        }
    }
}

/// Teardown initialized `libpostal` components.
///
/// # Safety
///
/// The method should follow [`setup`](self::setup) and makes the calling
/// program safe.
#[deprecated(
    since = "0.2.0",
    note = "This can be handled by the `Drop` trait when `LibModules` values go out of scope"
)]
pub unsafe fn teardown(component: LibModules) {
    ffi::libpostal_teardown();
    match component {
        Expand => {
            teardown_classifier();
        }
        Address => {
            teardown_parser();
        }
        All => {
            teardown_parser();
            teardown_classifier();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn libmodules_setup_expand() {
        let postal_module = Expand;
        assert!(postal_module.setup().is_ok());
    }

    #[test]
    fn libmodules_setup_parser() {
        let postal_module = Address;
        assert!(postal_module.setup().is_ok());
    }

    #[test]
    fn libmodules_setup_all() {
        let postal_module = All;
        assert!(postal_module.setup().is_ok());
    }
}