secp256k1_sys/macros.rs
1// SPDX-License-Identifier: CC0-1.0
2
3/// Implement methods and traits for types that contain an inner array.
4#[macro_export]
5macro_rules! impl_array_newtype {
6 ($thing:ident, $ty:ty, $len:expr) => {
7 impl $thing {
8 /// Like `cmp::Ord` but faster and with no guarantees across library versions.
9 ///
10 /// The inner byte array of `Self` is passed across the FFI boundry, as such there are
11 /// no guarantees on its layout and it is subject to change across library versions,
12 /// even minor versions. For this reason comparison function implementations (e.g.
13 /// `Ord`, `PartialEq`) take measures to ensure the data will remain constant (e.g., by
14 /// serializing it to a guaranteed format). This means they may be slow, this function
15 /// provides a faster comparison if you know that your types come from the same library
16 /// version.
17 pub fn cmp_fast_unstable(&self, other: &Self) -> core::cmp::Ordering {
18 self[..].cmp(&other[..])
19 }
20
21 /// Like `cmp::Eq` but faster and with no guarantees across library versions.
22 ///
23 /// The inner byte array of `Self` is passed across the FFI boundry, as such there are
24 /// no guarantees on its layout and it is subject to change across library versions,
25 /// even minor versions. For this reason comparison function implementations (e.g.
26 /// `Ord`, `PartialEq`) take measures to ensure the data will remain constant (e.g., by
27 /// serializing it to a guaranteed format). This means they may be slow, this function
28 /// provides a faster equality check if you know that your types come from the same
29 /// library version.
30 pub fn eq_fast_unstable(&self, other: &Self) -> bool { self[..].eq(&other[..]) }
31 }
32
33 impl AsRef<[$ty; $len]> for $thing {
34 #[inline]
35 /// Gets a reference to the underlying array
36 fn as_ref(&self) -> &[$ty; $len] {
37 let &$thing(ref dat) = self;
38 dat
39 }
40 }
41
42 impl<I> core::ops::Index<I> for $thing
43 where
44 [$ty]: core::ops::Index<I>,
45 {
46 type Output = <[$ty] as core::ops::Index<I>>::Output;
47
48 #[inline]
49 fn index(&self, index: I) -> &Self::Output { &self.0[index] }
50 }
51
52 impl $crate::CPtr for $thing {
53 type Target = $ty;
54
55 fn as_c_ptr(&self) -> *const Self::Target {
56 let &$thing(ref dat) = self;
57 dat.as_ptr()
58 }
59
60 fn as_mut_c_ptr(&mut self) -> *mut Self::Target {
61 let &mut $thing(ref mut dat) = self;
62 dat.as_mut_ptr()
63 }
64 }
65 };
66}
67
68#[macro_export]
69macro_rules! impl_raw_debug {
70 ($thing:ident) => {
71 impl core::fmt::Debug for $thing {
72 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
73 for i in self[..].iter().cloned() {
74 write!(f, "{:02x}", i)?;
75 }
76 Ok(())
77 }
78 }
79 };
80}