Skip to content

Instantly share code, notes, and snippets.

@dhilst
Last active April 10, 2020 05:33
Show Gist options
  • Save dhilst/c7dde72a8fa2c146d9762c13bd463aa5 to your computer and use it in GitHub Desktop.
Save dhilst/c7dde72a8fa2c146d9762c13bd463aa5 to your computer and use it in GitHub Desktop.
Rust simple rate limiter
use std::time::{Duration, Instant};
struct Limiter {
instant: Option<Instant>,
duration: Duration,
}
impl Limiter {
pub fn new(secs: u64) -> Limiter {
Limiter {
instant: None,
duration: Duration::from_secs(secs),
}
}
pub fn call<F, R>(&mut self, cb: F) -> Option<R>
where
F: Fn() -> R,
{
if self.instant.is_none() || self.instant.unwrap().elapsed() > self.duration {
self.instant = Some(Instant::now());
Some(cb())
} else {
None
}
}
}
fn main() {
let mut limiter = Limiter::new(3);
for i in { 0..10 } {
std::thread::sleep(Duration::from_secs(1));
println!("i {}", i);
limiter.call(&|| 1);
limiter.call(&|| println!("Hello"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment