hail_core 0.3.0

a library for implementing a speedrun timer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/*
  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/.
*/

#[cfg(feature = "serde")]
mod back_compat;
#[cfg(feature = "serde")]
mod hrn;
#[cfg(feature = "serde")]
mod lss;
#[cfg(feature = "serde")]
mod ser_des;
#[cfg(feature = "serde")]
pub use ser_des::SerDesRun;

use crate::types::{TimeType, TimingMethod};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Information about a speedrun, and a record of times set in it.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Run {
    pub game_title: String,
    pub category: String,
    /// Whether the run saves ingame time.
    pub ingame_time: bool,
    /// Time that the timer starts at. Can be positive or negative.
    pub offset: TimeType,
    pub segment_names: Vec<String>,
    /// Splits set in real-time for the fastest completed run.
    pub rta_pb_splits: Vec<TimeType>,
    /// Splits set in game-time for the fastest completed run.
    pub igt_pb_splits: Vec<TimeType>,
    rta_pb_segments: Vec<TimeType>,
    igt_pb_segments: Vec<TimeType>,
    /// Fastest individual segments set in real-time.
    pub rta_gold_segments: Vec<TimeType>,
    /// Fastest individual segments set in game-time.
    pub igt_gold_segments: Vec<TimeType>,
    rta_sum_segments: Vec<(usize, TimeType)>,
    igt_sum_segments: Vec<(usize, TimeType)>,
    rta_avg_segments: Vec<TimeType>,
    igt_avg_segments: Vec<TimeType>,
}

impl Run {
    /// Add an attempt to a segment's sum.
    ///
    /// Increments attempt count and adds `time` to sum of the `idx`th segment for the specified
    /// `method` only, and recalculates the average time.
    ///
    /// Calling this does nothing if `idx` is outside the segments for the `method`.
    pub fn add_segment_attempt(&mut self, idx: usize, time: TimeType, method: TimingMethod) {
        if method == TimingMethod::Rta {
            if idx >= self.rta_sum_segments.len() {
                return;
            }
            let s = &mut self.rta_sum_segments[idx];
            s.0 += 1;
            s.1 += time;
            self.rta_avg_segments[idx] = TimeType::from(s.1.val() / (s.0 as i128));
        } else {
            if idx >= self.igt_sum_segments.len() {
                return;
            }
            let s = &mut self.igt_sum_segments[idx];
            s.0 += 1;
            s.1 += time;
            self.igt_avg_segments[idx] = TimeType::from(s.1.val() / (s.0 as i128));
        };
    }
    /// Remove time and an attempt from a segment.
    ///
    /// Decrements attempt count and subtracts `time` from sum of the `idx`th segment for the specified
    /// `method` only, and recalculates the average time.
    ///
    /// Calling this does nothing if the attempt count is already 0, or `idx` is outside the segments for the `methdod`.
    pub fn remove_segment_attempt(&mut self, idx: usize, time: TimeType, method: TimingMethod) {
        let (s, a) = if method == TimingMethod::Rta {
            if idx >= self.rta_sum_segments.len() {
                return;
            }
            (
                &mut self.rta_sum_segments[idx],
                &mut self.rta_avg_segments[idx],
            )
        } else {
            if idx >= self.igt_sum_segments.len() {
                return;
            }
            (
                &mut self.igt_sum_segments[idx],
                &mut self.igt_avg_segments[idx],
            )
        };
        if s.0 > 1 {
            s.0 -= 1;
            s.1 -= time;
            *a = TimeType::from(s.1.val() / (s.0 as i128));
        } else if s.0 == 1 && s.1 == time {
            s.0 -= 1;
            s.1 = TimeType::None;
            *a = TimeType::None;
        }
    }
    /// Get the total PB time for the given `method`.
    pub fn pb(&self, method: TimingMethod) -> TimeType {
        *if method == TimingMethod::Rta {
            &self.rta_pb_splits
        } else {
            &self.igt_pb_splits
        }
        .last()
        .unwrap_or(&TimeType::None)
    }
    /// Get the average segment times of the run for the given `method`.
    pub fn avg_segments(&self, method: TimingMethod) -> &Vec<TimeType> {
        if method == TimingMethod::Rta {
            &self.rta_avg_segments
        } else {
            &self.igt_avg_segments
        }
    }
    /// Get the PB segment times of the run for the given `method`.
    pub fn pb_segments(&self, method: TimingMethod) -> &Vec<TimeType> {
        if method == TimingMethod::Rta {
            &self.rta_pb_segments
        } else {
            &self.igt_pb_segments
        }
    }
    /// Verify whether a run is valid.
    ///
    /// Returns `Ok(())` if the run is valid. Otherwise returns `Err` with the
    /// [`InvalidReason`] that the run was not valid.
    pub fn verify(&self) -> Result<(), InvalidReason> {
        use InvalidReason::*;
        let len = self.segment_names.len();
        if len == 0 {
            return Err(NoSegments);
        }
        if self.rta_pb_splits.len() != len {
            return Err(WrongLenPb(TimingMethod::Rta));
        } else if self.rta_gold_segments.len() != len {
            return Err(WrongLenGold(TimingMethod::Rta));
        } else if self.rta_sum_segments.len() != len {
            return Err(WrongLenSum(TimingMethod::Rta));
        }
        let mut prev = TimeType::None;
        for (i, &t) in self.rta_pb_splits.iter().enumerate() {
            if t.val() < 0 {
                return Err(NegPbSplit(i, TimingMethod::Rta));
            }
            if t.is_time() && t <= prev {
                return Err(NonIncreasingSplit(i, TimingMethod::Rta));
            }
            prev = t;
        }
        for (i, &t) in self.rta_gold_segments.iter().enumerate() {
            if t.val() < 0 {
                return Err(NegGoldSeg(i, TimingMethod::Rta));
            }
        }
        for (i, &(n, t)) in self.rta_sum_segments.iter().enumerate() {
            if t.val() < 0 {
                return Err(NegSumTime(i, TimingMethod::Rta));
            } else if n == 0 && t.val() != 0 {
                return Err(ZeroSegCount(i, TimingMethod::Rta));
            }
        }

        // only try to verify ingame if it is necessary
        if self.ingame_time {
            if self.igt_pb_splits.len() != len {
                return Err(WrongLenPb(TimingMethod::Igt));
            } else if self.igt_sum_segments.len() != len {
                return Err(WrongLenSum(TimingMethod::Igt));
            }
            let mut prev = TimeType::None;
            for (i, &t) in self.igt_pb_splits.iter().enumerate() {
                if t.val() < 0 {
                    return Err(NegPbSplit(i, TimingMethod::Igt));
                }
                if t.is_time() && t <= prev {
                    return Err(NonIncreasingSplit(i, TimingMethod::Rta));
                }
                prev = t;
            }
            for (i, &t) in self.igt_gold_segments.iter().enumerate() {
                if t.val() < 0 {
                    return Err(NegGoldSeg(i, TimingMethod::Igt));
                }
            }
            for (i, &(n, t)) in self.igt_sum_segments.iter().enumerate() {
                if t.val() < 0 {
                    return Err(NegSumTime(i, TimingMethod::Igt));
                } else if n == 0 && t.val() != 0 {
                    return Err(ZeroSegCount(i, TimingMethod::Igt));
                }
            }
        }
        Ok(())
    }
    /// Set any instances of `Time(0)` to `None`.
    pub fn normalize(&mut self) {
        self.offset.normalize();
        for t in &mut self.rta_pb_splits {
            t.normalize();
        }
        for t in &mut self.rta_gold_segments {
            t.normalize();
        }
        for (_, t) in &mut self.rta_sum_segments {
            t.normalize();
        }
        for t in &mut self.igt_pb_splits {
            t.normalize();
        }
        for t in &mut self.igt_gold_segments {
            t.normalize();
        }
        for (_, t) in &mut self.igt_sum_segments {
            t.normalize();
        }
    }
    /// Calculate all average segments.
    ///
    /// Assumes run has passed [`verify`](Self::verify).
    pub fn calc_avgs(&mut self) {
        self.rta_avg_segments = self
            .rta_sum_segments
            .iter()
            .map(|&(n, t)| {
                if t == TimeType::None {
                    TimeType::None
                } else {
                    TimeType::from(t.val() / n as i128)
                }
            })
            .collect();
        self.igt_avg_segments = self
            .igt_sum_segments
            .iter()
            .map(|&(n, t)| {
                if t == TimeType::None {
                    TimeType::None
                } else {
                    TimeType::from(t.val() / n as i128)
                }
            })
            .collect();
    }
    /// Calculate PB segment times.
    ///
    /// Assumes the run has passed [`verify`](Self::verify)
    pub fn calc_segments(&mut self) {
        self.rta_pb_segments = self
            .rta_pb_splits
            .iter()
            .enumerate()
            .scan(TimeType::None, split_to_seg)
            .collect();
        self.igt_pb_segments = self
            .igt_pb_splits
            .iter()
            .enumerate()
            .scan(TimeType::None, split_to_seg)
            .collect();
    }
}

impl Default for Run {
    fn default() -> Self {
        Self {
            game_title: "".into(),
            category: "".into(),
            ingame_time: false,
            offset: TimeType::None,
            segment_names: vec!["".into()],
            rta_pb_splits: vec![TimeType::None],
            igt_pb_splits: vec![TimeType::None],
            rta_pb_segments: vec![TimeType::None],
            igt_pb_segments: vec![TimeType::None],
            rta_gold_segments: vec![TimeType::None],
            igt_gold_segments: vec![TimeType::None],
            rta_sum_segments: vec![(0, TimeType::None)],
            igt_sum_segments: vec![(0, TimeType::None)],
            rta_avg_segments: vec![TimeType::None],
            igt_avg_segments: vec![TimeType::None],
        }
    }
}

fn split_to_seg(last: &mut TimeType, (i, &time): (usize, &TimeType)) -> Option<TimeType> {
    let ret = Some(if !time.is_time() || (!last.is_time() && i != 0) {
        TimeType::None
    } else {
        time - *last
    });
    *last = time;
    ret
}

/// Ways a run can be invalid.
///
/// Potential reasons that even though a run can be deserialized, it is still
/// semantically invalid. Errors that pertain to a specific array element contain the
/// index.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Error)]
pub enum InvalidReason {
    /// A PB segment contains a negative value.
    #[error("PB split {0} ({1:?}) is negative!")]
    NegPbSplit(usize, TimingMethod),
    /// A gold segment contains a negative value.
    #[error("Gold segment {0} ({1:?}) is negative!")]
    NegGoldSeg(usize, TimingMethod),
    /// A sum time contains a negative value.
    #[error("Sum time {0} ({1:?}) is negative!")]
    NegSumTime(usize, TimingMethod),
    /// There are zero attempts for a non-zero sum time.
    #[error("Sum count {0} ({1:?}) is zero, but a time is given!")]
    ZeroSegCount(usize, TimingMethod),
    /// No segment names were given.
    #[error("No segments given!")]
    NoSegments,
    /// Mismatch in number of segment names and PB times.
    #[error("Wrong number of PB segments! ({0:?})")]
    WrongLenPb(TimingMethod),
    /// Mismatch in number of segment names and gold times.
    #[error("Wrong number of gold segments! ({0:?})")]
    WrongLenGold(TimingMethod),
    /// Mismatch in number of segment names and sum times.
    #[error("Wrong number of sum segments! ({0:?})")]
    WrongLenSum(TimingMethod),
    /// A split time was lower than the previous split time.
    #[error("Split time {0} ({1:?}) is before the previous split!")]
    NonIncreasingSplit(usize, TimingMethod),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn update_avg_calc() {
        let mut r = Run::default();
        r.add_segment_attempt(0, TimeType::Time(777), TimingMethod::Rta);
        assert_eq!(r.avg_segments(TimingMethod::Rta)[0], TimeType::Time(777));
        r.add_segment_attempt(0, TimeType::Time(9999), TimingMethod::Rta);
        assert_eq!(r.avg_segments(TimingMethod::Rta)[0], TimeType::Time(5388));
    }

    #[test]
    fn calc_all_avg() {
        let mut r = Run {
            rta_sum_segments: vec![(5, TimeType::Time(505050)), (4, TimeType::Time(770239))],
            ..Default::default()
        };
        r.calc_avgs();
        assert_eq!(
            r.avg_segments(TimingMethod::Rta),
            &vec![TimeType::Time(101010), TimeType::Time(192559)]
        );
    }

    #[test]
    fn verify_wrong_len_pb() {
        let r = Run {
            rta_pb_splits: vec![TimeType::Time(1234), TimeType::Time(-1234)],
            ..Default::default()
        };
        assert_eq!(
            r.verify(),
            Err(InvalidReason::WrongLenPb(TimingMethod::Rta))
        );
    }

    #[test]
    fn verify_wrong_len_gold() {
        let r = Run {
            rta_gold_segments: vec![TimeType::Time(1234), TimeType::Time(-1234)],
            ..Default::default()
        };
        assert_eq!(
            r.verify(),
            Err(InvalidReason::WrongLenGold(TimingMethod::Rta))
        );
    }

    #[test]
    fn verify_wrong_len_sum() {
        let r = Run {
            rta_sum_segments: vec![(0, TimeType::Time(1234)), (0, TimeType::Time(-1234))],
            ..Default::default()
        };
        assert_eq!(
            r.verify(),
            Err(InvalidReason::WrongLenSum(TimingMethod::Rta))
        );
    }

    #[test]
    fn verify_neg_pb_seg() {
        let r = Run {
            segment_names: vec!["".into(), "".into()],
            rta_pb_splits: vec![TimeType::Time(1234), TimeType::Time(-1234)],
            rta_gold_segments: vec![TimeType::Time(1234), TimeType::Time(-1234)],
            rta_sum_segments: vec![(0, TimeType::Time(1234)), (0, TimeType::Time(-1234))],
            ..Default::default()
        };
        assert_eq!(
            r.verify(),
            Err(InvalidReason::NegPbSplit(1, TimingMethod::Rta))
        );
    }

    #[test]
    fn verify_neg_gold_seg() {
        let r = Run {
            segment_names: vec!["".into(), "".into()],
            rta_pb_splits: vec![TimeType::Time(1234), TimeType::Time(1235)],
            rta_gold_segments: vec![TimeType::Time(1234), TimeType::Time(-1234)],
            rta_sum_segments: vec![(0, TimeType::Time(1234)), (0, TimeType::Time(-1234))],
            ..Default::default()
        };
        assert_eq!(
            r.verify(),
            Err(InvalidReason::NegGoldSeg(1, TimingMethod::Rta))
        );
    }

    #[test]
    fn verify_neg_sum_time() {
        let r = Run {
            segment_names: vec!["".into(), "".into()],
            rta_pb_splits: vec![TimeType::Time(1234), TimeType::Time(1235)],
            rta_gold_segments: vec![TimeType::Time(1234), TimeType::Time(1234)],
            rta_sum_segments: vec![(1, TimeType::Time(1234)), (1, TimeType::Time(-1234))],
            ..Default::default()
        };
        assert_eq!(
            r.verify(),
            Err(InvalidReason::NegSumTime(1, TimingMethod::Rta))
        );
    }

    #[test]
    fn verify_no_segments() {
        let r = Run {
            segment_names: vec![],
            ..Default::default()
        };
        assert_eq!(r.verify(), Err(InvalidReason::NoSegments));
    }

    #[test]
    fn verify_zero_seg_count() {
        let r = Run {
            segment_names: vec!["".into(), "".into()],
            rta_pb_splits: vec![TimeType::Time(1234), TimeType::Time(1235)],
            rta_gold_segments: vec![TimeType::Time(1234), TimeType::Time(1234)],
            rta_sum_segments: vec![(0, TimeType::Time(1234)), (0, TimeType::Time(1234))],
            ..Default::default()
        };
        assert_eq!(
            r.verify(),
            Err(InvalidReason::ZeroSegCount(0, TimingMethod::Rta))
        );
    }

    #[test]
    fn verify_non_increasing() {
        let mut r = Run {
            segment_names: vec!["".into(), "".into(), "".into()],
            rta_pb_splits: vec![
                TimeType::Time(1234),
                TimeType::Time(1000),
                TimeType::Time(2000),
            ],
            rta_gold_segments: vec![
                TimeType::Time(1234),
                TimeType::Time(1234),
                TimeType::Time(1234),
            ],
            rta_sum_segments: vec![
                (1, TimeType::Time(1234)),
                (1, TimeType::Time(1234)),
                (1, TimeType::Time(1234)),
            ],
            ..Default::default()
        };
        assert_eq!(
            r.verify(),
            Err(InvalidReason::NonIncreasingSplit(1, TimingMethod::Rta))
        );
        r.rta_pb_splits[1] = TimeType::None;
        assert!(r.verify().is_ok());
    }

    #[test]
    fn normalize() {
        let mut r = Run {
            offset: TimeType::Time(0),
            ..Default::default()
        };
        r.rta_pb_splits[0] = TimeType::Time(0);
        r.rta_gold_segments[0] = TimeType::Time(0);
        r.rta_sum_segments[0].1 = TimeType::Time(0);
        r.normalize();
        assert_eq!(r, Run::default());
    }
}