Skip to content

Commit

Permalink
Allow conversion from ColoredString to Error
Browse files Browse the repository at this point in the history
  • Loading branch information
spenserblack committed Aug 26, 2020
1 parent 015f2a5 commit 71ae4cb
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
8 changes: 8 additions & 0 deletions examples/as_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
extern crate colored;

use colored::Colorize;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
Err("ERROR".red())?
}
24 changes: 24 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use super::ColoredString;
use std::{error::Error, fmt};

pub struct ColoredStringError(pub ColoredString);

impl ColoredStringError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0.to_string())
}
}

impl fmt::Display for ColoredStringError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.fmt(f)
}
}

impl fmt::Debug for ColoredStringError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.fmt(f)
}
}

impl Error for ColoredStringError {}
9 changes: 8 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,12 @@ extern crate rspec;

mod color;
pub mod control;
mod error;
mod style;

pub use color::*;

use std::{borrow::Cow, fmt, ops::Deref};
use std::{borrow::Cow, error::Error, fmt, ops::Deref};

pub use style::{Style, Styles};

Expand Down Expand Up @@ -595,6 +596,12 @@ impl fmt::Display for ColoredString {
}
}

impl From<ColoredString> for Box<dyn Error> {
fn from(cs: ColoredString) -> Box<dyn Error> {
Box::from(error::ColoredStringError(cs))
}
}

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

0 comments on commit 71ae4cb

Please sign in to comment.