1 use core::fmt::{self, Display};
2 use core::result;
3 
4 #[cfg(feature = "std")]
5 use std::io;
6 #[cfg(feature = "std")]
7 use std::error;
8 
9 #[derive(Debug)]
10 /// A custom Scroll error
11 pub enum Error {
12     /// The type you tried to read was too big
13     TooBig { size: usize, len: usize },
14     /// The requested offset to read/write at is invalid
15     BadOffset(usize),
16     BadInput{ size: usize, msg: &'static str },
17     #[cfg(feature = "std")]
18     /// A custom Scroll error for reporting messages to clients
19     Custom(String),
20     #[cfg(feature = "std")]
21     /// Returned when IO based errors are encountered
22     IO(io::Error),
23 }
24 
25 #[cfg(feature = "std")]
26 impl error::Error for Error {
description(&self) -> &str27     fn description(&self) -> &str {
28         match *self {
29             Error::TooBig{ .. } => { "TooBig" }
30             Error::BadOffset(_) => { "BadOffset" }
31             Error::BadInput{ .. } => { "BadInput" }
32             Error::Custom(_) => { "Custom" }
33             Error::IO(_) => { "IO" }
34         }
35     }
cause(&self) -> Option<&dyn error::Error>36     fn cause(&self) -> Option<&dyn error::Error> {
37         match *self {
38             Error::TooBig{ .. } => { None }
39             Error::BadOffset(_) => { None }
40             Error::BadInput{ .. } => { None }
41             Error::Custom(_) => { None }
42             Error::IO(ref io) => { io.source() }
43         }
44     }
45 }
46 
47 #[cfg(feature = "std")]
48 impl From<io::Error> for Error {
from(err: io::Error) -> Error49     fn from(err: io::Error) -> Error {
50         Error::IO(err)
51     }
52 }
53 
54 impl Display for Error {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result55     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
56         match *self {
57             Error::TooBig{ ref size, ref len } => { write! (fmt, "type is too big ({}) for {}", size, len) },
58             Error::BadOffset(ref offset) => { write! (fmt, "bad offset {}", offset) },
59             Error::BadInput{ ref msg, ref size } => { write! (fmt, "bad input {} ({})", msg, size) },
60             #[cfg(feature = "std")]
61             Error::Custom(ref msg) => { write! (fmt, "{}", msg) },
62             #[cfg(feature = "std")]
63             Error::IO(ref err) => { write!(fmt, "{}", err) },
64         }
65     }
66 }
67 
68 pub type Result<T> = result::Result<T, Error>;
69