rust
41 lines · 6 steps
A rolling average over a sliding window
A fixed-size ring keeps a running sum so each new reading yields an average in constant time.
Explained by
highlit
1use std::collections::VecDeque;
2
3pub struct RollingAverage {
4 window: VecDeque<f64>,
5 capacity: usize,
6 sum: f64,
7}
8
9impl RollingAverage {
10 pub fn new(capacity: usize) -> Self {
11 assert!(capacity > 0, "window capacity must be non-zero");
12 Self {
13 window: VecDeque::with_capacity(capacity),
14 capacity,
15 sum: 0.0,
16 }
17 }
18
19 pub fn push(&mut self, reading: f64) -> f64 {
20 if self.window.len() == self.capacity {
21 if let Some(oldest) = self.window.pop_front() {
22 self.sum -= oldest;
23 }
24 }
25 self.window.push_back(reading);
26 self.sum += reading;
27 self.average()
28 }
29
30 pub fn average(&self) -> f64 {
31 if self.window.is_empty() {
32 0.0
33 } else {
34 self.sum / self.window.len() as f64
35 }
36 }
37
38 pub fn is_full(&self) -> bool {
39 self.window.len() == self.capacity
40 }
41}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Maintaining a running sum alongside the window turns each average into an O(1) update instead of re-summing the whole buffer.
- 2A VecDeque is the natural fit for a sliding window because it supports cheap pushes and pops at both ends.
- 3Keeping the sum in sync means every mutation must both add the new value and subtract whatever leaves the window.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
rust
use axum::{ extract::State, routing::{get, post, MethodRouter}, Json, Router,
Self-documenting routes in Axum
builder-pattern
closures
shared-state
Intermediate
8 steps
rust
use std::collections::HashMap; use std::fs::File; use std::io::{self, BufRead, BufReader}; use std::path::Path;
Parsing INI files in Rust
parsing
file-io
hashmap
Intermediate
9 steps
rust
use axum::{ extract::{Path, Query}, http::Uri, response::{IntoResponse, Redirect},
Building HTTP redirect handlers in Axum
redirects
extractors
url-handling
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-rolling-average-over-a-sliding-window-explained-rust-4cb9/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.