From 894f82e7cc9eb459a297d43e82734621e0824610 Mon Sep 17 00:00:00 2001 From: yancy Date: Tue, 10 Sep 2024 13:58:57 -0500 Subject: [PATCH] Add a condition for parsing zero from string when not denominated. --- units/src/amount.rs | 53 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/units/src/amount.rs b/units/src/amount.rs index c4195a3ec2..064f8ddfaa 100644 --- a/units/src/amount.rs +++ b/units/src/amount.rs @@ -1158,7 +1158,22 @@ impl ops::DivAssign for Amount { impl FromStr for Amount { type Err = ParseError; - fn from_str(s: &str) -> Result { Amount::from_str_with_denomination(s) } + fn from_str(s: &str) -> Result { + 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 for Amount { @@ -1577,7 +1592,22 @@ impl ops::Neg for SignedAmount { impl FromStr for SignedAmount { type Err = ParseError; - fn from_str(s: &str) -> Result { SignedAmount::from_str_with_denomination(s) } + fn from_str(s: &str) -> Result { + 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 for SignedAmount { @@ -2075,6 +2105,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);