bitcoin_internals/
error.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! # Error
4//!
5//! Error handling macros and helpers.
6//!
7
8pub mod input_string;
9mod parse_error;
10
11pub use input_string::InputString;
12
13/// Formats error.
14///
15/// If `std` feature is OFF appends error source (delimited by `: `). We do this because
16/// `e.source()` is only available in std builds, without this macro the error source is lost for
17/// no-std builds.
18#[macro_export]
19macro_rules! write_err {
20    ($writer:expr, $string:literal $(, $args:expr)*; $source:expr) => {
21        {
22            #[cfg(feature = "std")]
23            {
24                let _ = &$source;   // Prevents clippy warnings.
25                write!($writer, $string $(, $args)*)
26            }
27            #[cfg(not(feature = "std"))]
28            {
29                write!($writer, concat!($string, ": {}") $(, $args)*, $source)
30            }
31        }
32    }
33}
34
35/// Impls std::error::Error for the specified type with appropriate attributes, possibly returning
36/// source.
37#[macro_export]
38macro_rules! impl_std_error {
39    // No source available
40    ($type:ty) => {
41        #[cfg(feature = "std")]
42        impl std::error::Error for $type {}
43    };
44    // Struct with $field as source
45    ($type:ty, $field:ident) => {
46        #[cfg(feature = "std")]
47        impl std::error::Error for $type {
48            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.$field) }
49        }
50    };
51}