Created
June 10, 2019 14:52
-
-
Save eknowlton/072284792f28e9394defcd5cfd4e0c50 to your computer and use it in GitHub Desktop.
Fun Log Parser
This file contains 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
extern crate chrono; | |
extern crate regex; | |
use chrono::{NaiveDate, NaiveDateTime}; | |
use regex::Regex; | |
use std::io::{self, BufRead}; | |
struct Item { | |
date: NaiveDate, | |
count: i32, | |
} | |
impl Item { | |
fn new(date: NaiveDate) -> Self { | |
Item { date, count: 1 } | |
} | |
fn add(&mut self) -> &Self { | |
self.count += 1; | |
self | |
} | |
} | |
fn read_input_line_by_line() { | |
let stdin = io::stdin(); | |
let search = Regex::new(r"\[([^\]]*)\]").unwrap(); | |
let mut results: Vec<Item> = Vec::new(); | |
for line in stdin.lock().lines() { | |
let line = line.unwrap(); | |
parse_line(&search, &line[..], &mut results); | |
} | |
for result in results.iter() { | |
println!("On {}, there were {} calls", result.date, result.count); | |
} | |
} | |
fn parse_line(search: &Regex, line: &str, results: &mut Vec<Item>) { | |
let parts = match search.captures(line) { | |
Some(parts) => parts, | |
_ => return, | |
}; | |
let date_time = parts.get(1).unwrap().as_str(); | |
let date = NaiveDateTime::parse_from_str(date_time, "%Y-%m-%d %H:%M").unwrap(); | |
match results.iter_mut().find(|r| r.date == date.date()) { | |
Some(r) => { | |
r.add(); | |
} | |
None => { | |
results.push(Item::new(date.date())); | |
} | |
}; | |
} | |
fn main() { | |
read_input_line_by_line(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment