Use closures

This commit is contained in:
Kenan Sulayman 2016-11-04 02:04:58 +01:00
parent f475dc2746
commit c08f460021
No known key found for this signature in database
GPG key ID: 76E277996E0723A2
3 changed files with 15 additions and 23 deletions

View file

@ -22,14 +22,10 @@ Add to your code,
extern crate logwatcher; extern crate logwatcher;
use logwatcher::LogWatcher; use logwatcher::LogWatcher;
Create a callback function, which accepts String as input Register the logwatcher, pass a closure and watch it!
fn parse_line(line: String) {
println!("Line {}", line);
}
Register the logwatcher and watch it!
let mut log_watcher = LogWatcher::register("/var/log/check.log".to_string()).unwrap(); let mut log_watcher = LogWatcher::register("/var/log/check.log".to_string()).unwrap();
log_watcher.watch(parse_line);
log_watcher.watch(&|line: String| {
println!("Line {}", line);
});

View file

@ -38,7 +38,8 @@ impl LogWatcher {
finish: false}) finish: false})
} }
fn reopen_if_log_rotated(&mut self, callback: fn (line: String)){ fn reopen_if_log_rotated<F: ?Sized>(&mut self, callback: &F)
where F: Fn(String) {
loop { loop {
match File::open(self.filename.clone()) { match File::open(self.filename.clone()) {
Ok(x) => { Ok(x) => {
@ -74,7 +75,8 @@ impl LogWatcher {
} }
} }
pub fn watch(&mut self, callback: fn (line: String)) { pub fn watch<F: ?Sized>(&mut self, callback: &F)
where F: Fn(String) {
loop{ loop{
let mut line = String::new(); let mut line = String::new();
let resp = self.reader.read_line(&mut line); let resp = self.reader.read_line(&mut line);
@ -102,8 +104,3 @@ impl LogWatcher {
} }
} }
} }
#[test]
fn it_works() {
}

View file

@ -4,11 +4,6 @@ use std::process::exit;
extern crate logwatcher; extern crate logwatcher;
use logwatcher::LogWatcher; use logwatcher::LogWatcher;
fn parse_line(line: String) {
println!("Line {}", line);
}
fn main(){ fn main(){
let filename = match args().nth(1) { let filename = match args().nth(1) {
Some(x) => x, Some(x) => x,
@ -17,6 +12,10 @@ fn main(){
exit(1); exit(1);
} }
}; };
let mut log_watcher = LogWatcher::register(filename).unwrap(); let mut log_watcher = LogWatcher::register(filename).unwrap();
log_watcher.watch(parse_line);
log_watcher.watch(&|line: String| {
println!("Line {}", line);
});
} }