Skip to content

Instantly share code, notes, and snippets.

@pmagwene
Created January 9, 2020 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmagwene/60fbaee14b63c5677f7fb9567f75b290 to your computer and use it in GitHub Desktop.
Save pmagwene/60fbaee14b63c5677f7fb9567f75b290 to your computer and use it in GitHub Desktop.
Rust parsing example
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::time::Instant;
#[derive(Debug)]
struct Record {
words: Vec<String>,
}
impl Record {
fn new() -> Record {
Record { words: Vec::new() }
}
fn parse(s: &str) -> Record {
// Record::new()
Record {
words: s.split_whitespace().map(str::to_owned).collect(),
}
}
}
#[derive(Debug)]
struct Table {
records: Vec<Record>,
}
impl Table {
fn new() -> Table {
Table {
records: Vec::new(),
}
}
fn parse(mut r: impl BufRead) -> Table {
let mut tbl = Table::new();
let mut line = String::new();
while r.read_line(&mut line).unwrap() > 0 {
let rec = Record::parse(&line);
tbl.records.push(rec);
line.clear();
}
tbl
}
}
fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
panic!("Must specify file argument")
}
let file = File::open(&args[1]).unwrap();
let timer = Instant::now();
let tbl = Table::parse(BufReader::new(file));
let duration = timer.elapsed();
println!("Time elapsed to parse records: {:?}", duration);
println!("Number of records: {}", tbl.records.len());
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment