Skip to content

Commit

Permalink
Merge rust-bitcoin#3346: Add a condition for parsing zero from string…
Browse files Browse the repository at this point in the history
… when not denominated.

894f82e Add a condition for parsing zero from string when not denominated. (yancy)

Pull request description:

  closes rust-bitcoin#3307

ACKs for top commit:
  Kixunil:
    ACK 894f82e
  tcharding:
    ACK 894f82e
  apoelstra:
    ACK 894f82e; successfully ran local tests.

Tree-SHA512: 6d32847c74ccedc3355d615838e2dd1e08add29cc47ff69d9ef22683eda93049d41131dd0c992c8d7be3a018f5438856c415a3d2f3cb9de9c986534b268ee386
  • Loading branch information
apoelstra committed Sep 13, 2024
2 parents 60e15b8 + 894f82e commit 7360c3c
Showing 1 changed file with 51 additions and 2 deletions.
53 changes: 51 additions & 2 deletions units/src/amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1157,7 +1157,22 @@ impl ops::DivAssign<u64> for Amount {
impl FromStr for Amount {
type Err = ParseError;

fn from_str(s: &str) -> Result<Self, Self::Err> { Amount::from_str_with_denomination(s) }
fn from_str(s: &str) -> Result<Self, Self::Err> {
let result = Amount::from_str_with_denomination(s);

match result {
Err(ParseError::MissingDenomination(_)) => {
let d = Amount::from_str_in(s, Denomination::Satoshi);

if d == Ok(Amount::ZERO) {
Ok(Amount::ZERO)
} else {
result
}
},
_ => result
}
}
}

impl TryFrom<SignedAmount> for Amount {
Expand Down Expand Up @@ -1580,7 +1595,22 @@ impl ops::Neg for SignedAmount {
impl FromStr for SignedAmount {
type Err = ParseError;

fn from_str(s: &str) -> Result<Self, Self::Err> { SignedAmount::from_str_with_denomination(s) }
fn from_str(s: &str) -> Result<Self, Self::Err> {
let result = SignedAmount::from_str_with_denomination(s);

match result {
Err(ParseError::MissingDenomination(_)) => {
let d = SignedAmount::from_str_in(s, Denomination::Satoshi);

if d == Ok(SignedAmount::ZERO) {
Ok(SignedAmount::ZERO)
} else {
result
}
},
_ => result
}
}
}

impl TryFrom<Amount> for SignedAmount {
Expand Down Expand Up @@ -2079,6 +2109,25 @@ mod tests {
}
}

#[test]
fn from_str_zero_without_denomination() {
let _a = Amount::from_str("0").unwrap();
let _a = Amount::from_str("0.0").unwrap();
let _a = Amount::from_str("00.0").unwrap();

assert!(Amount::from_str("-0").is_err());
assert!(Amount::from_str("-0.0").is_err());
assert!(Amount::from_str("-00.0").is_err());

let _a = SignedAmount::from_str("-0").unwrap();
let _a = SignedAmount::from_str("-0.0").unwrap();
let _a = SignedAmount::from_str("-00.0").unwrap();

let _a = SignedAmount::from_str("0").unwrap();
let _a = SignedAmount::from_str("0.0").unwrap();
let _a = SignedAmount::from_str("00.0").unwrap();
}

#[test]
fn from_int_btc() {
let amt = Amount::from_int_btc(2);
Expand Down

0 comments on commit 7360c3c

Please sign in to comment.