Add a condition for parsing zero from string when not denominated.

This commit is contained in:
yancy 2024-09-10 13:58:57 -05:00
parent c2e3e86106
commit 894f82e7cc
1 changed files with 51 additions and 2 deletions

View File

@ -1158,7 +1158,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 {
@ -1577,7 +1592,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 {
@ -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);