Merge rust-bitcoin/rust-bitcoin#4484: Introduce `map` function for `NumOpResult`

a66ff8f8b1 Introduce `map` function for `NumOpResult` (Shing Him Ng)

Pull request description:

  Closes #4476

ACKs for top commit:
  Kixunil:
    ACK a66ff8f8b1
  apoelstra:
    ACK a66ff8f8b143ebebb80ddc6b052cbc55e8dbb070; successfully ran local tests

Tree-SHA512: 63c79666685895033b9df0c46004fa4b042d038cc61e5ef443f56690be268ac6dd1ba461ab4f7d97c684e68623dfa53cdd37091f40ff7e6a5d3e53920c3fd40c
This commit is contained in:
merge-script 2025-05-13 16:00:55 +00:00
commit c5d8803148
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 30 additions and 0 deletions

View File

@ -87,6 +87,36 @@ pub enum NumOpResult<T> {
Error(NumOpError),
}
impl<T> NumOpResult<T> {
/// Maps a `NumOpResult<T>` to `NumOpResult<U>` by applying a function to a
/// contained [`NumOpResult::Valid`] value, leaving a [`NumOpResult::Error`] value untouched.
///
/// # Examples
///
/// ```
/// use bitcoin_units::{FeeRate, Amount, Weight, SignedAmount};
///
/// let fee_rate = FeeRate::from_sat_per_vb(1).unwrap();
/// let weight = Weight::from_wu(1000);
/// let amount = Amount::from_sat_u32(1_000_000);
///
/// let amount_after_fee = fee_rate
/// .to_fee(weight) // (1 sat/ 4 wu) * (1000 wu) = 250 sat fee
/// .map(|fee| fee.to_signed())
/// .and_then(|fee| amount.to_signed() - fee);
///
/// assert_eq!(amount_after_fee.unwrap(), SignedAmount::from_sat_i32(999_750))
/// ```
#[inline]
pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> NumOpResult<U> {
match self {
NumOpResult::Valid(t) => NumOpResult::Valid(op(t)),
NumOpResult::Error(e) => NumOpResult::Error(e),
}
}
}
impl<T: fmt::Debug> NumOpResult<T> {
/// Returns the contained valid numeric type, consuming `self`.
///