bitcode/
error.rs

1#[cfg(debug_assertions)]
2use alloc::borrow::Cow;
3use core::fmt::{Debug, Display, Formatter};
4
5/// Short version of `Err(error("..."))`.
6pub fn err<T>(msg: &'static str) -> Result<T, Error> {
7    Err(error(msg))
8}
9
10/// Creates an error with a message that might be displayed.
11pub fn error(_msg: &'static str) -> Error {
12    #[cfg(debug_assertions)]
13    return Error(Cow::Borrowed(_msg));
14    #[cfg(not(debug_assertions))]
15    Error(())
16}
17
18/// Creates an error from a `T:` [`Display`].
19#[cfg(feature = "serde")]
20pub fn error_from_display(_t: impl Display) -> Error {
21    #[cfg(debug_assertions)]
22    return Error(Cow::Owned(alloc::string::ToString::to_string(&_t)));
23    #[cfg(not(debug_assertions))]
24    Error(())
25}
26
27#[cfg(debug_assertions)]
28type ErrorImpl = Cow<'static, str>;
29#[cfg(not(debug_assertions))]
30type ErrorImpl = ();
31
32/// Decoding / (De)serialization errors.
33/// # Debug mode
34/// In debug mode, the error contains a reason.
35/// # Release mode
36/// In release mode, the error is a zero-sized type for efficiency.
37#[cfg_attr(test, derive(PartialEq))]
38pub struct Error(ErrorImpl);
39impl Debug for Error {
40    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
41        #[cfg(debug_assertions)]
42        return write!(f, "Error({:?})", self.0);
43        #[cfg(not(debug_assertions))]
44        f.write_str("Error(\"bitcode error\")")
45    }
46}
47impl Display for Error {
48    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
49        #[cfg(debug_assertions)]
50        return f.write_str(&self.0);
51        #[cfg(not(debug_assertions))]
52        f.write_str("bitcode error")
53    }
54}
55#[cfg(feature = "std")]
56// TODO expose to no_std when error_in_core stabilized (https://github.com/rust-lang/rust/issues/103765)
57impl std::error::Error for Error {}