Skip to content

Commit 15e4654

Browse files
authored
Merge pull request #39 from marshallpierce/median-equivalent-overflow
Simplify overflowing_add in median_equivalent
2 parents 5a51f46 + b23321a commit 15e4654

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

src/lib.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1252,11 +1252,9 @@ impl<T: Counter> Histogram<T> {
12521252
///
12531253
/// Note that the return value is capped at `u64::max_value()`.
12541254
pub fn median_equivalent(&self, value: u64) -> u64 {
1255-
// TODO isn't this just saturating?
1256-
match self.lowest_equivalent(value).overflowing_add(self.equivalent_range(value) >> 1) {
1257-
(_, of) if of => u64::max_value(),
1258-
(v, _) => v,
1259-
}
1255+
// adding half of the range to the bottom of the range shouldn't overflow
1256+
self.lowest_equivalent(value).checked_add(self.equivalent_range(value) >> 1)
1257+
.expect("median equivalent should not overflow")
12601258
}
12611259

12621260
/// Get the next value that is *not* equivalent to the given value within the histogram's

tests/histogram.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,15 @@ fn median_equivalent() {
300300
assert_eq!(h.median_equivalent(10007), 10004);
301301
}
302302

303+
#[test]
304+
fn median_equivalent_doesnt_panic_at_extremes() {
305+
let h = Histogram::<u64>::new_with_max(u64::max_value(), 3).unwrap();
306+
let _ = h.median_equivalent(u64::max_value());
307+
let _ = h.median_equivalent(u64::max_value() - 1);
308+
let _ = h.median_equivalent(0);
309+
let _ = h.median_equivalent(1);
310+
}
311+
303312
#[test]
304313
fn scaled_median_equivalent() {
305314
let h = Histogram::<u64>::new_with_bounds(1024, TRACKABLE_MAX, SIGFIG).unwrap();

0 commit comments

Comments
 (0)