/* 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 . */ #[derive(Clone)] pub struct Logger<'a> { pub entries: Vec>, } impl<'a> Logger<'a> { pub fn log(&mut self, entry: LogEntry<'a>) { if let LogEntry::Smart(mut smart) = entry { if self.entries.len() > 0 { if let LogEntry::Smart(last_smart) = self.entries.last_mut().unwrap() { if last_smart.template1 == smart.template1 && last_smart.template2 == smart.template2 { &last_smart.data.append(&mut smart.data); } else { self.entries.push(LogEntry::Smart(smart)); } } else { self.entries.push(LogEntry::Smart(smart)); } } else { self.entries.push(LogEntry::Smart(smart)); } } else { self.entries.push(entry); } } pub fn log_literal(&mut self, literal: String) { self.log(LogEntry::Literal(literal)); } pub fn log_smart(&mut self, template1: &'a str, template2: &'a str, data: Vec<&'a str>) { self.log(LogEntry::Smart(SmartLogEntry { template1: template1, template2: template2, data: data, })); } pub fn render(&self) -> Vec { return self.entries.iter().map(|e| match e { LogEntry::Smart(smart) => smart.render(), LogEntry::Literal(literal) => literal.to_string(), }).collect(); } } #[derive(Clone)] pub enum LogEntry<'a> { Smart(SmartLogEntry<'a>), Literal(String) } #[derive(Clone)] pub struct SmartLogEntry<'a> { template1: &'a str, template2: &'a str, data: Vec<&'a str>, } impl<'a> SmartLogEntry<'a> { pub fn render(&self) -> String { if self.data.len() == 0 { panic!("Attempted to format smart log entry with no data"); } else if self.data.len() == 1 { return String::from(self.template1).replace("{}", self.data.first().unwrap()); } else { let rendered_list = format!("{} and {}", self.data[0..self.data.len()-1].join(", "), self.data.last().unwrap()); return String::from(self.template2).replace("{}", &rendered_list); } } }