56 lines
1.8 KiB
Rust
56 lines
1.8 KiB
Rust
/* OpenTally: Open-source election vote counting
|
|
* Copyright © 2021 Lee Yingtong Li (RunasSudo)
|
|
*
|
|
* This program is free software: you can redistribute it and/or modify
|
|
* it under the terms of the GNU Affero General Public License as published by
|
|
* the Free Software Foundation, either version 3 of the License, or
|
|
* (at your option) any later version.
|
|
*
|
|
* This program is distributed in the hope that it will be useful,
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
* GNU Affero General Public License for more details.
|
|
*
|
|
* You should have received a copy of the GNU Affero General Public License
|
|
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
use crate::election::Election;
|
|
use crate::numbers::Number;
|
|
|
|
use csv::Writer;
|
|
|
|
use std::io::Write;
|
|
|
|
/// Write the [Election] into CSP format
|
|
pub fn write<W: Write, N: Number>(election: Election<N>, output: W) {
|
|
// Open writer
|
|
// csv::Writer performs its own buffering
|
|
let mut output = Writer::from_writer(output);
|
|
|
|
// Write header row
|
|
for candidate in election.candidates.iter() {
|
|
output.write_field(&candidate.name).expect("IO Error");
|
|
}
|
|
output.write_field("$mult").expect("IO Error");
|
|
output.write_record(None::<&[u8]>).expect("IO Error");
|
|
|
|
// Write ballots
|
|
for ballot in election.ballots {
|
|
// Code preferences to rankings
|
|
let mut rankings = vec![0_usize; election.candidates.len()];
|
|
for (i, preference) in ballot.preferences.into_iter().enumerate() {
|
|
for p in preference {
|
|
rankings[p] = i + 1;
|
|
}
|
|
}
|
|
|
|
// Write rankings
|
|
for ranking in rankings {
|
|
output.write_field(format!("{}", ranking)).expect("IO Error");
|
|
}
|
|
output.write_field(format!("{}", ballot.orig_value)).expect("IO Error");
|
|
output.write_record(None::<&[u8]>).expect("IO Error");
|
|
}
|
|
}
|