Skip to content

Instantly share code, notes, and snippets.

@eknowlton
Created June 10, 2019 14:52
Show Gist options
  • Save eknowlton/072284792f28e9394defcd5cfd4e0c50 to your computer and use it in GitHub Desktop.
Save eknowlton/072284792f28e9394defcd5cfd4e0c50 to your computer and use it in GitHub Desktop.
Fun Log Parser
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