1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
// Copyright (c) 2017, Marty Mills <daggerbot@gmail.com>
// This software is available under the terms of the zlib license.
// See COPYING.md for more information.

use std;
use std::ffi::NulError;
use std::fmt::{self, Formatter};
use std::sync::{mpsc, Arc};

use try_from::TryFromIntError;

/// `dwindow` result type.
pub type Result<T> = std::result::Result<T, Error>;

/// Enumeration of error kinds.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ErrorKind {
    BadTypeCast,
    ConnectionFailed,
    EncodingError,
    FormatError,
    IncompatibleResource,
    InvalidArgument,
    InvalidOperation,
    LibraryError,
    LockedDisplay,
    NoMatch,
    RequestFailed,
    ResourceExpired,
    SynchronizationError,
    Unimplemented,
    Unsupported,
}

impl ErrorKind {
    pub fn description (self) -> &'static str {
        match self {
            ErrorKind::BadTypeCast => "bad type cast",
            ErrorKind::ConnectionFailed => "connection failed",
            ErrorKind::EncodingError => "encoding error",
            ErrorKind::FormatError => "format error",
            ErrorKind::IncompatibleResource => "incompatible resource",
            ErrorKind::InvalidArgument => "invalid argument",
            ErrorKind::InvalidOperation => "invalid operation",
            ErrorKind::LibraryError => "library error",
            ErrorKind::LockedDisplay => "locked display",
            ErrorKind::NoMatch => "no match",
            ErrorKind::RequestFailed => "request failed",
            ErrorKind::ResourceExpired => "resource expired",
            ErrorKind::SynchronizationError => "synchronization error",
            ErrorKind::Unimplemented => "unimplemented",
            ErrorKind::Unsupported => "unsupported",
        }
    }
}

/// Error detail type.
#[derive(Clone, Debug)]
enum Detail {
    Static(&'static str),
    Owned(String),
}

impl AsRef<str> for Detail {
    fn as_ref (&self) -> &str {
        match *self {
            Detail::Static(s) => s,
            Detail::Owned(ref s) => s.as_str(),
        }
    }
}

/// `dwindow` error type.
#[derive(Clone, Debug)]
pub struct Error {
    kind: ErrorKind,
    detail: Option<Detail>,
    cause: Option<Arc<std::error::Error + Send + Sync>>,
}

impl Error {
    pub fn new (kind: ErrorKind) -> Error {
        Error {
            kind: kind,
            detail: None,
            cause: None,
        }
    }

    pub fn with_cause<E> (mut self, cause: E) -> Error
        where E: std::error::Error + Send + Sync + 'static
    {
        self.cause = Some(Arc::new(cause));
        self
    }

    pub fn with_detail<T> (mut self, detail: T) -> Error
        where T: std::fmt::Display
    {
        self.detail = Some(Detail::Owned(detail.to_string()));
        self
    }

    pub fn with_str (mut self, detail: &'static str) -> Error {
        self.detail = Some(Detail::Static(detail));
        self
    }
}

impl fmt::Display for Error {
    fn fmt (&self, f: &mut Formatter) -> fmt::Result {
        f.write_str(self.kind.description())?;

        if let Some(ref detail) = self.detail {
            f.write_str(" (")?;
            f.write_str(detail.as_ref())?;
            f.write_str(")")?;
        }

        if let Some(ref cause) = self.cause {
            f.write_str(": ")?;
            fmt::Display::fmt(cause, f)?;
        }

        Ok(())
    }
}

impl std::error::Error for Error {
    fn cause (&self) -> Option<&std::error::Error> {
        self.cause.as_ref().map(|e| &**e as &std::error::Error)
    }

    fn description (&self) -> &str { self.kind.description() }
}

/// Macro which constructs an error.
macro_rules! err {
    ($kind:ident) => {
        $crate::error::Error::new($crate::error::ErrorKind::$kind)
    };
}

// From impls

impl From<NulError> for Error {
    fn from (err: NulError) -> Error { err!(EncodingError).with_cause(err) }
}

impl From<TryFromIntError> for Error {
    fn from (err: TryFromIntError) -> Error { err!(BadTypeCast).with_cause(err) }
}

impl<T> From<mpsc::SendError<T>> for Error {
    fn from (err: mpsc::SendError<T>) -> Error { err!(SynchronizationError).with_detail(err) }
}