ballot-counter/src/counter.rs

46 lines
867 B
Rust

use crate::{ballot::{Ballot, BallotType}, header::Header};
#[derive(Debug)]
pub struct Counter {
pub header: Header,
pub ballots: Vec<Ballot>,
}
impl Counter {
pub fn new<T: std::io::BufRead>(mut csv: quick_csv::Csv<T>) -> Result<Self, Box<dyn std::error::Error>> {
let header = Header::parse(csv.next().ok_or("csv header missing")??)?;
let mut ballots = Vec::new();
for row in csv {
ballots.push(Ballot::parse(row?, &header)?.to_candidate_ballot(&header));
}
Ok(Counter {
header,
ballots,
})
}
pub fn count_primaries(&self, ty: BallotType, running: &[bool]) -> Vec<u32> {
let mut scores = vec![0; running.len()];
for ballot in self.ballots.iter() {
if ballot.ty != ty {
continue;
}
for &id in ballot.votes.iter() {
if !running[id] {
continue;
}
scores[id] += 1;
break;
}
}
scores
}
}