Debian Codegraph @

third_party/rust/scroll/src/error.rs

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