1use core::fmt::{self, Display};
2use core::{error, result};
3#[cfg(feature = "std")]
4use std::io;
5
6#[derive(Debug)]
7pub enum Error {
9 TooBig {
11 size: usize,
12 len: usize,
13 },
14 BadOffset(usize),
16 BadInput {
17 size: usize,
18 msg: &'static str,
19 },
20 #[cfg(feature = "std")]
23 Custom(String),
24 #[cfg(feature = "std")]
26 IO(io::Error),
27}
28
29impl error::Error for Error {
30 fn description(&self) -> &str {
31 match self {
32 Error::TooBig { .. } => "TooBig",
33 Error::BadOffset(_) => "BadOffset",
34 Error::BadInput { .. } => "BadInput",
35 #[cfg(feature = "std")]
36 Error::Custom(_) => "Custom",
37 #[cfg(feature = "std")]
38 Error::IO(_) => "IO",
39 }
40 }
41 fn cause(&self) -> Option<&dyn error::Error> {
42 match self {
43 Error::TooBig { .. } => None,
44 Error::BadOffset(_) => None,
45 Error::BadInput { .. } => None,
46 #[cfg(feature = "std")]
47 Error::Custom(_) => None,
48 #[cfg(feature = "std")]
49 Error::IO(io) => io.source(),
50 }
51 }
52}
53
54#[cfg(feature = "std")]
55impl From<io::Error> for Error {
56 fn from(err: io::Error) -> Error {
57 Error::IO(err)
58 }
59}
60
61impl Display for Error {
62 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
63 match self {
64 Error::TooBig { size, len } => {
65 write!(fmt, "type is too big ({size}) for {len}")
66 }
67 Error::BadOffset(offset) => {
68 write!(fmt, "bad offset {offset}")
69 }
70 Error::BadInput { msg, size } => {
71 write!(fmt, "bad input {msg} ({size})")
72 }
73 #[cfg(feature = "std")]
74 Error::Custom(msg) => {
75 write!(fmt, "{msg}")
76 }
77 #[cfg(feature = "std")]
78 Error::IO(err) => {
79 write!(fmt, "{err}")
80 }
81 }
82 }
83}
84
85pub type Result<T> = result::Result<T, Error>;