bitcoin_internals/
macros.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Various macros used by the Rust Bitcoin ecosystem.
4//!
5
6/// Implements standard array methods for a given wrapper type.
7#[macro_export]
8macro_rules! impl_array_newtype {
9    ($thing:ident, $ty:ty, $len:literal) => {
10        impl $thing {
11            /// Converts the object to a raw pointer.
12            #[inline]
13            pub fn as_ptr(&self) -> *const $ty {
14                let &$thing(ref dat) = self;
15                dat.as_ptr()
16            }
17
18            /// Converts the object to a mutable raw pointer.
19            #[inline]
20            pub fn as_mut_ptr(&mut self) -> *mut $ty {
21                let &mut $thing(ref mut dat) = self;
22                dat.as_mut_ptr()
23            }
24
25            /// Returns the length of the object as an array.
26            #[inline]
27            pub fn len(&self) -> usize { $len }
28
29            /// Returns whether the object, as an array, is empty. Always false.
30            #[inline]
31            pub fn is_empty(&self) -> bool { false }
32        }
33
34        impl<'a> core::convert::From<[$ty; $len]> for $thing {
35            fn from(data: [$ty; $len]) -> Self { $thing(data) }
36        }
37
38        impl<'a> core::convert::From<&'a [$ty; $len]> for $thing {
39            fn from(data: &'a [$ty; $len]) -> Self { $thing(*data) }
40        }
41
42        impl<'a> core::convert::TryFrom<&'a [$ty]> for $thing {
43            type Error = core::array::TryFromSliceError;
44
45            fn try_from(data: &'a [$ty]) -> core::result::Result<Self, Self::Error> {
46                use core::convert::TryInto;
47
48                Ok($thing(data.try_into()?))
49            }
50        }
51
52        impl AsRef<[$ty; $len]> for $thing {
53            fn as_ref(&self) -> &[$ty; $len] { &self.0 }
54        }
55
56        impl AsMut<[$ty; $len]> for $thing {
57            fn as_mut(&mut self) -> &mut [$ty; $len] { &mut self.0 }
58        }
59
60        impl AsRef<[$ty]> for $thing {
61            fn as_ref(&self) -> &[$ty] { &self.0 }
62        }
63
64        impl AsMut<[$ty]> for $thing {
65            fn as_mut(&mut self) -> &mut [$ty] { &mut self.0 }
66        }
67
68        impl core::borrow::Borrow<[$ty; $len]> for $thing {
69            fn borrow(&self) -> &[$ty; $len] { &self.0 }
70        }
71
72        impl core::borrow::BorrowMut<[$ty; $len]> for $thing {
73            fn borrow_mut(&mut self) -> &mut [$ty; $len] { &mut self.0 }
74        }
75
76        // The following two are valid because `[T; N]: Borrow<[T]>`
77        impl core::borrow::Borrow<[$ty]> for $thing {
78            fn borrow(&self) -> &[$ty] { &self.0 }
79        }
80
81        impl core::borrow::BorrowMut<[$ty]> for $thing {
82            fn borrow_mut(&mut self) -> &mut [$ty] { &mut self.0 }
83        }
84
85        impl<I> core::ops::Index<I> for $thing
86        where
87            [$ty]: core::ops::Index<I>,
88        {
89            type Output = <[$ty] as core::ops::Index<I>>::Output;
90
91            #[inline]
92            fn index(&self, index: I) -> &Self::Output { &self.0[index] }
93        }
94    };
95}
96
97/// Implements `Debug` by calling through to `Display`.
98#[macro_export]
99macro_rules! debug_from_display {
100    ($thing:ident) => {
101        impl core::fmt::Debug for $thing {
102            fn fmt(
103                &self,
104                f: &mut core::fmt::Formatter,
105            ) -> core::result::Result<(), core::fmt::Error> {
106                core::fmt::Display::fmt(self, f)
107            }
108        }
109    };
110}
111
112/// Asserts a boolean expression at compile time.
113#[macro_export]
114macro_rules! const_assert {
115    ($x:expr) => {{
116        const _: [(); 0 - !$x as usize] = [];
117    }};
118}
119
120/// Derives `From<core::convert::Infallible>` for the given type.
121///
122/// Supports types with arbitrary combinations of lifetimes and type parameters.
123///
124/// Note: Paths are not supported (for ex. impl_from_infallible!(Hello<D: std::fmt::Display>).
125///
126/// ## Examples
127///
128/// ```rust
129/// # use core::fmt::{Display, Debug};
130/// use bitcoin_internals::impl_from_infallible;
131///
132/// enum AlphaEnum { Item }
133/// impl_from_infallible!(AlphaEnum);
134///
135/// enum BetaEnum<'b> { Item(&'b usize) }
136/// impl_from_infallible!(BetaEnum<'b>);
137///
138/// enum GammaEnum<T> { Item(T) };
139/// impl_from_infallible!(GammaEnum<T>);
140///
141/// enum DeltaEnum<'b, 'a: 'static + 'b, T: 'a, D: Debug + Display + 'a> {
142///     Item((&'b usize, &'a usize, T, D))
143/// }
144/// impl_from_infallible!(DeltaEnum<'b, 'a: 'static + 'b, T: 'a, D: Debug + Display + 'a>);
145///
146/// struct AlphaStruct;
147/// impl_from_infallible!(AlphaStruct);
148///
149/// struct BetaStruct<'b>(&'b usize);
150/// impl_from_infallible!(BetaStruct<'b>);
151///
152/// struct GammaStruct<T>(T);
153/// impl_from_infallible!(GammaStruct<T>);
154///
155/// struct DeltaStruct<'b, 'a: 'static + 'b, T: 'a, D: Debug + Display + 'a> {
156///     hello: &'a T,
157///     what: &'b D,
158/// }
159/// impl_from_infallible!(DeltaStruct<'b, 'a: 'static + 'b, T: 'a, D: Debug + Display + 'a>);
160/// ```
161///
162/// See <https://stackoverflow.com/a/61189128> for more information about this macro.
163#[macro_export]
164macro_rules! impl_from_infallible {
165    ( $name:ident $(< $( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+ >)? ) => {
166        impl $(< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)?
167            From<core::convert::Infallible>
168        for $name
169            $(< $( $lt ),+ >)?
170        {
171            fn from(never: core::convert::Infallible) -> Self { match never {} }
172        }
173    }
174}