use std::fmt;
use std::error::Error;
#[derive(Debug)]
struct StaticStrError {
error: &'static str
}
impl Error for StaticStrError {
fn description(&self) -> &str {
self.error
}
}
impl fmt::Display for StaticStrError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.error)
}
}
#[derive(Debug)]
struct StringError {
error: String
}
impl Error for StringError {
fn description(&self) -> &str {
&self.error
}
}
impl fmt::Display for StringError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Error: {}", self.error)
}
}
pub fn static_err(e: &'static str) -> Box<Error> {
Box::new(StaticStrError { error: e })
}
pub fn new_err(e: &str) -> Box<Error> {
Box::new(StringError { error: String::from(e) })
}
pub fn into_err(e: String) -> Box<Error> {
Box::new(StringError { error: e })
}
#[cfg(test)]
mod tests {
use super::*;
static SOME_STRING : &'static str = "This is a String?!";
#[test]
fn test_static_err() {
let x = static_err(SOME_STRING);
assert_eq!(x.description(), SOME_STRING);
assert!(x.cause().is_none());
}
#[test]
fn test_new_err() {
let x = new_err(SOME_STRING);
assert_eq!(x.description(), SOME_STRING);
assert!(x.cause().is_none());
}
#[test]
fn test_into_err() {
let x = into_err(String::from(SOME_STRING));
assert_eq!(x.description(), SOME_STRING);
assert!(x.cause().is_none());
}
}