+#[derive(Debug)]
+struct Range {
+ start: u64,
+ end: u64,
+}
+impl Range {
+ fn new(t: &u64) -> Self {
+ Self { start: *t, end: *t }
+ }
+ fn contains(&self, t: &u64) -> bool {
+ t > &self.start && t < &self.end
+ }
+ fn extend(&mut self, t: &u64) {
+ if t < &self.start {
+ self.start = *t;
+ }
+ if t > &self.end {
+ self.end = *t;
+ }
+ }
+}
+
+fn merge_message(presses: &mut HashMap<MessageKey, Range>, message: Message) {
+ let key = message.key();
+ if let Some(r) = presses.get_mut(&key) {
+ if !r.contains(&message.t) {
+ r.extend(&message.t);
+ }
+ } else {
+ presses.insert(key, Range::new(&message.t));
+ }
+}
+
+fn replay_log() -> HashMap<MessageKey, Range> {
+ let mut presses = HashMap::new();
+ if std::path::Path::new(LOGFILENAME).exists() {
+ let mut log = csv::Reader::from_path(LOGFILENAME).expect("Couldn't open log for replay");
+ for message in log.deserialize() {
+ merge_message(
+ &mut presses,
+ message.expect("Error reading log during replay"),
+ );
+ }
+ }
+ presses
+}
+
+fn open_log_for_writing() -> csv::Writer<std::fs::File> {
+ let log_file_exists = std::path::Path::new(LOGFILENAME).exists();
+ let logfile = std::fs::OpenOptions::new()
+ .create_new(!log_file_exists)
+ .append(true)
+ .open(LOGFILENAME)
+ .expect("Coudln't open log file");
+ csv::WriterBuilder::new()
+ .has_headers(!log_file_exists)
+ .from_writer(logfile)
+}
+