Skip to content

Commit

Permalink
Make AtomicPosition::allow() logic more robust
Browse files Browse the repository at this point in the history
  • Loading branch information
djc committed Mar 17, 2022
1 parent f941a79 commit c088e9a
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/state.rs
Expand Up @@ -395,13 +395,17 @@ pub(crate) struct AtomicPosition {

impl AtomicPosition {
pub(crate) fn allow(&self, now: Instant) -> bool {
if now < self.start {
return false;
}

let mut capacity = self.capacity.load(Ordering::Acquire);
// `prev` is the number of ms after `self.started` we last returned `true`, in ns
let prev = self.prev.load(Ordering::Acquire);
// `elapsed` is the number of ns since `self.started`
let elapsed = (now - self.start).as_nanos() as u64;
// `diff` is the number of ns since we last returned `true`
let diff = elapsed - prev;
let diff = elapsed.saturating_sub(prev);

// If `capacity` is 0 and not enough time (1ms) has passed since `prev`
// to add new capacity, return `false`. The goal of this method is to
Expand All @@ -427,7 +431,7 @@ impl AtomicPosition {

fn reset(&self, now: Instant) {
self.set(0);
let elapsed = (now - self.start).as_millis() as u64;
let elapsed = (now.saturating_duration_since(self.start)).as_millis() as u64;
self.prev.store(elapsed, Ordering::Release);
}

Expand Down

0 comments on commit c088e9a

Please sign in to comment.