hail_core 0.3.0

a library for implementing a speedrun timer
Documentation
/*
  Copyright 2024 periwinkle

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

use crate::{
    Result, Run,
    error::DeError,
    types::{Comparison, SplitStatus, TimeType},
};

use std::io::{Read, Write};

use ron::{
    Options,
    de::from_reader,
    ser::{PrettyConfig, to_string_pretty},
};
use serde::{Deserialize, Serialize};

/// Information necessary to recreate any `HailState`.
///
/// Intended to be serialized and saved so that the state can be restored later.
/// Contains all necessary information to recreate any `HailState` exactly.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StateDump {
    pub run: Run,
    pub comparison: Comparison,
    pub current_seg: usize,
    pub rta: TimerDump,
    pub igt: TimerDump,
    pub igt_paused: bool,
}

impl StateDump {
    /// Deserialize a state dump from a reader.
    pub fn from_reader(r: impl Read) -> Result<Self> {
        let mut s: Self = from_reader(r).map_err(DeError::Ron)?;
        s.run.verify()?;
        s.run.normalize();
        s.run.calc_avgs();
        Ok(s)
    }
    /// Serialize the state dump to a string.
    pub fn to_string(&self) -> Result<String> {
        Ok(to_string_pretty(self, PrettyConfig::new())?)
    }
    /// Serialize the state dump to a writer.
    pub fn to_writer(&self, w: impl Write) -> Result<()> {
        Ok(Options::default().to_io_writer_pretty(w, self, PrettyConfig::new())?)
    }
}

/// Information necessary to recreate any `HailTimer`.
///
/// Intended to be serialized and saved so that the state can be restored later.
/// Contains all necessary information to recreate any `HailTimer` exactly. This is not
/// all of the information contained in `HailTimer`, as the rest can be recalculated.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TimerDump {
    pub active_time: i128,
    pub run_split_times: Vec<TimeType>,
    pub run_seg_times: Vec<TimeType>,
    pub run_pb_statuses: Vec<SplitStatus>,
    pub run_gold_statuses: Vec<SplitStatus>,
    pub run_avg_statuses: Vec<SplitStatus>,
    pub run_pb_diffs: Vec<TimeType>,
    pub run_pb_seg_diffs: Vec<TimeType>,
    pub run_gold_diffs: Vec<TimeType>,
    pub run_gold_seg_diffs: Vec<TimeType>,
    pub run_avg_diffs: Vec<TimeType>,
    pub run_avg_seg_diffs: Vec<TimeType>,
    // have to preserve these because the average is the only one that gets directly updated in the Run
    // and thus the originals are not retrievable from the run without a lot of work.
    pub avg_split_times: Vec<TimeType>,
}