csvsc 2.2.1

Build processing chains for CSV files
Documentation
use std::str::FromStr;
use std::cmp::PartialOrd;
use std::fmt::{Display, Debug};

use super::Aggregate;
use crate::{Headers, Row, error};

#[derive(Debug)]
pub struct Max<T> {
    source: String,
    current: T,
    colname: String,
    default: T,
}

impl<T: Copy> Max<T> {
    pub fn new(colname: String, source: String, init: T) -> Max<T> {
        Max {
            source,
            colname,
            current: init,
            default: init,
        }
    }
}

impl<T> Aggregate for Max<T>
where
    T: FromStr + PartialOrd + Display + Copy,
{
    fn update(&mut self, headers: &Headers, row: &Row) -> error::Result<()> {
        match headers.get_field(row, &self.source) {
            Some(data) =>  {
                let val: T = data.parse().unwrap_or(self.default);

                if val > self.current {
                    self.current = val;
                }

                Ok(())
            },
            None => Err(error::Error::ColumnNotFound(self.source.to_string())),
        }
    }

    fn value(&self) -> String {
        self.current.to_string()
    }

    fn colname(&self) -> &str {
        &self.colname
    }
}

#[cfg(test)]
mod tests {
    use std::f64;

    use super::{Aggregate, Max};
    use crate::{Row, error};

    #[test]
    fn test_max() {
        let mut max = Max::new("new".into(), "a".into(), f64::NEG_INFINITY);
        let h = Row::from(vec!["a"]).into();

        let r = Row::from(vec!["3.0"]);
        max.update(&h, &r).unwrap();
        let r = Row::from(vec!["2"]);
        max.update(&h, &r).unwrap();
        let r = Row::from(vec![".5"]);
        max.update(&h, &r).unwrap();

        assert_eq!(max.value(), "3");
    }

    #[test]
    fn test_missing_column() {
        let mut max = Max::new("new".into(), "a".into(), f64::NEG_INFINITY);
        let h = Row::from(vec!["b"]).into();

        let r = Row::from(vec!["3.0"]);

        match max.update(&h, &r) {
            Err(error::Error::ColumnNotFound(val)) => assert_eq!(val, "a"),
            _ => panic!("Test failed"),
        }
    }

    #[test]
    fn test_value_error() {
        let mut max = Max::new("new".into(), "a".into(), f64::NEG_INFINITY);
        let h = Row::from(vec!["a"]).into();

        let r = Row::from(vec!["chicken"]);

        max.update(&h, &r).unwrap();

        assert_eq!(max.value(), "-inf");
    }

    #[test]
    fn test_default() {
        let mut max = Max::new("new".into(), "a".into(), 1.0);
        let h = Row::from(vec!["a"]).into();

        let r = Row::from(vec!["-1.0"]);
        max.update(&h, &r).unwrap();
        let r = Row::from(vec!["0.0"]);
        max.update(&h, &r).unwrap();
        let r = Row::from(vec!["pollo"]);
        max.update(&h, &r).unwrap();

        assert_eq!(max.value(), "1");
    }
}