From 5fbbd483ea419c8705e5a2973aeeffab67e5cf89 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Wed, 3 May 2023 08:16:20 +1000 Subject: [PATCH] Use MIN/MAX consts instead of min/max_value We currently use the functions `min_value` and `max_value` because the consts were not available in Rust 1.41.1, however we recently bumped the MSRV so we can use the consts now. --- bitcoin/src/amount.rs | 61 ++++++++++----------- bitcoin/src/blockdata/fee_rate.rs | 8 +-- bitcoin/src/blockdata/script/instruction.rs | 2 +- bitcoin/src/blockdata/script/mod.rs | 8 +-- bitcoin/src/blockdata/transaction.rs | 2 +- bitcoin/src/blockdata/weight.rs | 10 ++-- bitcoin/src/blockdata/witness.rs | 4 +- bitcoin/src/consensus/encode.rs | 2 +- bitcoin/src/pow.rs | 18 +++--- bitcoin/src/psbt/mod.rs | 4 +- internals/src/hex/display.rs | 2 +- 11 files changed, 59 insertions(+), 62 deletions(-) diff --git a/bitcoin/src/amount.rs b/bitcoin/src/amount.rs index 0ff131a6..054a5c0d 100644 --- a/bitcoin/src/amount.rs +++ b/bitcoin/src/amount.rs @@ -525,7 +525,7 @@ impl Amount { if negative { return Err(ParseAmountError::Negative); } - if satoshi > i64::max_value() as u64 { + if satoshi > i64::MAX as u64 { return Err(ParseAmountError::TooBig); } Ok(Amount::from_sat(satoshi)) @@ -650,7 +650,7 @@ impl Amount { /// Convert to a signed amount. pub fn to_signed(self) -> Result { - if self.to_sat() > SignedAmount::max_value().to_sat() as u64 { + if self.to_sat() > SignedAmount::MAX.to_sat() as u64 { Err(ParseAmountError::TooBig) } else { Ok(SignedAmount::from_sat(self.to_sat() as i64)) @@ -861,7 +861,7 @@ impl SignedAmount { /// with denomination, use [FromStr]. pub fn from_str_in(s: &str, denom: Denomination) -> Result { 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); } Ok(match negative { @@ -980,7 +980,7 @@ impl SignedAmount { pub fn is_negative(self) -> bool { self.0.is_negative() } /// 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 { self.0.checked_abs().map(SignedAmount) } /// Checked addition. @@ -1583,7 +1583,7 @@ mod tests { #[test] fn test_overflows() { // 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()); let result = panic::catch_unwind(|| Amount::from_sat(8446744073709551615) * 3); assert!(result.is_err()); @@ -1594,10 +1594,10 @@ mod tests { let sat = Amount::from_sat; let ssat = SignedAmount::from_sat; - assert_eq!(SignedAmount::max_value().checked_add(ssat(1)), None); - assert_eq!(SignedAmount::min_value().checked_sub(ssat(1)), None); - assert_eq!(Amount::max_value().checked_add(sat(1)), None); - assert_eq!(Amount::min_value().checked_sub(sat(1)), None); + assert_eq!(SignedAmount::MAX.checked_add(ssat(1)), None); + assert_eq!(SignedAmount::MIN.checked_sub(ssat(1)), None); + assert_eq!(Amount::MAX.checked_add(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!(ssat(-6).checked_div(2), Some(ssat(-3))); @@ -1626,11 +1626,11 @@ mod tests { assert_eq!(sf(-184467440738.0, D::Bitcoin), Err(ParseAmountError::TooBig)); assert_eq!(f(18446744073709551617.0, D::Satoshi), Err(ParseAmountError::TooBig)); 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) ); 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) ); @@ -1659,7 +1659,7 @@ mod tests { assert_eq!(p("-1.0x", btc), Err(E::InvalidCharacter('x'))); assert_eq!(p("0.0 ", btc), Err(ParseAmountError::InvalidCharacter(' '))); 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("0.000000042", btc), Err(E::TooPrecise)); @@ -1676,8 +1676,8 @@ mod tests { Ok(Amount::from_sat(12_345_678_901__123_456_78)) ); - // make sure satoshi > i64::max_value() is checked. - let amount = Amount::from_sat(i64::max_value() as u64); + // make sure satoshi > i64::MAX is checked. + 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 + Amount(1)).to_string_in(sat), sat), @@ -1908,16 +1908,13 @@ mod tests { let sa = SignedAmount::from_sat; let ua = Amount::from_sat; - assert_eq!(Amount::max_value().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_value() as u64 + 1).to_signed(), Err(E::TooBig)); + assert_eq!(Amount::MAX.to_signed(), Err(E::TooBig)); + assert_eq!(ua(i64::MAX as u64).to_signed(), Ok(sa(i64::MAX))); + 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!( - sa(i64::max_value()).to_unsigned().unwrap().to_signed(), - Ok(sa(i64::max_value())) - ); + assert_eq!(sa(i64::MAX).to_unsigned().unwrap().to_signed(), Ok(sa(i64::MAX))); } #[test] @@ -2005,7 +2002,7 @@ mod tests { Ok(ua_sat(1_000_000_000_000)) ); 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) ); @@ -2015,12 +2012,12 @@ mod tests { ); 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) ); // Test an overflow bug in `abs()` 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) ); @@ -2029,11 +2026,11 @@ mod tests { Ok(sa_sat(-1)) ); 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) ); 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) ); @@ -2042,11 +2039,11 @@ mod tests { Ok(sa_sat(-1)) ); 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) ); 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) ); } @@ -2248,12 +2245,12 @@ mod tests { assert_eq!(Some(Amount::from_sat(1400)), sum); 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(); assert_eq!(None, sum); let amounts = vec![ - SignedAmount::from_sat(i64::min_value()), + SignedAmount::from_sat(i64::MIN), SignedAmount::from_sat(-1), SignedAmount::from_sat(21), ]; @@ -2261,7 +2258,7 @@ mod tests { assert_eq!(None, sum); let amounts = vec![ - SignedAmount::from_sat(i64::max_value()), + SignedAmount::from_sat(i64::MAX), SignedAmount::from_sat(1), SignedAmount::from_sat(21), ]; diff --git a/bitcoin/src/blockdata/fee_rate.rs b/bitcoin/src/blockdata/fee_rate.rs index 45f83322..100ab9e4 100644 --- a/bitcoin/src/blockdata/fee_rate.rs +++ b/bitcoin/src/blockdata/fee_rate.rs @@ -28,10 +28,10 @@ impl FeeRate { /// Minimum possible value (0 sat/kwu). /// /// 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. - pub const MAX: FeeRate = FeeRate(u64::max_value()); + pub const MAX: FeeRate = FeeRate(u64::MAX); /// Minimum fee rate required to broadcast a transaction. /// @@ -128,8 +128,8 @@ mod tests { #[test] fn fee_rate_const_test() { assert_eq!(0, FeeRate::ZERO.to_sat_per_kwu()); - assert_eq!(u64::min_value(), FeeRate::MIN.to_sat_per_kwu()); - assert_eq!(u64::max_value(), FeeRate::MAX.to_sat_per_kwu()); + assert_eq!(u64::MIN, FeeRate::MIN.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!(750, FeeRate::DUST.to_sat_per_kwu()); } diff --git a/bitcoin/src/blockdata/script/instruction.rs b/bitcoin/src/blockdata/script/instruction.rs index 8d824807..70ef3594 100644 --- a/bitcoin/src/blockdata/script/instruction.rs +++ b/bitcoin/src/blockdata/script/instruction.rs @@ -88,7 +88,7 @@ impl<'a> Instructions<'a> { // We do exhaustive matching to not forget to handle new variants if we extend // `UintError` type. // Overflow actually means early end of script (script is definitely shorter - // than `usize::max_value()`) + // than `usize::MAX`) Err(UintError::EarlyEndOfScript) | Err(UintError::NumericOverflow) => { self.kill(); return Some(Err(Error::EarlyEndOfScript)); diff --git a/bitcoin/src/blockdata/script/mod.rs b/bitcoin/src/blockdata/script/mod.rs index c3cab10f..b688ff13 100644 --- a/bitcoin/src/blockdata/script/mod.rs +++ b/bitcoin/src/blockdata/script/mod.rs @@ -187,11 +187,11 @@ pub fn read_scriptbool(v: &[u8]) -> bool { /// This function returns an error in these cases: /// /// * `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` /// /// Note that this does **not** return an error for `size` between `core::size_of::()` -/// and `u16::max_value / 8` if there's no overflow. +/// and `u16::MAX / 8` if there's no overflow. #[inline] #[deprecated(since = "0.30.0", note = "bitcoin integers are signed 32 bits, use read_scriptint")] pub fn read_uint(data: &[u8], size: usize) -> Result { @@ -203,7 +203,7 @@ pub fn read_uint(data: &[u8], size: usize) -> Result { fn read_uint_iter(data: &mut core::slice::Iter<'_, u8>, size: usize) -> Result { if data.len() < size { 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 Err(UintError::NumericOverflow) } else { @@ -596,7 +596,7 @@ pub(super) fn bytes_to_asm_fmt(script: &[u8], f: &mut dyn fmt::Write) -> fmt::Re $formatter.write_str("")?; 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 // the slice even though we don't know the exact number. This implies attempt to push // past end. diff --git a/bitcoin/src/blockdata/transaction.rs b/bitcoin/src/blockdata/transaction.rs index 62b28f61..d3da2552 100644 --- a/bitcoin/src/blockdata/transaction.rs +++ b/bitcoin/src/blockdata/transaction.rs @@ -61,7 +61,7 @@ impl OutPoint { /// /// This value is used for coinbase transactions because they don't have any previous outputs. #[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". /// diff --git a/bitcoin/src/blockdata/weight.rs b/bitcoin/src/blockdata/weight.rs index f2a296e0..0185e983 100644 --- a/bitcoin/src/blockdata/weight.rs +++ b/bitcoin/src/blockdata/weight.rs @@ -26,10 +26,10 @@ impl Weight { /// Minimum possible value (0 wu). /// /// 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. - 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). pub const MAX_BLOCK: Weight = Weight(4_000_000); @@ -124,7 +124,7 @@ mod tests { #[test] #[should_panic] 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] @@ -132,7 +132,7 @@ mod tests { let vb = Weight::from_vb(1).expect("expected weight unit"); assert_eq!(Weight(4), vb); - let vb = Weight::from_vb(u64::max_value()); + let vb = Weight::from_vb(u64::MAX); assert_eq!(None, vb); } @@ -144,7 +144,7 @@ mod tests { #[test] #[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] fn from_witness_data_size_test() { diff --git a/bitcoin/src/blockdata/witness.rs b/bitcoin/src/blockdata/witness.rs index 21ec99d6..dbaf2bc7 100644 --- a/bitcoin/src/blockdata/witness.rs +++ b/bitcoin/src/blockdata/witness.rs @@ -82,12 +82,12 @@ impl Decodable for Witness { let required_len = cursor .checked_add(element_size) .ok_or(self::Error::OversizedVectorAllocation { - requested: usize::max_value(), + requested: usize::MAX, max: MAX_VEC_SIZE, })? .checked_add(element_size_varint_len) .ok_or(self::Error::OversizedVectorAllocation { - requested: usize::max_value(), + requested: usize::MAX, max: MAX_VEC_SIZE, })?; diff --git a/bitcoin/src/consensus/encode.rs b/bitcoin/src/consensus/encode.rs index 6fc6a588..7f6e2f0e 100644 --- a/bitcoin/src/consensus/encode.rs +++ b/bitcoin/src/consensus/encode.rs @@ -895,7 +895,7 @@ mod tests { test_varint_len(VarInt(0x10000), 5); test_varint_len(VarInt(0xFFFFFFFF), 5); 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) { diff --git a/bitcoin/src/pow.rs b/bitcoin/src/pow.rs index 9630ed50..82d21718 100644 --- a/bitcoin/src/pow.rs +++ b/bitcoin/src/pow.rs @@ -363,7 +363,7 @@ impl U256 { fn is_one(&self) -> bool { self.0 == 0 && self.1 == 1 } #[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. fn low_u32(&self) -> u32 { self.low_u128() as u32 } @@ -377,8 +377,8 @@ impl U256 { /// Returns `self` as a `u128` saturating to `u128::MAX` if `self` is too big. // Matagen gives false positive because >= and > both return u128::MAX fn saturating_to_u128(&self) -> u128 { - if *self > U256::from(u128::max_value()) { - u128::max_value() + if *self > U256::from(u128::MAX) { + u128::MAX } else { self.low_u128() } @@ -937,7 +937,7 @@ mod tests { assert_eq!(U256::from(60000_u64).bits(), 16); 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); // Try to read the following lines out loud quickly @@ -1009,7 +1009,7 @@ mod tests { fn u256_display() { assert_eq!(format!("{}", U256::from(100_u32)), "100",); 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!( format!("{}", U256::MAX), "115792089237316195423570985008687907853269984665640564039457584007913129639935", @@ -1324,7 +1324,7 @@ mod tests { #[test] fn u256_addition() { - let x = U256::from(u128::max_value()); + let x = U256::from(u128::MAX); let (add, overflow) = x.overflowing_add(U256::ONE); assert!(!overflow); assert_eq!(add, U256(1, 0)); @@ -1342,7 +1342,7 @@ mod tests { let x = U256(1, 0); let (sub, overflow) = x.overflowing_sub(U256::ONE); assert!(!overflow); - assert_eq!(sub, U256::from(u128::max_value())); + assert_eq!(sub, U256::from(u128::MAX)); } #[test] @@ -1475,7 +1475,7 @@ mod tests { #[test] 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 { assert!(!t.is_max()) } @@ -1485,7 +1485,7 @@ mod tests { fn u256_is_max_correct_positive() { assert!(U256::MAX.is_max()); - let u = u128::max_value(); + let u = u128::MAX; assert!(((U256::from(u) << 128) + U256::from(u)).is_max()); } diff --git a/bitcoin/src/psbt/mod.rs b/bitcoin/src/psbt/mod.rs index 5af2317c..7aeeabcb 100644 --- a/bitcoin/src/psbt/mod.rs +++ b/bitcoin/src/psbt/mod.rs @@ -1769,8 +1769,8 @@ mod tests { e => panic!("unexpected error: {:?}", e), } // overflow - t.unsigned_tx.output[0].value = u64::max_value(); - t.unsigned_tx.output[1].value = u64::max_value(); + t.unsigned_tx.output[0].value = u64::MAX; + t.unsigned_tx.output[1].value = u64::MAX; match t.fee().unwrap_err() { Error::FeeOverflow => {} e => panic!("unexpected error: {:?}", e), diff --git a/internals/src/hex/display.rs b/internals/src/hex/display.rs index 6a75864a..85da1684 100644 --- a/internals/src/hex/display.rs +++ b/internals/src/hex/display.rs @@ -220,7 +220,7 @@ macro_rules! fmt_hex_exact { ($formatter:expr, $len:expr, $bytes:expr, $case:expr) => {{ // statically check $len #[allow(deprecated)] - const _: () = [()][($len > usize::max_value() / 2) as usize]; + const _: () = [()][($len > usize::MAX / 2) as usize]; assert_eq!($bytes.len(), $len); let mut buf = [0u8; $len * 2]; let buf = $crate::hex::buf_encoder::AsOutBytes::as_mut_out_bytes(&mut buf);