Merge rust-bitcoin/rust-bitcoin#1829: Remove `min_value` and `max_value`

6cab7beba3 Deprecate min/max_value methods (Tobin C. Harding)
5fbbd483ea Use MIN/MAX consts instead of min/max_value (Tobin C. Harding)
3885f4d430 Add MIN/MAX consts to amounts (Tobin C. Harding)

Pull request description:

  The new MSRV (1.48.0) uses associated consts MAX/MIN instead of functions, we had functions to be compliant with the old MSRV.

  ~Remove all methods `min_value` and `max_value` including calls to these methods on stdlib types.~

  PR is now split into three patches:
  - patch 1: Add missing associated consts MIN/MAX as needed
  - patch 2: Use consts instead of method calls
  - patch 3: Deprecate methods `min_value` and `max_value`

ACKs for top commit:
  sanket1729:
    ACK 6cab7beba3
  apoelstra:
    ACK 6cab7beba3
  Kixunil:
    ACK 6cab7beba3

Tree-SHA512: 60949d1bb971e0dfbab7f573b4447f889b5fa1a5f1c9ac9325a2970fe17a19ccc93418dba57f07bed7e13864b130de48b6b3741d1d80266c6144237dd4565ff7
This commit is contained in:
Andrew Poelstra 2023-05-04 12:20:15 +00:00
commit ac664106be
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
13 changed files with 81 additions and 62 deletions

View File

@ -494,6 +494,10 @@ impl Amount {
pub const ONE_BTC: Amount = Amount(100_000_000); pub const ONE_BTC: Amount = Amount(100_000_000);
/// The maximum value allowed as an amount. Useful for sanity checking. /// The maximum value allowed as an amount. Useful for sanity checking.
pub const MAX_MONEY: Amount = Amount(21_000_000 * 100_000_000); pub const MAX_MONEY: Amount = Amount(21_000_000 * 100_000_000);
/// The minimum value of an amount.
pub const MIN: Amount = Amount::ZERO;
/// The maximum value of an amount.
pub const MAX: Amount = Amount(u64::MAX);
/// Create an [Amount] with satoshi precision and the given number of satoshis. /// Create an [Amount] with satoshi precision and the given number of satoshis.
pub const fn from_sat(satoshi: u64) -> Amount { Amount(satoshi) } pub const fn from_sat(satoshi: u64) -> Amount { Amount(satoshi) }
@ -502,9 +506,11 @@ impl Amount {
pub fn to_sat(self) -> u64 { self.0 } pub fn to_sat(self) -> u64 { self.0 }
/// The maximum value of an [Amount]. /// The maximum value of an [Amount].
#[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
pub const fn max_value() -> Amount { Amount(u64::max_value()) } pub const fn max_value() -> Amount { Amount(u64::max_value()) }
/// The minimum value of an [Amount]. /// The minimum value of an [Amount].
#[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
pub const fn min_value() -> Amount { Amount(u64::min_value()) } pub const fn min_value() -> Amount { Amount(u64::min_value()) }
/// Convert from a value expressing bitcoins to an [Amount]. /// Convert from a value expressing bitcoins to an [Amount].
@ -521,7 +527,7 @@ impl Amount {
if negative { if negative {
return Err(ParseAmountError::Negative); return Err(ParseAmountError::Negative);
} }
if satoshi > i64::max_value() as u64 { if satoshi > i64::MAX as u64 {
return Err(ParseAmountError::TooBig); return Err(ParseAmountError::TooBig);
} }
Ok(Amount::from_sat(satoshi)) Ok(Amount::from_sat(satoshi))
@ -646,7 +652,7 @@ impl Amount {
/// Convert to a signed amount. /// Convert to a signed amount.
pub fn to_signed(self) -> Result<SignedAmount, ParseAmountError> { pub fn to_signed(self) -> Result<SignedAmount, ParseAmountError> {
if self.to_sat() > SignedAmount::max_value().to_sat() as u64 { if self.to_sat() > SignedAmount::MAX.to_sat() as u64 {
Err(ParseAmountError::TooBig) Err(ParseAmountError::TooBig)
} else { } else {
Ok(SignedAmount::from_sat(self.to_sat() as i64)) Ok(SignedAmount::from_sat(self.to_sat() as i64))
@ -829,6 +835,10 @@ impl SignedAmount {
pub const ONE_BTC: SignedAmount = SignedAmount(100_000_000); pub const ONE_BTC: SignedAmount = SignedAmount(100_000_000);
/// The maximum value allowed as an amount. Useful for sanity checking. /// The maximum value allowed as an amount. Useful for sanity checking.
pub const MAX_MONEY: SignedAmount = SignedAmount(21_000_000 * 100_000_000); pub const MAX_MONEY: SignedAmount = SignedAmount(21_000_000 * 100_000_000);
/// The minimum value of an amount.
pub const MIN: SignedAmount = SignedAmount(i64::MIN);
/// The maximum value of an amount.
pub const MAX: SignedAmount = SignedAmount(i64::MAX);
/// Create an [SignedAmount] with satoshi precision and the given number of satoshis. /// Create an [SignedAmount] with satoshi precision and the given number of satoshis.
pub const fn from_sat(satoshi: i64) -> SignedAmount { SignedAmount(satoshi) } pub const fn from_sat(satoshi: i64) -> SignedAmount { SignedAmount(satoshi) }
@ -837,9 +847,11 @@ impl SignedAmount {
pub fn to_sat(self) -> i64 { self.0 } pub fn to_sat(self) -> i64 { self.0 }
/// The maximum value of an [SignedAmount]. /// The maximum value of an [SignedAmount].
#[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
pub const fn max_value() -> SignedAmount { SignedAmount(i64::max_value()) } pub const fn max_value() -> SignedAmount { SignedAmount(i64::max_value()) }
/// The minimum value of an [SignedAmount]. /// The minimum value of an [SignedAmount].
#[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
pub const fn min_value() -> SignedAmount { SignedAmount(i64::min_value()) } pub const fn min_value() -> SignedAmount { SignedAmount(i64::min_value()) }
/// Convert from a value expressing bitcoins to an [SignedAmount]. /// Convert from a value expressing bitcoins to an [SignedAmount].
@ -853,7 +865,7 @@ impl SignedAmount {
/// with denomination, use [FromStr]. /// with denomination, use [FromStr].
pub fn from_str_in(s: &str, denom: Denomination) -> Result<SignedAmount, ParseAmountError> { pub fn from_str_in(s: &str, denom: Denomination) -> Result<SignedAmount, ParseAmountError> {
let (negative, satoshi) = parse_signed_to_satoshi(s, denom)?; let (negative, satoshi) = parse_signed_to_satoshi(s, denom)?;
if satoshi > i64::max_value() as u64 { if satoshi > i64::MAX as u64 {
return Err(ParseAmountError::TooBig); return Err(ParseAmountError::TooBig);
} }
Ok(match negative { Ok(match negative {
@ -972,7 +984,7 @@ impl SignedAmount {
pub fn is_negative(self) -> bool { self.0.is_negative() } pub fn is_negative(self) -> bool { self.0.is_negative() }
/// Get the absolute value of this [SignedAmount]. /// Get the absolute value of this [SignedAmount].
/// Returns [None] if overflow occurred. (`self == min_value()`) /// Returns [None] if overflow occurred. (`self == MIN`)
pub fn checked_abs(self) -> Option<SignedAmount> { self.0.checked_abs().map(SignedAmount) } pub fn checked_abs(self) -> Option<SignedAmount> { self.0.checked_abs().map(SignedAmount) }
/// Checked addition. /// Checked addition.
@ -1575,7 +1587,7 @@ mod tests {
#[test] #[test]
fn test_overflows() { fn test_overflows() {
// panic on overflow // panic on overflow
let result = panic::catch_unwind(|| Amount::max_value() + Amount::from_sat(1)); let result = panic::catch_unwind(|| Amount::MAX + Amount::from_sat(1));
assert!(result.is_err()); assert!(result.is_err());
let result = panic::catch_unwind(|| Amount::from_sat(8446744073709551615) * 3); let result = panic::catch_unwind(|| Amount::from_sat(8446744073709551615) * 3);
assert!(result.is_err()); assert!(result.is_err());
@ -1586,10 +1598,10 @@ mod tests {
let sat = Amount::from_sat; let sat = Amount::from_sat;
let ssat = SignedAmount::from_sat; let ssat = SignedAmount::from_sat;
assert_eq!(SignedAmount::max_value().checked_add(ssat(1)), None); assert_eq!(SignedAmount::MAX.checked_add(ssat(1)), None);
assert_eq!(SignedAmount::min_value().checked_sub(ssat(1)), None); assert_eq!(SignedAmount::MIN.checked_sub(ssat(1)), None);
assert_eq!(Amount::max_value().checked_add(sat(1)), None); assert_eq!(Amount::MAX.checked_add(sat(1)), None);
assert_eq!(Amount::min_value().checked_sub(sat(1)), None); assert_eq!(Amount::MIN.checked_sub(sat(1)), None);
assert_eq!(sat(5).checked_div(2), Some(sat(2))); // integer division assert_eq!(sat(5).checked_div(2), Some(sat(2))); // integer division
assert_eq!(ssat(-6).checked_div(2), Some(ssat(-3))); assert_eq!(ssat(-6).checked_div(2), Some(ssat(-3)));
@ -1618,11 +1630,11 @@ mod tests {
assert_eq!(sf(-184467440738.0, D::Bitcoin), Err(ParseAmountError::TooBig)); assert_eq!(sf(-184467440738.0, D::Bitcoin), Err(ParseAmountError::TooBig));
assert_eq!(f(18446744073709551617.0, D::Satoshi), Err(ParseAmountError::TooBig)); assert_eq!(f(18446744073709551617.0, D::Satoshi), Err(ParseAmountError::TooBig));
assert_eq!( assert_eq!(
f(SignedAmount::max_value().to_float_in(D::Satoshi) + 1.0, D::Satoshi), f(SignedAmount::MAX.to_float_in(D::Satoshi) + 1.0, D::Satoshi),
Err(ParseAmountError::TooBig) Err(ParseAmountError::TooBig)
); );
assert_eq!( assert_eq!(
f(Amount::max_value().to_float_in(D::Satoshi) + 1.0, D::Satoshi), f(Amount::MAX.to_float_in(D::Satoshi) + 1.0, D::Satoshi),
Err(ParseAmountError::TooBig) Err(ParseAmountError::TooBig)
); );
@ -1651,7 +1663,7 @@ mod tests {
assert_eq!(p("-1.0x", btc), Err(E::InvalidCharacter('x'))); assert_eq!(p("-1.0x", btc), Err(E::InvalidCharacter('x')));
assert_eq!(p("0.0 ", btc), Err(ParseAmountError::InvalidCharacter(' '))); assert_eq!(p("0.0 ", btc), Err(ParseAmountError::InvalidCharacter(' ')));
assert_eq!(p("0.000.000", btc), Err(E::InvalidFormat)); assert_eq!(p("0.000.000", btc), Err(E::InvalidFormat));
let more_than_max = format!("1{}", Amount::max_value()); let more_than_max = format!("1{}", Amount::MAX);
assert_eq!(p(&more_than_max, btc), Err(E::TooBig)); assert_eq!(p(&more_than_max, btc), Err(E::TooBig));
assert_eq!(p("0.000000042", btc), Err(E::TooPrecise)); assert_eq!(p("0.000000042", btc), Err(E::TooPrecise));
@ -1668,8 +1680,8 @@ mod tests {
Ok(Amount::from_sat(12_345_678_901__123_456_78)) Ok(Amount::from_sat(12_345_678_901__123_456_78))
); );
// make sure satoshi > i64::max_value() is checked. // make sure satoshi > i64::MAX is checked.
let amount = Amount::from_sat(i64::max_value() as u64); let amount = Amount::from_sat(i64::MAX as u64);
assert_eq!(Amount::from_str_in(&amount.to_string_in(sat), sat), Ok(amount)); assert_eq!(Amount::from_str_in(&amount.to_string_in(sat), sat), Ok(amount));
assert_eq!( assert_eq!(
Amount::from_str_in(&(amount + Amount(1)).to_string_in(sat), sat), Amount::from_str_in(&(amount + Amount(1)).to_string_in(sat), sat),
@ -1900,16 +1912,13 @@ mod tests {
let sa = SignedAmount::from_sat; let sa = SignedAmount::from_sat;
let ua = Amount::from_sat; let ua = Amount::from_sat;
assert_eq!(Amount::max_value().to_signed(), Err(E::TooBig)); assert_eq!(Amount::MAX.to_signed(), Err(E::TooBig));
assert_eq!(ua(i64::max_value() as u64).to_signed(), Ok(sa(i64::max_value()))); assert_eq!(ua(i64::MAX as u64).to_signed(), Ok(sa(i64::MAX)));
assert_eq!(ua(i64::max_value() as u64 + 1).to_signed(), Err(E::TooBig)); assert_eq!(ua(i64::MAX as u64 + 1).to_signed(), Err(E::TooBig));
assert_eq!(sa(i64::max_value()).to_unsigned(), Ok(ua(i64::max_value() as u64))); assert_eq!(sa(i64::MAX).to_unsigned(), Ok(ua(i64::MAX as u64)));
assert_eq!( assert_eq!(sa(i64::MAX).to_unsigned().unwrap().to_signed(), Ok(sa(i64::MAX)));
sa(i64::max_value()).to_unsigned().unwrap().to_signed(),
Ok(sa(i64::max_value()))
);
} }
#[test] #[test]
@ -1997,7 +2006,7 @@ mod tests {
Ok(ua_sat(1_000_000_000_000)) Ok(ua_sat(1_000_000_000_000))
); );
assert_eq!( assert_eq!(
ua_str(&ua_sat(u64::max_value()).to_string_in(D::MilliBitcoin), D::MilliBitcoin), ua_str(&ua_sat(u64::MAX).to_string_in(D::MilliBitcoin), D::MilliBitcoin),
Err(ParseAmountError::TooBig) Err(ParseAmountError::TooBig)
); );
@ -2007,12 +2016,12 @@ mod tests {
); );
assert_eq!( assert_eq!(
sa_str(&sa_sat(i64::max_value()).to_string_in(D::Satoshi), D::MicroBitcoin), sa_str(&sa_sat(i64::MAX).to_string_in(D::Satoshi), D::MicroBitcoin),
Err(ParseAmountError::TooBig) Err(ParseAmountError::TooBig)
); );
// Test an overflow bug in `abs()` // Test an overflow bug in `abs()`
assert_eq!( assert_eq!(
sa_str(&sa_sat(i64::min_value()).to_string_in(D::Satoshi), D::MicroBitcoin), sa_str(&sa_sat(i64::MIN).to_string_in(D::Satoshi), D::MicroBitcoin),
Err(ParseAmountError::TooBig) Err(ParseAmountError::TooBig)
); );
@ -2021,11 +2030,11 @@ mod tests {
Ok(sa_sat(-1)) Ok(sa_sat(-1))
); );
assert_eq!( assert_eq!(
sa_str(&sa_sat(i64::max_value()).to_string_in(D::Satoshi), D::NanoBitcoin), sa_str(&sa_sat(i64::MAX).to_string_in(D::Satoshi), D::NanoBitcoin),
Err(ParseAmountError::TooPrecise) Err(ParseAmountError::TooPrecise)
); );
assert_eq!( assert_eq!(
sa_str(&sa_sat(i64::min_value()).to_string_in(D::Satoshi), D::NanoBitcoin), sa_str(&sa_sat(i64::MIN).to_string_in(D::Satoshi), D::NanoBitcoin),
Err(ParseAmountError::TooPrecise) Err(ParseAmountError::TooPrecise)
); );
@ -2034,11 +2043,11 @@ mod tests {
Ok(sa_sat(-1)) Ok(sa_sat(-1))
); );
assert_eq!( assert_eq!(
sa_str(&sa_sat(i64::max_value()).to_string_in(D::Satoshi), D::PicoBitcoin), sa_str(&sa_sat(i64::MAX).to_string_in(D::Satoshi), D::PicoBitcoin),
Err(ParseAmountError::TooPrecise) Err(ParseAmountError::TooPrecise)
); );
assert_eq!( assert_eq!(
sa_str(&sa_sat(i64::min_value()).to_string_in(D::Satoshi), D::PicoBitcoin), sa_str(&sa_sat(i64::MIN).to_string_in(D::Satoshi), D::PicoBitcoin),
Err(ParseAmountError::TooPrecise) Err(ParseAmountError::TooPrecise)
); );
} }
@ -2240,12 +2249,12 @@ mod tests {
assert_eq!(Some(Amount::from_sat(1400)), sum); assert_eq!(Some(Amount::from_sat(1400)), sum);
let amounts = let amounts =
vec![Amount::from_sat(u64::max_value()), Amount::from_sat(1337), Amount::from_sat(21)]; vec![Amount::from_sat(u64::MAX), Amount::from_sat(1337), Amount::from_sat(21)];
let sum = amounts.into_iter().checked_sum(); let sum = amounts.into_iter().checked_sum();
assert_eq!(None, sum); assert_eq!(None, sum);
let amounts = vec![ let amounts = vec![
SignedAmount::from_sat(i64::min_value()), SignedAmount::from_sat(i64::MIN),
SignedAmount::from_sat(-1), SignedAmount::from_sat(-1),
SignedAmount::from_sat(21), SignedAmount::from_sat(21),
]; ];
@ -2253,7 +2262,7 @@ mod tests {
assert_eq!(None, sum); assert_eq!(None, sum);
let amounts = vec![ let amounts = vec![
SignedAmount::from_sat(i64::max_value()), SignedAmount::from_sat(i64::MAX),
SignedAmount::from_sat(1), SignedAmount::from_sat(1),
SignedAmount::from_sat(21), SignedAmount::from_sat(21),
]; ];

View File

@ -28,10 +28,10 @@ impl FeeRate {
/// Minimum possible value (0 sat/kwu). /// Minimum possible value (0 sat/kwu).
/// ///
/// Equivalent to [`ZERO`](Self::ZERO), may better express intent in some contexts. /// Equivalent to [`ZERO`](Self::ZERO), may better express intent in some contexts.
pub const MIN: FeeRate = FeeRate(u64::min_value()); pub const MIN: FeeRate = FeeRate::ZERO;
/// Maximum possible value. /// Maximum possible value.
pub const MAX: FeeRate = FeeRate(u64::max_value()); pub const MAX: FeeRate = FeeRate(u64::MAX);
/// Minimum fee rate required to broadcast a transaction. /// Minimum fee rate required to broadcast a transaction.
/// ///
@ -128,8 +128,8 @@ mod tests {
#[test] #[test]
fn fee_rate_const_test() { fn fee_rate_const_test() {
assert_eq!(0, FeeRate::ZERO.to_sat_per_kwu()); assert_eq!(0, FeeRate::ZERO.to_sat_per_kwu());
assert_eq!(u64::min_value(), FeeRate::MIN.to_sat_per_kwu()); assert_eq!(u64::MIN, FeeRate::MIN.to_sat_per_kwu());
assert_eq!(u64::max_value(), FeeRate::MAX.to_sat_per_kwu()); assert_eq!(u64::MAX, FeeRate::MAX.to_sat_per_kwu());
assert_eq!(250, FeeRate::BROADCAST_MIN.to_sat_per_kwu()); assert_eq!(250, FeeRate::BROADCAST_MIN.to_sat_per_kwu());
assert_eq!(750, FeeRate::DUST.to_sat_per_kwu()); assert_eq!(750, FeeRate::DUST.to_sat_per_kwu());
} }

View File

@ -397,11 +397,13 @@ impl Height {
/// The minimum absolute block height (0), the genesis block. /// The minimum absolute block height (0), the genesis block.
/// ///
/// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MIN`]. /// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MIN`].
#[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
pub const fn min_value() -> Self { Self::MIN } pub const fn min_value() -> Self { Self::MIN }
/// The maximum absolute block height. /// The maximum absolute block height.
/// ///
/// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MAX`]. /// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MAX`].
#[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
pub const fn max_value() -> Self { Self::MAX } pub const fn max_value() -> Self { Self::MAX }
/// Constructs a new block height. /// Constructs a new block height.
@ -477,11 +479,13 @@ impl Time {
/// The minimum absolute block time. /// The minimum absolute block time.
/// ///
/// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MIN`]. /// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MIN`].
#[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
pub const fn min_value() -> Self { Self::MIN } pub const fn min_value() -> Self { Self::MIN }
/// The maximum absolute block time. /// The maximum absolute block time.
/// ///
/// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MAX`]. /// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MAX`].
#[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
pub const fn max_value() -> Self { Self::MAX } pub const fn max_value() -> Self { Self::MAX }
/// Constructs a new block time. /// Constructs a new block time.

View File

@ -210,11 +210,13 @@ impl Height {
/// The minimum relative block height (0), can be included in any block. /// The minimum relative block height (0), can be included in any block.
/// ///
/// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MIN`]. /// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MIN`].
#[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
pub const fn min_value() -> Self { Self::MIN } pub const fn min_value() -> Self { Self::MIN }
/// The maximum relative block height. /// The maximum relative block height.
/// ///
/// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MAX`]. /// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MAX`].
#[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
pub const fn max_value() -> Self { Self::MAX } pub const fn max_value() -> Self { Self::MAX }
/// Returns the inner `u16` value. /// Returns the inner `u16` value.
@ -254,11 +256,13 @@ impl Time {
/// The minimum relative block time. /// The minimum relative block time.
/// ///
/// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MIN`]. /// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MIN`].
#[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
pub const fn min_value() -> Self { Self::MIN } pub const fn min_value() -> Self { Self::MIN }
/// The maximum relative block time. /// The maximum relative block time.
/// ///
/// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MAX`]. /// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MAX`].
#[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
pub const fn max_value() -> Self { Self::MAX } pub const fn max_value() -> Self { Self::MAX }
/// Create a [`Time`] using time intervals where each interval is equivalent to 512 seconds. /// Create a [`Time`] using time intervals where each interval is equivalent to 512 seconds.

View File

@ -88,7 +88,7 @@ impl<'a> Instructions<'a> {
// We do exhaustive matching to not forget to handle new variants if we extend // We do exhaustive matching to not forget to handle new variants if we extend
// `UintError` type. // `UintError` type.
// Overflow actually means early end of script (script is definitely shorter // Overflow actually means early end of script (script is definitely shorter
// than `usize::max_value()`) // than `usize::MAX`)
Err(UintError::EarlyEndOfScript) | Err(UintError::NumericOverflow) => { Err(UintError::EarlyEndOfScript) | Err(UintError::NumericOverflow) => {
self.kill(); self.kill();
return Some(Err(Error::EarlyEndOfScript)); return Some(Err(Error::EarlyEndOfScript));

View File

@ -187,11 +187,11 @@ pub fn read_scriptbool(v: &[u8]) -> bool {
/// This function returns an error in these cases: /// This function returns an error in these cases:
/// ///
/// * `data` is shorter than `size` => `EarlyEndOfScript` /// * `data` is shorter than `size` => `EarlyEndOfScript`
/// * `size` is greater than `u16::max_value / 8` (8191) => `NumericOverflow` /// * `size` is greater than `u16::MAX / 8` (8191) => `NumericOverflow`
/// * The number being read overflows `usize` => `NumericOverflow` /// * The number being read overflows `usize` => `NumericOverflow`
/// ///
/// Note that this does **not** return an error for `size` between `core::size_of::<usize>()` /// Note that this does **not** return an error for `size` between `core::size_of::<usize>()`
/// and `u16::max_value / 8` if there's no overflow. /// and `u16::MAX / 8` if there's no overflow.
#[inline] #[inline]
#[deprecated(since = "0.30.0", note = "bitcoin integers are signed 32 bits, use read_scriptint")] #[deprecated(since = "0.30.0", note = "bitcoin integers are signed 32 bits, use read_scriptint")]
pub fn read_uint(data: &[u8], size: usize) -> Result<usize, Error> { pub fn read_uint(data: &[u8], size: usize) -> Result<usize, Error> {
@ -203,7 +203,7 @@ pub fn read_uint(data: &[u8], size: usize) -> Result<usize, Error> {
fn read_uint_iter(data: &mut core::slice::Iter<'_, u8>, size: usize) -> Result<usize, UintError> { fn read_uint_iter(data: &mut core::slice::Iter<'_, u8>, size: usize) -> Result<usize, UintError> {
if data.len() < size { if data.len() < size {
Err(UintError::EarlyEndOfScript) Err(UintError::EarlyEndOfScript)
} else if size > usize::from(u16::max_value() / 8) { } else if size > usize::from(u16::MAX / 8) {
// Casting to u32 would overflow // Casting to u32 would overflow
Err(UintError::NumericOverflow) Err(UintError::NumericOverflow)
} else { } else {
@ -596,7 +596,7 @@ pub(super) fn bytes_to_asm_fmt(script: &[u8], f: &mut dyn fmt::Write) -> fmt::Re
$formatter.write_str("<unexpected end>")?; $formatter.write_str("<unexpected end>")?;
break; break;
} }
// We got the data in a slice which implies it being shorter than `usize::max_value()` // We got the data in a slice which implies it being shorter than `usize::MAX`
// So if we got overflow, we can confidently say the number is higher than length of // So if we got overflow, we can confidently say the number is higher than length of
// the slice even though we don't know the exact number. This implies attempt to push // the slice even though we don't know the exact number. This implies attempt to push
// past end. // past end.

View File

@ -61,7 +61,7 @@ impl OutPoint {
/// ///
/// This value is used for coinbase transactions because they don't have any previous outputs. /// This value is used for coinbase transactions because they don't have any previous outputs.
#[inline] #[inline]
pub fn null() -> OutPoint { OutPoint { txid: Hash::all_zeros(), vout: u32::max_value() } } pub fn null() -> OutPoint { OutPoint { txid: Hash::all_zeros(), vout: u32::MAX } }
/// Checks if an `OutPoint` is "null". /// Checks if an `OutPoint` is "null".
/// ///
@ -305,6 +305,7 @@ impl Sequence {
/// The maximum allowable sequence number. /// The maximum allowable sequence number.
/// ///
/// This is provided for consistency with Rust 1.41.1, newer code should use [`Sequence::MAX`]. /// This is provided for consistency with Rust 1.41.1, newer code should use [`Sequence::MAX`].
#[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
pub const fn max_value() -> Self { Self::MAX } pub const fn max_value() -> Self { Self::MAX }
/// Returns `true` if the sequence number enables absolute lock-time ([`Transaction::lock_time`]). /// Returns `true` if the sequence number enables absolute lock-time ([`Transaction::lock_time`]).

View File

@ -26,10 +26,10 @@ impl Weight {
/// Minimum possible value (0 wu). /// Minimum possible value (0 wu).
/// ///
/// Equivalent to [`ZERO`](Self::ZERO), may better express intent in some contexts. /// Equivalent to [`ZERO`](Self::ZERO), may better express intent in some contexts.
pub const MIN: Weight = Weight(u64::min_value()); pub const MIN: Weight = Weight(u64::MIN);
/// Maximum possible value. /// Maximum possible value.
pub const MAX: Weight = Weight(u64::max_value()); pub const MAX: Weight = Weight(u64::MAX);
/// The maximum allowed weight for a block, see BIP 141 (network rule). /// The maximum allowed weight for a block, see BIP 141 (network rule).
pub const MAX_BLOCK: Weight = Weight(4_000_000); pub const MAX_BLOCK: Weight = Weight(4_000_000);
@ -124,7 +124,7 @@ mod tests {
#[test] #[test]
#[should_panic] #[should_panic]
fn kilo_weight_constructor_panic_test() { fn kilo_weight_constructor_panic_test() {
Weight::from_kwu(u64::max_value()).expect("expected weight unit"); Weight::from_kwu(u64::MAX).expect("expected weight unit");
} }
#[test] #[test]
@ -132,7 +132,7 @@ mod tests {
let vb = Weight::from_vb(1).expect("expected weight unit"); let vb = Weight::from_vb(1).expect("expected weight unit");
assert_eq!(Weight(4), vb); assert_eq!(Weight(4), vb);
let vb = Weight::from_vb(u64::max_value()); let vb = Weight::from_vb(u64::MAX);
assert_eq!(None, vb); assert_eq!(None, vb);
} }
@ -144,7 +144,7 @@ mod tests {
#[test] #[test]
#[should_panic] #[should_panic]
fn from_vb_unchecked_panic_test() { Weight::from_vb_unchecked(u64::max_value()); } fn from_vb_unchecked_panic_test() { Weight::from_vb_unchecked(u64::MAX); }
#[test] #[test]
fn from_witness_data_size_test() { fn from_witness_data_size_test() {

View File

@ -82,12 +82,12 @@ impl Decodable for Witness {
let required_len = cursor let required_len = cursor
.checked_add(element_size) .checked_add(element_size)
.ok_or(self::Error::OversizedVectorAllocation { .ok_or(self::Error::OversizedVectorAllocation {
requested: usize::max_value(), requested: usize::MAX,
max: MAX_VEC_SIZE, max: MAX_VEC_SIZE,
})? })?
.checked_add(element_size_varint_len) .checked_add(element_size_varint_len)
.ok_or(self::Error::OversizedVectorAllocation { .ok_or(self::Error::OversizedVectorAllocation {
requested: usize::max_value(), requested: usize::MAX,
max: MAX_VEC_SIZE, max: MAX_VEC_SIZE,
})?; })?;

View File

@ -895,7 +895,7 @@ mod tests {
test_varint_len(VarInt(0x10000), 5); test_varint_len(VarInt(0x10000), 5);
test_varint_len(VarInt(0xFFFFFFFF), 5); test_varint_len(VarInt(0xFFFFFFFF), 5);
test_varint_len(VarInt(0xFFFFFFFF + 1), 9); test_varint_len(VarInt(0xFFFFFFFF + 1), 9);
test_varint_len(VarInt(u64::max_value()), 9); test_varint_len(VarInt(u64::MAX), 9);
} }
fn test_varint_len(varint: VarInt, expected: usize) { fn test_varint_len(varint: VarInt, expected: usize) {

View File

@ -133,6 +133,7 @@ impl Target {
/// The maximum possible target (see [`Target::MAX`]). /// The maximum possible target (see [`Target::MAX`]).
/// ///
/// This is provided for consistency with Rust 1.41.1, newer code should use [`Target::MAX`]. /// This is provided for consistency with Rust 1.41.1, newer code should use [`Target::MAX`].
#[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
pub const fn max_value() -> Self { Target::MAX } pub const fn max_value() -> Self { Target::MAX }
/// Computes the [`Target`] value from a compact representation. /// Computes the [`Target`] value from a compact representation.
@ -363,7 +364,7 @@ impl U256 {
fn is_one(&self) -> bool { self.0 == 0 && self.1 == 1 } fn is_one(&self) -> bool { self.0 == 0 && self.1 == 1 }
#[cfg_attr(all(test, mutate), mutate)] #[cfg_attr(all(test, mutate), mutate)]
fn is_max(&self) -> bool { self.0 == u128::max_value() && self.1 == u128::max_value() } fn is_max(&self) -> bool { self.0 == u128::MAX && self.1 == u128::MAX }
/// Returns the low 32 bits. /// Returns the low 32 bits.
fn low_u32(&self) -> u32 { self.low_u128() as u32 } fn low_u32(&self) -> u32 { self.low_u128() as u32 }
@ -377,8 +378,8 @@ impl U256 {
/// Returns `self` as a `u128` saturating to `u128::MAX` if `self` is too big. /// Returns `self` as a `u128` saturating to `u128::MAX` if `self` is too big.
// Matagen gives false positive because >= and > both return u128::MAX // Matagen gives false positive because >= and > both return u128::MAX
fn saturating_to_u128(&self) -> u128 { fn saturating_to_u128(&self) -> u128 {
if *self > U256::from(u128::max_value()) { if *self > U256::from(u128::MAX) {
u128::max_value() u128::MAX
} else { } else {
self.low_u128() self.low_u128()
} }
@ -937,7 +938,7 @@ mod tests {
assert_eq!(U256::from(60000_u64).bits(), 16); assert_eq!(U256::from(60000_u64).bits(), 16);
assert_eq!(U256::from(70000_u64).bits(), 17); assert_eq!(U256::from(70000_u64).bits(), 17);
let u = U256::from(u128::max_value()) << 1; let u = U256::from(u128::MAX) << 1;
assert_eq!(u.bits(), 129); assert_eq!(u.bits(), 129);
// Try to read the following lines out loud quickly // Try to read the following lines out loud quickly
@ -1009,7 +1010,7 @@ mod tests {
fn u256_display() { fn u256_display() {
assert_eq!(format!("{}", U256::from(100_u32)), "100",); assert_eq!(format!("{}", U256::from(100_u32)), "100",);
assert_eq!(format!("{}", U256::ZERO), "0",); assert_eq!(format!("{}", U256::ZERO), "0",);
assert_eq!(format!("{}", U256::from(u64::max_value())), format!("{}", u64::max_value()),); assert_eq!(format!("{}", U256::from(u64::MAX)), format!("{}", u64::MAX),);
assert_eq!( assert_eq!(
format!("{}", U256::MAX), format!("{}", U256::MAX),
"115792089237316195423570985008687907853269984665640564039457584007913129639935", "115792089237316195423570985008687907853269984665640564039457584007913129639935",
@ -1324,7 +1325,7 @@ mod tests {
#[test] #[test]
fn u256_addition() { fn u256_addition() {
let x = U256::from(u128::max_value()); let x = U256::from(u128::MAX);
let (add, overflow) = x.overflowing_add(U256::ONE); let (add, overflow) = x.overflowing_add(U256::ONE);
assert!(!overflow); assert!(!overflow);
assert_eq!(add, U256(1, 0)); assert_eq!(add, U256(1, 0));
@ -1342,7 +1343,7 @@ mod tests {
let x = U256(1, 0); let x = U256(1, 0);
let (sub, overflow) = x.overflowing_sub(U256::ONE); let (sub, overflow) = x.overflowing_sub(U256::ONE);
assert!(!overflow); assert!(!overflow);
assert_eq!(sub, U256::from(u128::max_value())); assert_eq!(sub, U256::from(u128::MAX));
} }
#[test] #[test]
@ -1475,7 +1476,7 @@ mod tests {
#[test] #[test]
fn u256_is_max_correct_negative() { fn u256_is_max_correct_negative() {
let tc = vec![U256::ZERO, U256::ONE, U256::from(u128::max_value())]; let tc = vec![U256::ZERO, U256::ONE, U256::from(u128::MAX)];
for t in tc { for t in tc {
assert!(!t.is_max()) assert!(!t.is_max())
} }
@ -1485,7 +1486,7 @@ mod tests {
fn u256_is_max_correct_positive() { fn u256_is_max_correct_positive() {
assert!(U256::MAX.is_max()); assert!(U256::MAX.is_max());
let u = u128::max_value(); let u = u128::MAX;
assert!(((U256::from(u) << 128) + U256::from(u)).is_max()); assert!(((U256::from(u) << 128) + U256::from(u)).is_max());
} }

View File

@ -1769,8 +1769,8 @@ mod tests {
e => panic!("unexpected error: {:?}", e), e => panic!("unexpected error: {:?}", e),
} }
// overflow // overflow
t.unsigned_tx.output[0].value = u64::max_value(); t.unsigned_tx.output[0].value = u64::MAX;
t.unsigned_tx.output[1].value = u64::max_value(); t.unsigned_tx.output[1].value = u64::MAX;
match t.fee().unwrap_err() { match t.fee().unwrap_err() {
Error::FeeOverflow => {} Error::FeeOverflow => {}
e => panic!("unexpected error: {:?}", e), e => panic!("unexpected error: {:?}", e),

View File

@ -220,7 +220,7 @@ macro_rules! fmt_hex_exact {
($formatter:expr, $len:expr, $bytes:expr, $case:expr) => {{ ($formatter:expr, $len:expr, $bytes:expr, $case:expr) => {{
// statically check $len // statically check $len
#[allow(deprecated)] #[allow(deprecated)]
const _: () = [()][($len > usize::max_value() / 2) as usize]; const _: () = [()][($len > usize::MAX / 2) as usize];
assert_eq!($bytes.len(), $len); assert_eq!($bytes.len(), $len);
let mut buf = [0u8; $len * 2]; let mut buf = [0u8; $len * 2];
let buf = $crate::hex::buf_encoder::AsOutBytes::as_mut_out_bytes(&mut buf); let buf = $crate::hex::buf_encoder::AsOutBytes::as_mut_out_bytes(&mut buf);