Skip to content

Commit 7a3bf39

Browse files
committed
Return Result type instead of Option
Result allows for a more descriptive error messaging.
1 parent 232ae4b commit 7a3bf39

File tree

2 files changed

+16
-10
lines changed

2 files changed

+16
-10
lines changed

units/src/amount/tests.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -1466,8 +1466,8 @@ fn math_op_errors() {
14661466
fn to_effective_value() {
14671467
let amt = "1 cBTC".parse::<Amount>().unwrap();
14681468
let fee_rate = FeeRate::from_sat_per_kwu(10);
1469-
let effective_value =
1470-
amt.to_effective_value(fee_rate, Weight::from_wu(272)).unwrap();
1469+
let effective_value = amt.to_effective_value(
1470+
fee_rate, Weight::from_wu(272)).unwrap();
14711471

14721472
// 10 sat/kwu * 272 wu = 4 sats (rounding up)
14731473
let expected_fee = "3 sats".parse::<SignedAmount>().unwrap();
@@ -1476,7 +1476,7 @@ fn to_effective_value() {
14761476
}
14771477

14781478
#[test]
1479-
fn effective_value_fee_rate_does_not_overflow() {
1480-
let eff_value =Amount::ZERO.to_effective_value(FeeRate::MAX, Weight::from_wu(272));
1481-
assert!(eff_value.is_none());
1479+
fn to_effective_value_error() {
1480+
let eff_val = Amount::ZERO.to_effective_value(FeeRate::MAX, Weight::from_wu(272));
1481+
assert_eq!(eff_val, Err(OutOfRangeError::too_big(false).into()));
14821482
}

units/src/amount/unsigned.rs

+11-5
Original file line numberDiff line numberDiff line change
@@ -250,11 +250,17 @@ impl Amount {
250250
/// * `input_weight_prediction` - the predicted input weight.
251251
pub fn to_effective_value(
252252
&self,
253-
fee_rate: FeeRate,
254-
weight: Weight,
255-
) -> Option<SignedAmount> {
256-
let signed_input_fee = fee_rate.to_fee(weight)?.to_signed();
257-
self.to_signed().checked_sub(signed_input_fee)
253+
fee_rate: crate::FeeRate,
254+
weight: crate::Weight
255+
) -> Result<SignedAmount, OutOfRangeError> {
256+
let signed_input_fee = fee_rate.to_fee(weight).ok_or(
257+
OutOfRangeError { is_signed: false, is_greater_than_max: true }
258+
)?.to_signed();
259+
260+
// it's not possible to overflow when subtracted by the smallest given:
261+
// Amount::MIN - SignedAmount::MAX = SignedAmount::MIN
262+
let eff_val = (self.to_signed() - signed_input_fee).unwrap(); //unwrap ok
263+
Ok(eff_val)
258264
}
259265

260266
/// Converts this [`Amount`] in floating-point notation in the given [`Denomination`].

0 commit comments

Comments
 (0)