Guest User

counting the number of lines in rust

a guest
Sep 15th, 2014
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. use std::os;
  2. use std::io;
  3.  
  4. fn main() {
  5. let args = os::args();
  6. if args.len() != 2 {
  7. println!("Usage: {:s} <file>", args[0].as_slice());
  8. return;
  9. }
  10. let p = Path::new(args[1].as_slice());
  11. match io::File::open(&p) {
  12. Ok(f) => {
  13. let cnt = count_lines(f);
  14. println!("{}", cnt);
  15. }
  16. Err(e) => fail!("{}", e),
  17. }
  18. }
  19.  
  20. fn count_lines(mut f: io::File) -> uint {
  21. let mut lines = 0u;
  22.  
  23. // // ~ 1) slow
  24. // let mut r = io::BufferedReader::new(f);
  25. // loop {
  26. // match r.read_byte() {
  27. // Ok(c) => if c == b'\n' {lines += 1;},
  28. // Err(_) => break,
  29. // }
  30. // }
  31.  
  32. // // ~ 2) slow as well
  33. // lines += io::BufferedReader::new(f).chars().filter(|c| match c {
  34. // &Ok(c) if c == '\n' => true,
  35. // _ => false,
  36. // }).count();
  37.  
  38. // // ~ 3) faster by still slow
  39. // lines += io::BufferedReader::new(f).lines().count();
  40.  
  41. // ~ 4) as fast as i could get it so far
  42. let mut buf = [0u8, ..64*1024];
  43. loop {
  44. match f.read(buf) {
  45. Ok(n) => {
  46. for i in range(0, n) {
  47. if buf[i] == b'\n' {
  48. lines += 1;
  49. }
  50. }
  51. }
  52. Err(_) => {
  53. break;
  54. }
  55. }
  56. }
  57.  
  58. return lines;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment