Skip to content

Commit

Permalink
Merge rust-bitcoin#3150: Create a macro that implements to_hex for …
Browse files Browse the repository at this point in the history
…types that have `core::fmt::LowerHex` implemented

30bb93c Implement impl_to_hex_from_lower_hex macro for types that implement fmt::LowerHex (Shing Him Ng)

Pull request description:

  Created a macro that implements `to_hex` for types that currently have `core::fmt::LowerHex` and called it on types that have `core::fmt::LowerHex` implemented. I put the macro in the `internals` crate since there are types across the whole project that can potentially use this.

  Resolves rust-bitcoin#2869

ACKs for top commit:
  Kixunil:
    ACK 30bb93c
  apoelstra:
    ACK 30bb93c successfully ran local tests

Tree-SHA512: d3ebc7b5c0c23f1a8f8eef4379c1b475e8c23845e18ce514cb1e98eb63fc4f215e6bc4425f97c7303053df13374ef931ae9d9373badd7ca1975a55b0d00d0e40
  • Loading branch information
apoelstra committed Sep 2, 2024
2 parents b535102 + 30bb93c commit 3b057ad
Show file tree
Hide file tree
Showing 10 changed files with 49 additions and 9 deletions.
3 changes: 3 additions & 0 deletions bitcoin/src/blockdata/script/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ use core::fmt;
use core::ops::{Deref, DerefMut};

use hashes::{hash160, sha256};
use internals::impl_to_hex_from_lower_hex;
use io::{BufRead, Write};

use crate::consensus::{encode, Decodable, Encodable};
Expand Down Expand Up @@ -459,11 +460,13 @@ impl fmt::LowerHex for Script {
fmt::LowerHex::fmt(&self.as_bytes().as_hex(), f)
}
}
impl_to_hex_from_lower_hex!(Script, |script: &Script| script.len() * 2);

impl fmt::LowerHex for ScriptBuf {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(self.as_script(), f) }
}
impl_to_hex_from_lower_hex!(ScriptBuf, |script_buf: &ScriptBuf| script_buf.len() * 2);

impl fmt::UpperHex for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Expand Down
3 changes: 2 additions & 1 deletion bitcoin/src/crypto/ecdsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use core::str::FromStr;
use core::{fmt, iter};

use hex::FromHex;
use internals::write_err;
use internals::{impl_to_hex_from_lower_hex, write_err};
use io::Write;

use crate::prelude::{DisplayHex, Vec};
Expand Down Expand Up @@ -174,6 +174,7 @@ impl fmt::LowerHex for SerializedSignature {
fmt::LowerHex::fmt(&(**self).as_hex(), f)
}
}
impl_to_hex_from_lower_hex!(SerializedSignature, |signature: &SerializedSignature| signature.len * 2);

impl fmt::UpperHex for SerializedSignature {
#[inline]
Expand Down
4 changes: 3 additions & 1 deletion bitcoin/src/crypto/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use core::str::FromStr;
use hashes::hash160;
use hex::{FromHex, HexToArrayError};
use internals::array_vec::ArrayVec;
use internals::write_err;
use internals::{impl_to_hex_from_lower_hex, write_err};
use io::{Read, Write};

use crate::crypto::ecdsa;
Expand Down Expand Up @@ -705,6 +705,8 @@ pub struct TweakedPublicKey(XOnlyPublicKey);
impl fmt::LowerHex for TweakedPublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) }
}
// Allocate for serialized size
impl_to_hex_from_lower_hex!(TweakedPublicKey, |_| constants::SCHNORR_PUBLIC_KEY_SIZE * 2);

impl fmt::Display for TweakedPublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
Expand Down
5 changes: 3 additions & 2 deletions bitcoin/src/p2p/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@ pub mod message_network;

use core::str::FromStr;
use core::{fmt, ops};

use hex::FromHex;
use internals::{debug_from_display, write_err};
use internals::{debug_from_display, impl_to_hex_from_lower_hex, write_err};
use io::{BufRead, Write};

use crate::consensus::encode::{self, Decodable, Encodable};
Expand Down Expand Up @@ -123,6 +122,7 @@ impl ServiceFlags {
impl fmt::LowerHex for ServiceFlags {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) }
}
impl_to_hex_from_lower_hex!(ServiceFlags, |service_flags: &ServiceFlags| 16 - service_flags.0.leading_zeros() as usize / 4);

impl fmt::UpperHex for ServiceFlags {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::UpperHex::fmt(&self.0, f) }
Expand Down Expand Up @@ -290,6 +290,7 @@ impl fmt::LowerHex for Magic {
Ok(())
}
}
impl_to_hex_from_lower_hex!(Magic, |_| 8);

impl fmt::UpperHex for Magic {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
Expand Down
4 changes: 3 additions & 1 deletion bitcoin/src/pow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

use core::ops::{Add, Div, Mul, Not, Rem, Shl, Shr, Sub};
use core::{cmp, fmt};

use internals::impl_to_hex_from_lower_hex;
use io::{BufRead, Write};
#[cfg(all(test, mutate))]
use mutagen::mutate;
Expand Down Expand Up @@ -108,6 +108,7 @@ impl Work {
pub fn log2(self) -> f64 { self.0.to_f64().log2() }
}
do_impl!(Work);
impl_to_hex_from_lower_hex!(Work, |_| 64);

impl Add for Work {
type Output = Work;
Expand Down Expand Up @@ -333,6 +334,7 @@ impl Target {
pub fn max_transition_threshold_unchecked(&self) -> Self { Self(self.0 << 2) }
}
do_impl!(Target);
impl_to_hex_from_lower_hex!(Target, |_| 64);

define_extension_trait! {
/// Extension functionality for the [`CompactTarget`] type.
Expand Down
4 changes: 3 additions & 1 deletion bitcoin/src/taproot/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use core::fmt;
use core::iter::FusedIterator;

use hashes::{hash_newtype, sha256t, sha256t_tag, HashEngine};
use internals::write_err;
use internals::{impl_to_hex_from_lower_hex, write_err};
use io::Write;
use secp256k1::{Scalar, Secp256k1};

Expand Down Expand Up @@ -1221,6 +1221,7 @@ impl fmt::LowerHex for FutureLeafVersion {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) }
}
impl_to_hex_from_lower_hex!(FutureLeafVersion, |_| 2);

impl fmt::UpperHex for FutureLeafVersion {
#[inline]
Expand Down Expand Up @@ -1277,6 +1278,7 @@ impl fmt::LowerHex for LeafVersion {
fmt::LowerHex::fmt(&self.to_consensus(), f)
}
}
impl_to_hex_from_lower_hex!(LeafVersion, |_| 2);

impl fmt::UpperHex for LeafVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand Down
27 changes: 27 additions & 0 deletions internals/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,30 @@ macro_rules! impl_from_infallible {
}
}
}

/// Implements `to_hex` for functions that have implemented [`core::fmt::LowerHex`]
#[macro_export]
#[cfg(feature = "alloc")]
macro_rules! impl_to_hex_from_lower_hex {
($t:ident, $hex_len_fn:expr) => {
impl $t {
/// Gets the hex representation of this type
pub fn to_hex(&self) -> alloc::string::String {
use core::fmt::Write;

let mut hex_string = alloc::string::String::with_capacity($hex_len_fn(self));
write!(&mut hex_string, "{:x}", self).expect("writing to string shouldn't fail");

hex_string
}
}
};
}

#[macro_export]
#[cfg(not(feature = "alloc"))]
macro_rules! impl_to_hex_from_lower_hex {
($t:ident, $hex_len_fn:expr) => {

};
}
2 changes: 1 addition & 1 deletion primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,5 @@ pub use self::{pow::CompactTarget, sequence::Sequence};
#[allow(unused_imports)]
mod prelude {
#[cfg(feature = "alloc")]
pub use alloc::string::ToString;
pub use alloc::string::{String, ToString};
}
2 changes: 2 additions & 0 deletions primitives/src/pow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! Proof-of-work related integer types.

use core::fmt;
use internals::impl_to_hex_from_lower_hex;

/// Encoding of 256-bit target as 32-bit float.
///
Expand Down Expand Up @@ -34,6 +35,7 @@ impl fmt::LowerHex for CompactTarget {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) }
}
impl_to_hex_from_lower_hex!(CompactTarget, |compact_target: &CompactTarget| 8 - compact_target.0.leading_zeros() as usize / 4);

impl fmt::UpperHex for CompactTarget {
#[inline]
Expand Down
4 changes: 2 additions & 2 deletions primitives/src/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,13 @@
//! [BIP-125]: <https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki>

use core::fmt;

use internals::impl_to_hex_from_lower_hex;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "alloc")]
use units::locktime::relative::TimeOverflowError;
#[cfg(feature = "alloc")]
use units::parse::{self, PrefixedHexError, UnprefixedHexError};

#[cfg(feature = "alloc")]
use crate::locktime::relative;

Expand Down Expand Up @@ -220,6 +219,7 @@ impl fmt::Display for Sequence {
impl fmt::LowerHex for Sequence {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) }
}
impl_to_hex_from_lower_hex!(Sequence, |sequence: &Sequence| 8 - sequence.0.leading_zeros() as usize / 4);

impl fmt::UpperHex for Sequence {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::UpperHex::fmt(&self.0, f) }
Expand Down

0 comments on commit 3b057ad

Please sign in to comment.