Skip to content

Commit

Permalink
Merge pull request #336 from tmccombs/kv-error
Browse files Browse the repository at this point in the history
Add conversion to/from io::Error for kv::Error
  • Loading branch information
KodrAus committed Jul 3, 2019
2 parents 569175e + 86748c8 commit bcbee9f
Showing 1 changed file with 42 additions and 6 deletions.
48 changes: 42 additions & 6 deletions src/kv/error.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,47 @@
use std::fmt;
#[cfg(feature = "std")]
use std::io;

/// An error encountered while working with structured data.
#[derive(Clone, Debug)]
#[derive(Debug)]
pub struct Error {
msg: &'static str,
inner: Inner
}

#[derive(Debug)]
enum Inner {
#[cfg(feature = "std")]
Io(io::Error),
Msg(&'static str),
Fmt,
}

impl Error {
/// Create an error from the given message.
pub fn msg(msg: &'static str) -> Self {
Error {
msg: msg,
inner: Inner::Msg(msg),
}
}
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.msg.fmt(f)
use self::Inner::*;
match &self.inner {
#[cfg(feature = "std")]
&Io(ref err) => err.fmt(f),
&Msg(ref msg) => msg.fmt(f),
&Fmt => fmt::Error.fmt(f),
}
}
}

impl From<fmt::Error> for Error {
fn from(_: fmt::Error) -> Self {
Error::msg("formatting failed")
Error {
inner: Inner::Fmt,
}
}
}

Expand All @@ -36,11 +54,29 @@ impl From<Error> for fmt::Error {
#[cfg(feature = "std")]
mod std_support {
use super::*;
use std::error;
use std::{error, io};

impl error::Error for Error {
fn description(&self) -> &str {
"key values error"
}
}

impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error {
inner: Inner::Io(err)
}
}
}

impl From<Error> for io::Error {
fn from(err: Error) -> Self {
if let Inner::Io(err) = err.inner {
err
} else {
io::Error::new(io::ErrorKind::Other, err)
}
}
}
}

0 comments on commit bcbee9f

Please sign in to comment.