Skip to content

Commit 5295317

Browse files
authored
Fix AtomicPosition::reset storing wrong value (#650)
The code actually expects this value to be in ns. I reckon the bug got introduced because the comments are worded a bit ambiguously, so I also cleared those up.
1 parent 022fda7 commit 5295317

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

src/state.rs

+15-4
Original file line numberDiff line numberDiff line change
@@ -537,7 +537,7 @@ impl AtomicPosition {
537537
}
538538

539539
let mut capacity = self.capacity.load(Ordering::Acquire);
540-
// `prev` is the number of ms after `self.started` we last returned `true`, in ns
540+
// `prev` is the number of ns after `self.started` we last returned `true`
541541
let prev = self.prev.load(Ordering::Acquire);
542542
// `elapsed` is the number of ns since `self.started`
543543
let elapsed = (now - self.start).as_nanos() as u64;
@@ -551,8 +551,8 @@ impl AtomicPosition {
551551
return false;
552552
}
553553

554-
// We now calculate `new`, the number of ms, in ns, since we last returned `true`,
555-
// and `remainder`, which represents a number of ns less than 1ms which we cannot
554+
// We now calculate `new`, the number of INTERVALs since we last returned `true`,
555+
// and `remainder`, which represents a number of ns less than INTERVAL which we cannot
556556
// convert into capacity now, so we're saving it for later. We do this by
557557
// subtracting this from `elapsed` before storing it into `self.prev`.
558558
let (new, remainder) = ((diff / INTERVAL), (diff % INTERVAL));
@@ -568,7 +568,7 @@ impl AtomicPosition {
568568

569569
fn reset(&self, now: Instant) {
570570
self.set(0);
571-
let elapsed = (now.saturating_duration_since(self.start)).as_millis() as u64;
571+
let elapsed = (now.saturating_duration_since(self.start)).as_nanos() as u64;
572572
self.prev.store(elapsed, Ordering::Release);
573573
}
574574

@@ -799,4 +799,15 @@ mod tests {
799799
// Should not panic.
800800
atomic_position.allow(later);
801801
}
802+
803+
#[test]
804+
fn test_atomic_position_reset() {
805+
const ELAPSE_TIME: Duration = Duration::from_millis(20);
806+
let mut pos = AtomicPosition::new();
807+
pos.reset(pos.start + ELAPSE_TIME);
808+
809+
// prev should be exactly ELAPSE_TIME after reset
810+
assert_eq!(*pos.pos.get_mut(), 0);
811+
assert_eq!(*pos.prev.get_mut(), ELAPSE_TIME.as_nanos() as u64);
812+
}
802813
}

0 commit comments

Comments
 (0)