Skip to content

Commit

Permalink
[#2] Delegate setup/teardown to LibModules
Browse files Browse the repository at this point in the history
  • Loading branch information
kodemartin committed Jul 16, 2021
1 parent 06ef51e commit c6078b6
Showing 1 changed file with 66 additions and 15 deletions.
81 changes: 66 additions & 15 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,65 @@ 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);
Expand All @@ -73,6 +126,10 @@ pub unsafe fn setup(component: LibModules) {
///
/// 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` traint when `LibModules` values go out of scope"
)]
pub unsafe fn teardown(component: LibModules) {
ffi::libpostal_teardown();
match component {
Expand All @@ -94,26 +151,20 @@ mod tests {
use super::*;

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

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

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

0 comments on commit c6078b6

Please sign in to comment.