Merge rust-bitcoin/rust-bitcoin#4271: Make code style consistent and fix naming in macro Array implementations

e744347022 Make usage of Self and type uniform across both modules (Erick Cestari)
dfb49f014c Rename impl_try_from_array to impl_from_array (Erick Cestari)

Pull request description:

  This PR makes two main changes:

  1. Standardizes the function signatures in the `Amount` and `SignedAmount` implementations by consistently using `Self` as the return type instead of the concrete type names. This improves code consistency, maintainability, and follows Rust's idiomatic practices.
  2. Renames `impl_try_from_array` to `impl_from_array` to better reflect its functionality.

  ### Changes
  **Consistent usage of Self instead of concrete types**

  - Replace all occurrences of `-> Amount` with `-> Self `in unsigned.rs
  - Replace all occurrences of `-> SignedAmount` with `-> Self` in signed.rs
  - Make similar replacements for Option/Result return types
  - Use `Self::` instead of explicit type name for static method calls

  **Function rename**

  Renamed `impl_try_from_array` to `impl_from_array` for better clarity

  ### Related Issues

  Closes #4210

  Closes #4241

ACKs for top commit:
  Kixunil:
    ACK e744347022
  tcharding:
    ACK e744347022
  apoelstra:
    ACK e744347022d1ad1e0ca0a83ec9350501af08297b; successfully ran local tests

Tree-SHA512: 3113f3ccf595b298afe6b23514f1de790284df7fcb55a13658aabe3ef4fcea0e401b65b0a2c67ac18da87a1bcd247bd1f1484856fe03470b98dfa2614958a3bb
This commit is contained in:
merge-script 2025-03-25 19:39:23 +00:00
commit cf79f05ad6
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
3 changed files with 49 additions and 49 deletions

View File

@ -126,7 +126,7 @@ impl_try_from!(&[TapNodeHash]);
impl_try_from!(Vec<TapNodeHash>);
impl_try_from!(Box<[TapNodeHash]>);
macro_rules! impl_try_from_array {
macro_rules! impl_from_array {
($($len:expr),* $(,)?) => {
$(
impl From<[TapNodeHash; $len]> for TaprootMerkleBranchBuf {
@ -142,7 +142,7 @@ macro_rules! impl_try_from_array {
//
// The reason zero is included is that `TaprootMerkleBranchBuf` doesn't contain the hash of the node
// that's being proven - it's not needed because the script is already right before control block.
impl_try_from_array!(
impl_from_array!(
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,

View File

@ -61,8 +61,8 @@ mod encapsulate {
///
/// Accepts an `i32` which is guaranteed to be in range for the type, but which can only
/// represent roughly -21.47 to 21.47 BTC.
pub const fn from_sat_i32(satoshi: i32) -> SignedAmount {
SignedAmount(satoshi as i64) // cannot use i64::from in a constfn
pub const fn from_sat_i32(satoshi: i32) -> Self {
Self(satoshi as i64) // cannot use i64::from in a constfn
}
/// Gets the number of satoshis in this [`SignedAmount`].
@ -90,7 +90,7 @@ mod encapsulate {
/// assert_eq!(amount.to_sat(), sat);
/// # Ok::<_, amount::OutOfRangeError>(())
/// ```
pub const fn from_sat(satoshi: i64) -> Result<SignedAmount, OutOfRangeError> {
pub const fn from_sat(satoshi: i64) -> Result<Self, OutOfRangeError> {
if satoshi < Self::MIN.to_sat() {
Err(OutOfRangeError { is_signed: true, is_greater_than_max: false })
} else if satoshi > Self::MAX_MONEY.to_sat() {
@ -106,13 +106,13 @@ pub use encapsulate::SignedAmount;
impl SignedAmount {
/// The zero amount.
pub const ZERO: Self = SignedAmount::from_sat_i32(0);
pub const ZERO: Self = Self::from_sat_i32(0);
/// Exactly one satoshi.
pub const ONE_SAT: Self = SignedAmount::from_sat_i32(1);
pub const ONE_SAT: Self = Self::from_sat_i32(1);
/// Exactly one bitcoin.
pub const ONE_BTC: Self = SignedAmount::from_btc_i16(1);
pub const ONE_BTC: Self = Self::from_btc_i16(1);
/// Exactly fifty bitcoin.
pub const FIFTY_BTC: Self = SignedAmount::from_btc_i16(50);
pub const FIFTY_BTC: Self = Self::from_btc_i16(50);
/// The maximum value allowed as an amount. Useful for sanity checking.
pub const MAX_MONEY: Self = Self::MAX;
@ -133,24 +133,24 @@ impl SignedAmount {
/// # Ok::<_, amount::ParseAmountError>(())
/// ```
#[cfg(feature = "alloc")]
pub fn from_btc(btc: f64) -> Result<SignedAmount, ParseAmountError> {
pub fn from_btc(btc: f64) -> Result<Self, ParseAmountError> {
Self::from_float_in(btc, Denomination::Bitcoin)
}
/// Converts from a value expressing a whole number of bitcoin to a [`SignedAmount`].
#[allow(clippy::missing_panics_doc)]
pub fn from_int_btc<T: Into<i16>>(whole_bitcoin: T) -> SignedAmount {
SignedAmount::from_btc_i16(whole_bitcoin.into())
pub fn from_int_btc<T: Into<i16>>(whole_bitcoin: T) -> Self {
Self::from_btc_i16(whole_bitcoin.into())
}
/// Converts from a value expressing a whole number of bitcoin to a [`SignedAmount`]
/// in const context.
#[allow(clippy::missing_panics_doc)]
pub const fn from_btc_i16(whole_bitcoin: i16) -> SignedAmount {
pub const fn from_btc_i16(whole_bitcoin: i16) -> Self {
let btc = whole_bitcoin as i64; // Can't call `into` in const context.
let sats = btc * 100_000_000;
match SignedAmount::from_sat(sats) {
match Self::from_sat(sats) {
Ok(amount) => amount,
Err(_) => panic!("unreachable - 65536 BTC is within range"),
}
@ -164,7 +164,7 @@ impl SignedAmount {
/// # Errors
///
/// If the amount is too big (positive or negative) or too precise.
pub fn from_str_in(s: &str, denom: Denomination) -> Result<SignedAmount, ParseAmountError> {
pub fn from_str_in(s: &str, denom: Denomination) -> Result<Self, ParseAmountError> {
parse_signed_to_satoshi(s, denom)
.map(|(_, amount)| amount)
.map_err(|error| error.convert(true))
@ -187,7 +187,7 @@ impl SignedAmount {
/// assert_eq!(amount, SignedAmount::from_sat(10_000_000)?);
/// # Ok::<_, amount::ParseError>(())
/// ```
pub fn from_str_with_denomination(s: &str) -> Result<SignedAmount, ParseError> {
pub fn from_str_with_denomination(s: &str) -> Result<Self, ParseError> {
let (amt, denom) = split_amount_and_denomination(s)?;
Self::from_str_in(amt, denom).map_err(Into::into)
}
@ -236,7 +236,7 @@ impl SignedAmount {
pub fn from_float_in(
value: f64,
denom: Denomination,
) -> Result<SignedAmount, ParseAmountError> {
) -> Result<Self, ParseAmountError> {
// This is inefficient, but the safest way to deal with this. The parsing logic is safe.
// Any performance-critical application should not be dealing with floats.
Self::from_str_in(&value.to_string(), denom)
@ -315,7 +315,7 @@ impl SignedAmount {
///
/// This function never overflows or panics, unlike `i64::abs()`.
#[must_use]
pub const fn abs(self) -> SignedAmount {
pub const fn abs(self) -> Self {
// `i64::abs()` can never overflow because SignedAmount::MIN == -MAX_MONEY.
match Self::from_sat(self.to_sat().abs()) {
Ok(amount) => amount,
@ -358,16 +358,16 @@ impl SignedAmount {
#[must_use]
#[deprecated(since = "TBD", note = "Never returns none, use `abs()` instead")]
#[allow(clippy::unnecessary_wraps)] // To match stdlib function definition.
pub const fn checked_abs(self) -> Option<SignedAmount> { Some(self.abs()) }
pub const fn checked_abs(self) -> Option<Self> { Some(self.abs()) }
/// Checked addition.
///
/// Returns [`None`] if the sum is above [`SignedAmount::MAX`] or below [`SignedAmount::MIN`].
#[must_use]
pub const fn checked_add(self, rhs: SignedAmount) -> Option<SignedAmount> {
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
// No `map()` in const context.
match self.to_sat().checked_add(rhs.to_sat()) {
Some(res) => match SignedAmount::from_sat(res) {
Some(res) => match Self::from_sat(res) {
Ok(amount) => Some(amount),
Err(_) => None,
},
@ -380,7 +380,7 @@ impl SignedAmount {
/// Returns [`None`] if the difference is above [`SignedAmount::MAX`] or below
/// [`SignedAmount::MIN`].
#[must_use]
pub const fn checked_sub(self, rhs: SignedAmount) -> Option<SignedAmount> {
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
// No `map()` in const context.
match self.to_sat().checked_sub(rhs.to_sat()) {
Some(res) => match Self::from_sat(res) {
@ -396,7 +396,7 @@ impl SignedAmount {
/// Returns [`None`] if the product is above [`SignedAmount::MAX`] or below
/// [`SignedAmount::MIN`].
#[must_use]
pub const fn checked_mul(self, rhs: i64) -> Option<SignedAmount> {
pub const fn checked_mul(self, rhs: i64) -> Option<Self> {
// No `map()` in const context.
match self.to_sat().checked_mul(rhs) {
Some(res) => match Self::from_sat(res) {
@ -413,7 +413,7 @@ impl SignedAmount {
///
/// Returns [`None`] if overflow occurred.
#[must_use]
pub const fn checked_div(self, rhs: i64) -> Option<SignedAmount> {
pub const fn checked_div(self, rhs: i64) -> Option<Self> {
// No `map()` in const context.
match self.to_sat().checked_div(rhs) {
Some(res) => match Self::from_sat(res) {
@ -428,7 +428,7 @@ impl SignedAmount {
///
/// Returns [`None`] if overflow occurred.
#[must_use]
pub const fn checked_rem(self, rhs: i64) -> Option<SignedAmount> {
pub const fn checked_rem(self, rhs: i64) -> Option<Self> {
// No `map()` in const context.
match self.to_sat().checked_rem(rhs) {
Some(res) => match Self::from_sat(res) {
@ -443,7 +443,7 @@ impl SignedAmount {
///
/// Returns [`None`] if either `self`, `rhs` or the result is strictly negative.
#[must_use]
pub fn positive_sub(self, rhs: SignedAmount) -> Option<SignedAmount> {
pub fn positive_sub(self, rhs: Self) -> Option<Self> {
if self.is_negative() || rhs.is_negative() || rhs > self {
None
} else {
@ -469,7 +469,7 @@ impl SignedAmount {
}
impl default::Default for SignedAmount {
fn default() -> Self { SignedAmount::ZERO }
fn default() -> Self { Self::ZERO }
}
impl fmt::Debug for SignedAmount {

View File

@ -61,8 +61,8 @@ mod encapsulate {
///
/// Accepts an `u32` which is guaranteed to be in range for the type, but which can only
/// represent roughly 0 to 42.95 BTC.
pub const fn from_sat_u32(satoshi: u32) -> Amount {
Amount(satoshi as u64) // cannot use u64::from in a constfn
pub const fn from_sat_u32(satoshi: u32) -> Self {
Self(satoshi as u64) // cannot use u64::from in a constfn
}
/// Gets the number of satoshis in this [`Amount`].
@ -90,7 +90,7 @@ mod encapsulate {
/// assert_eq!(amount.to_sat(), sat);
/// # Ok::<_, amount::OutOfRangeError>(())
/// ```
pub const fn from_sat(satoshi: u64) -> Result<Amount, OutOfRangeError> {
pub const fn from_sat(satoshi: u64) -> Result<Self, OutOfRangeError> {
if satoshi > Self::MAX_MONEY.to_sat() {
Err(OutOfRangeError { is_signed: false, is_greater_than_max: true })
} else {
@ -104,15 +104,15 @@ pub use encapsulate::Amount;
impl Amount {
/// The zero amount.
pub const ZERO: Self = Amount::from_sat_u32(0);
pub const ZERO: Self = Self::from_sat_u32(0);
/// Exactly one satoshi.
pub const ONE_SAT: Self = Amount::from_sat_u32(1);
pub const ONE_SAT: Self = Self::from_sat_u32(1);
/// Exactly one bitcoin.
pub const ONE_BTC: Self = Amount::from_btc_u16(1);
pub const ONE_BTC: Self = Self::from_btc_u16(1);
/// Exactly fifty bitcoin.
pub const FIFTY_BTC: Self = Amount::from_btc_u16(50);
pub const FIFTY_BTC: Self = Self::from_btc_u16(50);
/// The maximum value allowed as an amount. Useful for sanity checking.
pub const MAX_MONEY: Self = Amount::MAX;
pub const MAX_MONEY: Self = Self::MAX;
/// The number of bytes that an amount contributes to the size of a transaction.
pub const SIZE: usize = 8; // Serialized length of a u64.
@ -133,24 +133,24 @@ impl Amount {
/// # Ok::<_, amount::ParseAmountError>(())
/// ```
#[cfg(feature = "alloc")]
pub fn from_btc(btc: f64) -> Result<Amount, ParseAmountError> {
pub fn from_btc(btc: f64) -> Result<Self, ParseAmountError> {
Self::from_float_in(btc, Denomination::Bitcoin)
}
/// Converts from a value expressing a whole number of bitcoin to an [`Amount`].
#[allow(clippy::missing_panics_doc)]
pub fn from_int_btc<T: Into<u16>>(whole_bitcoin: T) -> Amount {
Amount::from_btc_u16(whole_bitcoin.into())
pub fn from_int_btc<T: Into<u16>>(whole_bitcoin: T) -> Self {
Self::from_btc_u16(whole_bitcoin.into())
}
/// Converts from a value expressing a whole number of bitcoin to an [`Amount`]
/// in const context.
#[allow(clippy::missing_panics_doc)]
pub const fn from_btc_u16(whole_bitcoin: u16) -> Amount {
pub const fn from_btc_u16(whole_bitcoin: u16) -> Self {
let btc = whole_bitcoin as u64; // Can't call `into` in const context.
let sats = btc * 100_000_000;
match Amount::from_sat(sats) {
match Self::from_sat(sats) {
Ok(amount) => amount,
Err(_) => panic!("unreachable - 65536 BTC is within range"),
}
@ -164,7 +164,7 @@ impl Amount {
/// # Errors
///
/// If the amount is too precise, negative, or greater than 21,000,000.
pub fn from_str_in(s: &str, denom: Denomination) -> Result<Amount, ParseAmountError> {
pub fn from_str_in(s: &str, denom: Denomination) -> Result<Self, ParseAmountError> {
let (is_neg, amount) =
parse_signed_to_satoshi(s, denom).map_err(|error| error.convert(false))?;
if is_neg {
@ -192,7 +192,7 @@ impl Amount {
/// assert_eq!(amount, Amount::from_sat(10_000_000)?);
/// # Ok::<_, amount::ParseError>(())
/// ```
pub fn from_str_with_denomination(s: &str) -> Result<Amount, ParseError> {
pub fn from_str_with_denomination(s: &str) -> Result<Self, ParseError> {
let (amt, denom) = split_amount_and_denomination(s)?;
Self::from_str_in(amt, denom).map_err(Into::into)
}
@ -238,7 +238,7 @@ impl Amount {
///
/// Please be aware of the risk of using floating-point numbers.
#[cfg(feature = "alloc")]
pub fn from_float_in(value: f64, denom: Denomination) -> Result<Amount, ParseAmountError> {
pub fn from_float_in(value: f64, denom: Denomination) -> Result<Self, ParseAmountError> {
if value < 0.0 {
return Err(OutOfRangeError::negative().into());
}
@ -320,7 +320,7 @@ impl Amount {
///
/// Returns [`None`] if the sum is larger than [`Amount::MAX`].
#[must_use]
pub const fn checked_add(self, rhs: Amount) -> Option<Amount> {
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
// No `map()` in const context.
// Unchecked add ok, adding two values less than `MAX_MONEY` cannot overflow an `i64`.
match Self::from_sat(self.to_sat() + rhs.to_sat()) {
@ -333,7 +333,7 @@ impl Amount {
///
/// Returns [`None`] if overflow occurred.
#[must_use]
pub const fn checked_sub(self, rhs: Amount) -> Option<Amount> {
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
// No `map()` in const context.
match self.to_sat().checked_sub(rhs.to_sat()) {
Some(res) => match Self::from_sat(res) {
@ -348,7 +348,7 @@ impl Amount {
///
/// Returns [`None`] if the product is larger than [`Amount::MAX`].
#[must_use]
pub const fn checked_mul(self, rhs: u64) -> Option<Amount> {
pub const fn checked_mul(self, rhs: u64) -> Option<Self> {
// No `map()` in const context.
match self.to_sat().checked_mul(rhs) {
Some(res) => match Self::from_sat(res) {
@ -365,7 +365,7 @@ impl Amount {
///
/// Returns [`None`] if overflow occurred.
#[must_use]
pub const fn checked_div(self, rhs: u64) -> Option<Amount> {
pub const fn checked_div(self, rhs: u64) -> Option<Self> {
// No `map()` in const context.
match self.to_sat().checked_div(rhs) {
Some(res) => match Self::from_sat(res) {
@ -380,7 +380,7 @@ impl Amount {
///
/// Returns [`None`] if overflow occurred.
#[must_use]
pub const fn checked_rem(self, rhs: u64) -> Option<Amount> {
pub const fn checked_rem(self, rhs: u64) -> Option<Self> {
// No `map()` in const context.
match self.to_sat().checked_rem(rhs) {
Some(res) => match Self::from_sat(res) {
@ -401,7 +401,7 @@ impl Amount {
}
impl default::Default for Amount {
fn default() -> Self { Amount::ZERO }
fn default() -> Self { Self::ZERO }
}
impl fmt::Debug for Amount {