Created
December 30, 2018 10:55
-
-
Save djhworld/ced7eabca8e0c06d5b65917e87fb8745 to your computer and use it in GitHub Desktop.
improved version
This file contains hidden or 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::collections::HashMap; | |
use std::io; | |
use std::io::BufRead; | |
struct Counter { | |
items: HashMap<String, usize>, | |
} | |
impl Counter { | |
fn new() -> Counter { | |
return Counter { | |
items: HashMap::new(), | |
}; | |
} | |
fn add(&mut self, st: &str) { | |
match self.items.get_mut(st) { | |
Some(x) => { | |
*x += 1; | |
} | |
None => { | |
self.items.insert(st.to_owned(), 1); | |
} | |
} | |
} | |
fn render(&self) { | |
for (key, val) in &self.items { | |
println!("{}\t{}", val, key); | |
} | |
} | |
} | |
fn using_read_line_with_reuse(c: &mut Counter) { | |
let st = io::stdin(); | |
let mut stdin = st.lock(); | |
let mut line = String::new(); | |
loop { | |
line.clear(); | |
let r = stdin.read_line(&mut line); | |
match r { | |
Ok(0) => break, | |
Ok(_) => { | |
c.add(line.trim_end()); | |
} | |
Err(err) => { | |
println!("{}", err); | |
break; | |
} | |
}; | |
} | |
} | |
fn using_read_line(c: &mut Counter) { | |
let st = io::stdin(); | |
let mut stdin = st.lock(); | |
loop { | |
let mut line = String::new(); | |
let r = stdin.read_line(&mut line); | |
match r { | |
Ok(0) => break, | |
Ok(_) => { | |
c.add(line.trim_end()); | |
} | |
Err(err) => { | |
println!("{}", err); | |
break; | |
} | |
}; | |
} | |
} | |
// uses lines() iterator | |
fn using_bufread_lines(c: &mut Counter) { | |
for r in io::stdin().lock().lines().filter_map(Result::ok) { | |
c.add(r.as_str()); | |
} | |
} | |
fn main() { | |
let mut c = Counter::new(); | |
// using_bufread_lines(&mut c); | |
//using_read_line(&mut c); | |
using_read_line_with_reuse(&mut c); | |
c.render(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another suggestion was to use the change the hashmap implementation to the crate
hashbrown
, here are the resultsThe
buf.lines()
implementation is now almost the same as the go version, and the other 2 rust implementations are faster