Skip to content

Commit

Permalink
[#2] Create error module
Browse files Browse the repository at this point in the history
  • Loading branch information
kodemartin committed Jul 16, 2021
1 parent 0333694 commit 06ef51e
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//! Runtime errors for the [`rustpostal`] crate.
use std::error;
use std::ffi::NulError;
use std::fmt;

/// An error indicating failure in setting up required `libpostal` resources.
/// Returned by [`setup`](`LibModules.setup`) method on [`LibModules`].
#[derive(Debug, Clone)]
pub struct SetupError;

impl fmt::Display for SetupError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "setup of libpostal resources failed")
}
}

impl error::Error for SetupError {}

/// Error indicating possible runtime failures.
#[derive(Debug, Clone)]
pub enum RuntimeError {
FailedSetup(SetupError),
InvalidAddress(NulError),
}

impl fmt::Display for RuntimeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RuntimeError::FailedSetup(ref err) => err.fmt(f),
RuntimeError::InvalidAddress(_) => {
write!(f, "input address possibly contains internal null byte")
}
}
}
}

impl error::Error for RuntimeError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
RuntimeError::FailedSetup(ref err) => Some(err),
RuntimeError::InvalidAddress(ref err) => Some(err),
}
}
}

impl From<SetupError> for RuntimeError {
/// Create a new [`RuntimeError`] consuming a [`SetupError`].
fn from(err: SetupError) -> Self {
RuntimeError::FailedSetup(err)
}
}

impl From<NulError> for RuntimeError {
/// Create a new [`RuntimeError`] consuming a [`NulError`].
fn from(err: NulError) -> Self {
RuntimeError::InvalidAddress(err)
}
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ 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.
pub enum LibModules {
Expand Down

0 comments on commit 06ef51e

Please sign in to comment.