Skip to content

Commit

Permalink
Add the FromStr
Browse files Browse the repository at this point in the history
  • Loading branch information
zbraniecki committed Dec 18, 2020
1 parent 3fe3bad commit 1038f66
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
19 changes: 16 additions & 3 deletions components/plurals/src/operands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ pub struct PluralOperands {
pub f: u64,
/// Visible fraction digits without trailing zeros
pub t: u64,
/// Exponent
pub e: usize,
}

Expand Down Expand Up @@ -103,6 +104,15 @@ impl From<IOError> for OperandsError {
}
}

fn get_exponent(input: &str) -> Result<(&str, usize), OperandsError> {
if let Some(e_idx) = input.find('e') {
let e = usize::from_str(&input[e_idx + 1..])?;
Ok((&input[..e_idx], e))
} else {
Ok((input, 0))
}
}

impl FromStr for PluralOperands {
type Err = OperandsError;

Expand All @@ -119,9 +129,10 @@ impl FromStr for PluralOperands {
num_fraction_digits,
fraction_digits0,
fraction_digits,
exponent,
) = if let Some(sep_idx) = abs_str.find('.') {
let int_str = &abs_str[..sep_idx];
let dec_str = &abs_str[(sep_idx + 1)..];
let (dec_str, exponent) = get_exponent(&abs_str[(sep_idx + 1)..])?;

let integer_digits = u64::from_str(int_str)?;

Expand All @@ -144,10 +155,12 @@ impl FromStr for PluralOperands {
num_fraction_digits,
fraction_digits0,
fraction_digits,
exponent,
)
} else {
let (abs_str, exponent) = get_exponent(abs_str)?;
let integer_digits = u64::from_str(abs_str)?;
(integer_digits, 0, 0, 0, 0)
(integer_digits, 0, 0, 0, 0, exponent)
};

Ok(Self {
Expand All @@ -156,7 +169,7 @@ impl FromStr for PluralOperands {
w: num_fraction_digits,
f: fraction_digits0,
t: fraction_digits,
e: 0,
e: exponent,
})
}
}
Expand Down
8 changes: 8 additions & 0 deletions components/plurals/tests/fixtures/operands.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@
{
"input": "2.0",
"output": [2, 2, 1, 0, 0, 0, 0]
},
{
"input": "2e3",
"output": [2, 2, 0, 0, 0, 0, 3]
},
{
"input": "2.0e12",
"output": [2, 2, 1, 0, 0, 0, 12]
}
],
"int": [
Expand Down

0 comments on commit 1038f66

Please sign in to comment.