use super::Aggregate;
use crate::{Headers, Row, error};
#[derive(Default, Debug)]
pub struct Avg {
source: String,
colname: String,
sum: f64,
count: u64,
}
impl Avg {
pub fn new(colname: String, source: String) -> Avg {
Avg {
source,
colname,
..Default::default()
}
}
}
impl Aggregate for Avg {
fn update(&mut self, headers: &Headers, row: &Row) -> error::Result<()> {
match headers.get_field(row, &self.source) {
Some(data) => match data.parse::<f64>() {
Ok(num) => {
self.sum += num;
self.count += 1;
Ok(())
}
Err(_) => Err(error::Error::ValueError {
data: data.into(),
to_type: "f64".into(),
}),
},
None => Err(error::Error::ColumnNotFound(self.source.to_string())),
}
}
fn value(&self) -> String {
if self.count != 0 {
(self.sum / self.count as f64).to_string()
} else {
"NaN".to_string()
}
}
fn colname(&self) -> &str {
&self.colname
}
}
#[cfg(test)]
mod tests {
use super::{Aggregate, Avg};
use crate::{Row, error::Error};
#[test]
fn test_avg() {
let mut avg = Avg::new("new".into(), "a".into());
let h = Row::from(vec!["a"]).into();
let r = Row::from(vec!["3.0"]);
avg.update(&h, &r).unwrap();
let r = Row::from(vec!["2"]);
avg.update(&h, &r).unwrap();
let r = Row::from(vec![".5"]);
avg.update(&h, &r).unwrap();
let r = Row::from(vec![".5"]);
avg.update(&h, &r).unwrap();
assert_eq!(avg.value(), "1.5");
}
#[test]
fn test_missing_column() {
let mut avg = Avg::new("new".into(), "a".into());
let h = Row::from(vec!["b"]).into();
let r = Row::from(vec!["3.0"]);
match avg.update(&h, &r) {
Err(Error::ColumnNotFound(val)) => assert_eq!(val, "a"),
_ => panic!("Test failed"),
}
}
#[test]
fn test_value_error() {
let mut avg = Avg::new("new".into(), "a".into());
let h = Row::from(vec!["a"]).into();
let r = Row::from(vec!["chicken"]);
match avg.update(&h, &r) {
Err(Error::ValueError{ data, to_type }) => {
assert_eq!(data, "chicken");
assert_eq!(to_type, "f64");
}
_ => panic!("Test failed"),
}
}
}