# HG changeset patch # User Matt Johnston # Date 1487341664 -28800 # Node ID 282fae1c12e42ef40fc72259c7b8c7e1e504e8bd # Parent 3c1d37d78415f8a1738ae215d5776869eaa49f00 NotTooOften diff -r 3c1d37d78415 -r 282fae1c12e4 rust/src/main.rs --- a/rust/src/main.rs Fri Feb 17 21:38:45 2017 +0800 +++ b/rust/src/main.rs Fri Feb 17 22:27:44 2017 +0800 @@ -18,6 +18,9 @@ extern crate docopt; use std::io; +use std::time::{Duration,Instant}; +use std::ops::Not; +use std::cell::Cell; use tokio_core::reactor::Core; use futures::{Stream,Sink,Future}; @@ -173,3 +176,27 @@ run(&config, args.flag_nowait, args.flag_test); } +/// Call closures with a rate limit. Useful for log message ratelimiting +pub struct NotTooOften { + last: Cell, + limit: Duration, +} + +impl NotTooOften { + pub fn new(limit_secs: u64) -> Self { + NotTooOften { + limit: Duration::new(limit_secs, 0), + last: Cell::new(Instant::now() - Duration::new(limit_secs+1, 0)), + } + } + + pub fn and_then(&self, op: F) + where F: Fn() { + let now = Instant::now(); + if now - self.last.get() > self.limit { + self.last.set(now); + op(); + } + } +} +