From 71ae4cb234b072d2e269b5230e9abe52982de2ae Mon Sep 17 00:00:00 2001 From: Spenser Black Date: Wed, 26 Aug 2020 14:48:24 -0400 Subject: [PATCH] Allow conversion from ColoredString to Error --- examples/as_error.rs | 8 ++++++++ src/error.rs | 24 ++++++++++++++++++++++++ src/lib.rs | 9 ++++++++- 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 examples/as_error.rs create mode 100644 src/error.rs diff --git a/examples/as_error.rs b/examples/as_error.rs new file mode 100644 index 0000000..f04c685 --- /dev/null +++ b/examples/as_error.rs @@ -0,0 +1,8 @@ +extern crate colored; + +use colored::Colorize; +use std::error::Error; + +fn main() -> Result<(), Box> { + Err("ERROR".red())? +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..31fe8de --- /dev/null +++ b/src/error.rs @@ -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 {} diff --git a/src/lib.rs b/src/lib.rs index 4475320..775c092 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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}; @@ -595,6 +596,12 @@ impl fmt::Display for ColoredString { } } +impl From for Box { + fn from(cs: ColoredString) -> Box { + Box::from(error::ColoredStringError(cs)) + } +} + #[cfg(test)] mod tests { use super::*;