Skip to content

Commit

Permalink
Guard against invalid percentiles (#380)
Browse files Browse the repository at this point in the history
  • Loading branch information
casey authored and terror committed Aug 30, 2022
1 parent 344031c commit 29a08d4
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/ordinal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,19 @@ impl Ordinal {

let percentile = percentile[..percentile.len() - 1].parse::<f64>()?;

let position = percentile / 100.0;
if percentile < 0.0 {
bail!("Invalid percentile: {}", percentile);
}

let last = Ordinal::LAST.n() as f64;

let n = position * Ordinal::LAST.n() as f64;
let n = (percentile / 100.0 * last).round() as u64;

Ok(Ordinal(n.round() as u64))
if n > Ordinal::LAST.n() {
bail!("Invalid percentile: {}", percentile);
}

Ok(Ordinal(n as u64))
}
}

Expand Down Expand Up @@ -520,6 +528,12 @@ mod tests {
assert_eq!(Ordinal::LAST.percentile(), "100%");
}

#[test]
fn from_percentile() {
"-1%".parse::<Ordinal>().unwrap_err();
"101%".parse::<Ordinal>().unwrap_err();
}

#[test]
fn percentile_round_trip() {
fn case(n: u64) {
Expand Down

0 comments on commit 29a08d4

Please sign in to comment.