made counter.rs

This commit is contained in:
Jay Robson 2025-05-03 21:30:39 +10:00
parent 29ffe1190f
commit 4645cb31ee
2 changed files with 32 additions and 9 deletions

22
src/counter.rs Normal file
View File

@ -0,0 +1,22 @@
use crate::{ballot::Ballot, 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 ballots = Ballot::parse_rows(csv, &header)?;
Ok(Counter {
header,
ballots,
})
}
}

View File

@ -1,11 +1,13 @@
use std::env; use std::env;
use ballot::{Ballot, BallotType}; use ballot::{Ballot, BallotType};
use counter::Counter;
use header::Header; use header::Header;
pub mod candidate; pub mod candidate;
mod ballot; pub mod ballot;
mod header; pub mod header;
mod counter;
fn main() { fn main() {
let csv_path = { let csv_path = {
@ -16,18 +18,17 @@ fn main() {
} }
args[1].clone() args[1].clone()
}; };
let mut csv = quick_csv::Csv::from_file(csv_path).unwrap().flexible(true); let csv = quick_csv::Csv::from_file(csv_path).unwrap().flexible(true);
let header = Header::parse(csv.next().unwrap().unwrap()).unwrap(); let counter = Counter::new(csv).unwrap();
let ballots = Ballot::parse_rows(csv, &header).unwrap();
println!("Parties: {}", header.parties.len()); println!("Parties: {}", counter.header.parties.len());
println!("Candidates: {}", header.candidates.len()); println!("Candidates: {}", counter.header.candidates.len());
let total = ballots.len() as u32; let total = counter.ballots.len() as u32;
let mut total_atl = 0u32; let mut total_atl = 0u32;
let mut total_btl = 0u32; let mut total_btl = 0u32;
for ballot in ballots.iter() { for ballot in counter.ballots.iter() {
*match ballot.ty { *match ballot.ty {
BallotType::Party => &mut total_atl, BallotType::Party => &mut total_atl,
BallotType::Candidate => &mut total_btl, BallotType::Candidate => &mut total_btl,