extern crate redis;
use std::error;
use std::fmt;
use std::fmt::Display;
#[derive(Debug)]
pub enum ErrorInfo {
RedisError(redis::RedisError),
Description(&'static str),
TimeoutError(&'static str)
}
#[derive(Debug)]
pub struct RedisError {
pub info: ErrorInfo
}
impl error::Error for RedisError {
fn description(&self) -> &str {
match self.info {
ErrorInfo::RedisError(ref cause) => cause.description(),
ErrorInfo::Description(description) => description,
ErrorInfo::TimeoutError(description) => description,
}
}
fn cause(&self) -> Option<&error::Error> {
match self.info {
ErrorInfo::RedisError(ref cause) => Some(cause as &error::Error),
_ => None,
}
}
}
impl Display for RedisError {
fn fmt(
&self,
format: &mut fmt::Formatter,
) -> Result<(), fmt::Error> {
match self.info {
ErrorInfo::RedisError(ref cause) => cause.fmt(format),
ErrorInfo::Description(description) => description.fmt(format),
ErrorInfo::TimeoutError(description) => description.fmt(format),
}
}
}
pub trait RedisArg: Sized + ToString {}
macro_rules! as_redis_arg {
($t:ty) => (
impl RedisArg for $t {}
)
}
impl<'a> RedisArg for &'a str {}
as_redis_arg!(i8);
as_redis_arg!(i16);
as_redis_arg!(u16);
as_redis_arg!(i32);
as_redis_arg!(u32);
as_redis_arg!(i64);
as_redis_arg!(u64);
as_redis_arg!(f32);
as_redis_arg!(f64);
as_redis_arg!(isize);
as_redis_arg!(usize);
as_redis_arg!(bool);
pub type Message = redis::Msg;
pub type RedisResult<T> = Result<T, RedisError>;
pub type RedisEmptyResult = RedisResult<()>;
pub type RedisMessageResult = RedisResult<Message>;
pub type RedisStringResult = RedisResult<String>;
pub type RedisBoolResult = RedisResult<bool>;
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error;
use std::io::Write;
#[test]
fn redis_error_description() {
let redis_error = RedisError { info: ErrorInfo::Description("test") };
assert_eq!(redis_error.description(), "test");
assert!(redis_error.cause().is_none());
let mut writer = Vec::new();
write!(&mut writer, "formatted {}", redis_error).unwrap();
assert_eq!(writer, b"formatted test");
}
#[test]
fn redis_error_timeout_error() {
let redis_error = RedisError { info: ErrorInfo::TimeoutError("timeout") };
assert_eq!(redis_error.description(), "timeout");
assert!(redis_error.cause().is_none());
let mut writer = Vec::new();
write!(&mut writer, "formatted {}", redis_error).unwrap();
assert_eq!(writer, b"formatted timeout");
}
}