diff --git a/src/lib.rs b/src/lib.rs index aa87f4c..604fba2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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); @@ -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 { @@ -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()); } }