Skip to main content

Module rolling_sum

Module rolling_sum 

Source
Expand description

§Rolling Sum

RollingSum tracks the sum of values in a fixed-size window. When the window is full, pushing a new value evicts the oldest.

API guarantees:

  • Add is O(1).
  • Total is O(1).
  • Overflow and underflow are detected and recoverable.
  • Zero heap allocations.

The value of this implementation is error recovery. RollingSum returns None as long as the inner sum overflows T::MAX or underflows T::MIN. And it resumes yielding Some(&T) as soon as the inner sum recovers.

use high_roller::rolling_sum::RollingSum;

let mut rsum: RollingSum<i8, 3> = RollingSum::default();

// Add an initial value.
rsum.add(5);
assert_eq!(rsum.total().copied(), Some(5));

// Stream of -1s takes over the window.
for _ in 0..100 {
    rsum.add(-1);
}
assert_eq!(rsum.total().copied(), Some(-3));

// Underflow forces total to None.
rsum.add(i8::MIN);
assert_eq!(rsum.total(), None);

// Balanced back to zero.
rsum.add(i8::MAX);
rsum.add(1);
assert_eq!(rsum.total().copied(), Some(0));

// Evicting i8::MIN causes overflow.
rsum.add(0);
assert_eq!(rsum.total(), None);

// Cause multiple overflows.
for _ in 0..100 {
    rsum.add(i8::MAX);
}
assert_eq!(rsum.total(), None);

// And recover back into an expected range.
for _ in 0..100 {
    rsum.add(1);
}
assert_eq!(rsum.total().copied(), Some(3));

Structs§

RollingSum
Tracks a rolling sum of at most WINDOW values.