[ create a new paste ] login | about

Link: http://codepad.org/O0A4Vl5r    [ raw code | fork ]

Plain Text, pasted on May 24:
/*
Cargo.toml contains:

[dependencies]
smallstring = "0.1.2"
ordermap = "0.2.10"

[profile.release]
opt-level = 3
lto = true
panic = "abort"


Compiled with:
cargo rustc --release --bin max_column_sum_by_key -- -C target-cpu=native
*/

extern crate ordermap;
extern crate smallstring;

fn main() {
    use std::cmp::max;
    use std::fs::File;
    use std::io::{BufReader, BufRead};
    use ordermap::OrderMap;
    use smallstring::SmallString;

    let args: Vec<_> = std::env::args().collect();
    if args.len() != 4 {
        return eprintln!("synopsis: {} filename keyfield valuefield", args[0]);
    }

    let file_name = &args[1];
    let key_field_index: usize = args[2].parse().unwrap();
    let value_field_index: usize = args[3].parse().unwrap();
    let max_field_index = max(key_field_index, value_field_index);
    let delim = '\t';
    let mut sum_by_key = OrderMap::<SmallString, i64>::new();

    for line in BufReader::new(File::open(file_name).unwrap()).lines() {
        let mut key = None;
        let mut field_value = None;

        for (i, field) in line.unwrap().splitn(max_field_index + 2, delim).enumerate() {
            if i == key_field_index {
                key = Some(field.into());
            } else if i == value_field_index {
                field_value = Some(field.parse().unwrap());
            }
        }

        if let (Some(key), Some(field_value)) = (key, field_value) {
            *sum_by_key.entry(key).or_insert(0) += field_value;
        }
    }

    if let Some((max_key, max_val)) = sum_by_key.iter().max_by_key(|&(_, v)| v) {
        println!("max_key: {} sum: {}", max_key, max_val);
    } else {
        println!("No entries");
    }
}


Create a new paste based on this one


Comments: