Skip to content

Commit

Permalink
AtomicPosition: fix overflowing addition
Browse files Browse the repository at this point in the history
  • Loading branch information
arxanas authored and djc committed Mar 24, 2022
1 parent bce8da6 commit 647a1f8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/draw_target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ impl RateLimiter {

// We add `new` to `capacity`, subtract one for returning `true` from here,
// then make sure it does not exceed a maximum of `MAX_BURST`, then store it.
self.capacity = Ord::min(MAX_BURST, self.capacity + new as u8 - 1);
self.capacity = Ord::min(MAX_BURST as u128, (self.capacity as u128) + new - 1) as u8;
// Store `prev` for the next iteration after subtracting the `remainder`.
self.prev = now - Duration::from_nanos(remainder as u64);
true
Expand Down
10 changes: 9 additions & 1 deletion src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ impl AtomicPosition {
let (new, remainder) = ((diff / INTERVAL), (diff % INTERVAL));
// We add `new` to `capacity`, subtract one for returning `true` from here,
// then make sure it does not exceed a maximum of `MAX_BURST`.
capacity = Ord::min(MAX_BURST, capacity + new as u8 - 1);
capacity = Ord::min(MAX_BURST as u128, (capacity as u128) + (new as u128) - 1) as u8;

// Then, we just store `capacity` and `prev` atomically for the next iteration
self.capacity.store(capacity, Ordering::Release);
Expand Down Expand Up @@ -603,4 +603,12 @@ mod tests {
// Should not panic.
pb.set_position(0);
}

#[test]
fn test_atomic_position_large_time_difference() {
let atomic_position = AtomicPosition::new();
let later = atomic_position.start + Duration::from_nanos(INTERVAL * u64::from(u8::MAX));
// Should not panic.
atomic_position.allow(later);
}
}

0 comments on commit 647a1f8

Please sign in to comment.