Last active
April 10, 2020 05:33
-
-
Save dhilst/c7dde72a8fa2c146d9762c13bd463aa5 to your computer and use it in GitHub Desktop.
Rust simple rate limiter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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