bdk_chain::bitcoin::hashes::hex::display

Macro impl_fmt_traits

macro_rules! impl_fmt_traits {
    (impl fmt_traits for $ty:ident { const LENGTH: usize = $len:expr; }) => { ... };
    (#[display_backward($reverse:expr)] impl fmt_traits for $ty:ident { const LENGTH: usize = $len:expr; }) => { ... };
    (impl<$($gen:ident: $gent:ident),*> fmt_traits for $ty:ident<$($unused:ident),*> { const LENGTH: usize = $len:expr; }) => { ... };
    (#[display_backward($reverse:expr)] impl<$($gen:ident: $gent:ident),*> fmt_traits for $ty:ident<$($unused:ident),*> { const LENGTH: usize = $len:expr; }) => { ... };
}
Expand description

Adds core::fmt trait implementations to type $ty.

Implements:

  • fmt::{LowerHex, UpperHex} using fmt_hex_exact.
  • fmt::{Display, Debug} by calling LowerHex.

Requires:

  • $ty must implement IntoIterator<Item=Borrow<u8>>.

§Parameters

  • $ty - the type to implement traits on.
  • $len - known length of $bytes, must be a const expression.
  • $bytes - bytes to be encoded, most likely a reference to an array.
  • $reverse - true if you want the array to be displayed backwards.
  • $gen: $gent - optional generic type(s) and trait bound(s) to put on $ty e.g, F: Foo.

§Examples

struct Wrapper([u8; 4]);

impl Borrow<[u8]> for Wrapper {
    fn borrow(&self) -> &[u8] { &self.0[..] }
}

impl_fmt_traits! {
    impl fmt_traits for Wrapper {
        const LENGTH: usize = 4;
    }
}

let w = Wrapper([0x12, 0x34, 0x56, 0x78]);
assert_eq!(format!("{}", w), "12345678");

We support generics on $ty:

struct Wrapper<T>([u8; 4], PhantomData<T>);

// `Clone` is just some arbitrary trait.
impl<T: Clone> Borrow<[u8]> for Wrapper<T> {
    fn borrow(&self) -> &[u8] { &self.0[..] }
}

impl_fmt_traits! {
    impl<T: Clone> fmt_traits for Wrapper<T> {
        const LENGTH: usize = 4;
    }
}

let w = Wrapper([0x12, 0x34, 0x56, 0x78], PhantomData::<u32>);
assert_eq!(format!("{}", w), "12345678");

And also, as is required by rust-bitcoin, we support displaying the hex string byte-wise backwards:

struct Wrapper([u8; 4]);

impl Borrow<[u8]> for Wrapper {
    fn borrow(&self) -> &[u8] { &self.0[..] }
}

impl_fmt_traits! {
    #[display_backward(true)]
    impl fmt_traits for Wrapper {
        const LENGTH: usize = 4;
    }
}
let w = Wrapper([0x12, 0x34, 0x56, 0x78]);
assert_eq!(format!("{}", w), "78563412");