diff rust/src/main.rs @ 607:282fae1c12e4 rust

NotTooOften
author Matt Johnston <matt@ucc.asn.au>
date Fri, 17 Feb 2017 22:27:44 +0800
parents 278f1002b5c7
children 7bda01659426
line wrap: on
line diff
--- 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<Instant>,
+    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<F>(&self, op: F)
+        where F: Fn() {
+        let now = Instant::now();
+        if now - self.last.get() > self.limit {
+            self.last.set(now);
+            op();
+        }
+    }
+}
+