Skip to content

Instantly share code, notes, and snippets.

@ykon
Last active January 19, 2019 13:43
Show Gist options
  • Select an option

  • Save ykon/19fa1f43861991cc7bf1ee78c731c8fc to your computer and use it in GitHub Desktop.

Select an option

Save ykon/19fa1f43861991cc7bf1ee78c731c8fc to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Result};
type MailHeader = HashMap<String, Vec<String>>;
fn proc_folding_line(line: String, prev_fname: &String, mail_header: &mut MailHeader) {
if prev_fname == "" {
eprintln!("prev-key error: line: {}", line);
}
else {
match mail_header.get_mut(prev_fname) {
Some(v) => match v.last_mut() {
Some(last) => *last = format!("{} {}", last, line.trim_start()),
None => eprintln!("vec error: prev_fname: {}, line: {}", prev_fname, line),
},
None => eprintln!("key error: prev_fname: {}, line: {}", prev_fname, line),
}
}
}
fn proc_header_line(line: String, mail_header: &mut MailHeader) -> String {
let kv: Vec<&str> = line.splitn(2, ':').collect();
let fname = kv[0].to_lowercase().to_string();
let fvalue = kv[1].trim_start().to_string();
match mail_header.get_mut(&fname) {
Some(v) => v.push(fvalue),
None => {
mail_header.insert(fname.clone(), vec![fvalue]);
},
}
fname
}
fn main() {
let mut mail_header: MailHeader = HashMap::new();
let file = File::open("data.txt").expect("IO error");
let mut prev_fname = String::from("");
for line in BufReader::new(file).lines().filter_map(Result::ok) {
if line == "" { // \r\n\r\n
break;
}
if line.starts_with(' ') || line.starts_with('\t') {
proc_folding_line(line, &prev_fname, &mut mail_header);
}
else {
prev_fname = proc_header_line(line, &mut mail_header);
}
}
//println!("{:?}", mail_header);
for (fname, fvalue) in mail_header {
println!("{}: {:?}", fname, fvalue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment