vsrg 0.3.0

Data structures for vertical scrolling rhythm games
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
use std::ops::{Add, Div, Sub};

/// Time measured in either clock time, or musical beat time.
///
/// # Remarks:
/// Events in a notes storage can be defined by either timing unit. Both untis disallow NaN values, but
/// allows infinity.
///
/// The conversion between two variants requires knowing the full list of tempo change over time,
/// which is described by [`super::TempoTrack`].
///
/// Arithmetic between two time values can only be done if they have the same unit. You must
/// first prove two [`Time`] values have the same unit first with [`Time::prove_same_unit`],
/// which returns [`SameUnitTime`].
///
/// Arithmetic can be done safely with [`SameUnitTime`] without panicking.
///
/// Addition and subtraction automatically produces positive infinity for INF - INF or -INF + INF
/// cases without panicking.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Time {
    Clock(ClockTime),
    Beat(BeatTime),
}

impl PartialOrd for Time {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        match (self, other) {
            (Time::Clock(x), Time::Clock(y)) => x.0.partial_cmp(&y.0),
            (Time::Beat(x), Time::Beat(y)) => x.0.partial_cmp(&y.0),
            _ => None,
        }
    }
}

/// [`Time`] value proven to have the same unit as other values sharing its lifetime id.
///
/// # Remarks
/// This type uses [`generativity`] trick. Values with the same 'id lifetime parameter are proven to
/// have same unit at compile time, which means arithmetic between values of the same
/// [`SameUnitTime`] type instance is guaranteed to be valid.
///
/// Arithmetic can be done safely with [`SameUnitTime`] without panicking.
/// Addition and subtraction automatically produces positive infinity for INF - INF or -INF + INF
/// cases without panicking.
///
/// # Examples
/// ```
/// use vsrg::rhythm::{Time, ClockTime};
/// use vsrg::generativity::make_guard;
///
/// let t1 = Time::Clock(ClockTime::ZERO);
/// let t2 = Time::Clock(ClockTime::ONE);
///
/// make_guard!(guard);
/// let (t1, t2) = Time::prove_same_unit(t1, t2, guard).expect("Both are clock time");
/// assert_eq!((t1 + t2).as_time(), t2.as_time());
/// ```
///
/// This would not compile, only units proven with the same [`generativity::Guard`] have the same
/// type.
/// ```compile_fail
/// use vsrg::rhythm::{Time, BeatTime, ClockTime};
/// use vsrg::generativity::make_guard;
///
/// let t1 = Time::Clock(ClockTime::ZERO);
/// let t2 = Time::Clock(ClockTime::ONE);
/// let t3 = Time::Beat(BeatTime::ZERO);
/// let t4 = Time::Beat(BeatTime::ONE);
///
/// make_guard!(g12);
/// let (t1, t2) = Time::prove_same_unit(t1, t2, g12).expect("Both are clock time");
/// make_guard!(g34);
/// let (t3, t4) = Time::prove_same_unit(t3, t4, g34).expect("Both are beat time");
///
/// // Invalid, because t1 and t3 are different instances of the same SameUnitTime type.
/// let this_is_invalid = t1 - t3;
/// ```
///
#[derive(Debug, Clone, Copy)]
pub struct SameUnitTime<'id>(Time, generativity::Id<'id>);

impl From<SameUnitTime<'_>> for Time {
    fn from(value: SameUnitTime<'_>) -> Self {
        value.0
    }
}

impl Time {
    /// Proves that two [`Time`] values have the same unit.
    ///
    /// See [`SameUnitTime`] for examples.
    pub fn prove_same_unit<'id>(
        self,
        other: Time,
        guard: generativity::Guard<'id>,
    ) -> Option<(SameUnitTime<'id>, SameUnitTime<'id>)> {
        let id = guard.into();
        match (self, other) {
            (Time::Clock(_), Time::Clock(_)) | (Time::Beat(_), Time::Beat(_)) => {
                Some((SameUnitTime(self, id), SameUnitTime(other, id)))
            }
            _ => None,
        }
    }
}

impl<'id> SameUnitTime<'id> {
    /// Proves that a raw [`Time`] value has the same unit with this value.
    ///
    /// This reflexively proves that the value has the same unit as other values with the same
    /// 'id life time parameter.
    pub fn prove_same_unit(self, other: Time) -> Option<SameUnitTime<'id>> {
        match (self.0, other) {
            (Time::Clock(_), Time::Clock(_)) | (Time::Beat(_), Time::Beat(_)) => {
                Some(SameUnitTime(other, self.1))
            }
            _ => None,
        }
    }

    /// Retrieves back a raw [`Time`] value.
    pub fn as_time(&self) -> Time {
        self.0
    }
}

impl<'id> Add for SameUnitTime<'id> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        match (self.0, rhs.0) {
            (Time::Clock(x), Time::Clock(y)) => {
                SameUnitTime(Time::Clock(ClockTime(non_nan_add(x.0, y.0))), self.1)
            }
            (Time::Beat(x), Time::Beat(y)) => {
                SameUnitTime(Time::Beat(BeatTime(non_nan_add(x.0, y.0))), self.1)
            }
            _ => unreachable!("Both are proven to have the same unit"),
        }
    }
}

impl<'id> Sub for SameUnitTime<'id> {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        match (self.0, rhs.0) {
            (Time::Clock(x), Time::Clock(y)) => {
                SameUnitTime(Time::Clock(ClockTime(non_nan_sub(x.0, y.0))), self.1)
            }
            (Time::Beat(x), Time::Beat(y)) => {
                SameUnitTime(Time::Beat(BeatTime(non_nan_sub(x.0, y.0))), self.1)
            }
            _ => unreachable!("Both are proven to have the same unit"),
        }
    }
}

impl<'id> Div for SameUnitTime<'id> {
    type Output = f64;

    fn div(self, rhs: Self) -> Self::Output {
        match (self.0, rhs.0) {
            (Time::Clock(x), Time::Clock(y)) => x.0 / y.0,
            (Time::Beat(x), Time::Beat(y)) => x.0 / y.0,
            _ => unreachable!("Both are proven to have the same unit"),
        }
    }
}

/// Time measured in clock time (seconds, miliseconds, etc.).
///
/// # Remarks:
/// NaN time values are disallowed, but infinities are allowed.
///
/// Addition and subtraction automatically produces positive infinity for INF - INF or -INF + INF
/// cases without panicking.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ClockTime(f64);

impl Eq for ClockTime {}

impl PartialOrd for ClockTime {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ClockTime {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // IMPORTANT: We do not use total_cmp because it defines -0.0 < 0.0.
        self.0.partial_cmp(&other.0).expect("Time can not be NaN")
    }
}

impl ClockTime {
    pub const ZERO: Self = Self(0.0);
    pub const ONE: Self = Self(1.0);
    pub const INF: Self = Self(f64::INFINITY);
    pub const NEG_INF: Self = Self(f64::NEG_INFINITY);

    /// Creates a clock time from seconds.
    ///
    /// Returns `None` only if `secs` is NaN.
    /// Infinite values are permitted.
    pub fn from_seconds(secs: f64) -> Option<Self> {
        (!secs.is_nan()).then_some(Self(secs))
    }

    /// Creates a clock time from miliseconds.
    ///
    /// Returns `None` only if `milis` is NaN.
    /// Infinite values are permitted.
    pub fn from_milis(milis: f64) -> Option<Self> {
        (!milis.is_nan()).then_some(Self(milis / 1000.0))
    }

    /// Creates a clock time from [`std::time::Duration`].
    ///
    /// This is infallible because [`std::time::Duration`] can not be NaN.
    pub const fn from_duration(dur: std::time::Duration) -> Self {
        Self(dur.as_secs_f64())
    }

    pub const fn seconds(self) -> f64 {
        self.0
    }

    /// Converts to a [`std::time::Duration`].
    pub fn duration(self) -> Result<std::time::Duration, std::time::TryFromFloatSecsError> {
        std::time::Duration::try_from_secs_f64(self.0)
    }

    /// Scale by a factor.
    ///
    /// Returns `None` if the resulting multiplcation produces is NaN (e.g. 0 × inf).
    pub fn scale(self, factor: f64) -> Option<Self> {
        checked_mul(self.0, factor).map(Self)
    }
}

impl Add for ClockTime {
    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        Self(non_nan_add(self.0, rhs.0))
    }
}

impl Sub for ClockTime {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self::Output {
        Self(non_nan_sub(self.0, rhs.0))
    }
}

impl Div for ClockTime {
    type Output = f64;
    fn div(self, rhs: Self) -> Self::Output {
        self.0 / rhs.0
    }
}

/// Time measured in beats.
///
/// # Remarks:
/// NaN time values are disallowed, but infinities are allowed.
///
/// The concrete [`ClockTime`] of a beat time depends on the exact tempo change throughout the
/// song. It can be calculated with a [`super::TempoTrack`].
///
/// Addition and subtraction automatically produces positive infinity for INF - INF or -INF + INF
/// cases without panicking.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BeatTime(f64);

impl Eq for BeatTime {}

impl PartialOrd for BeatTime {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for BeatTime {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // IMPORTANT: We do not use total_cmp because it defines -0.0 < 0.0
        self.0.partial_cmp(&other.0).expect("Time can not be NaN")
    }
}

impl BeatTime {
    pub const ZERO: Self = Self(0.0);
    pub const ONE: Self = Self(1.0);
    pub const INF: Self = Self(f64::INFINITY);

    /// Creates a beat time.
    ///
    /// Returns `None` only if `beats` is NaN.
    /// Infinite values are permitted.
    pub fn new(beats: f64) -> Option<Self> {
        (!beats.is_nan()).then_some(Self(beats))
    }

    pub fn beats(self) -> f64 {
        self.0
    }

    /// Scale by a factor.
    ///
    /// Returns `None` if the multiplication produces NaN (e.g. 0 × inf).
    pub fn scale(self, factor: f64) -> Option<Self> {
        checked_mul(self.0, factor).map(Self)
    }
}

impl Add for BeatTime {
    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        Self(non_nan_add(self.0, rhs.0))
    }
}

impl Sub for BeatTime {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self::Output {
        Self(non_nan_sub(self.0, rhs.0))
    }
}

impl Div for BeatTime {
    type Output = f64;
    fn div(self, rhs: Self) -> Self::Output {
        self.0 / rhs.0
    }
}

/// A vec of time values that have the same unit.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SameUnitTimeVec {
    Clock(Vec<ClockTime>),
    Beat(Vec<BeatTime>),
}

impl SameUnitTimeVec {
    /// Creates [`SameUnitTimeVec`] from a list of Time.
    ///
    /// Returns None if all values don't havethe same unit.
    pub fn try_from_iter(times: impl ExactSizeIterator<Item = Time>) -> Option<Self> {
        let len = times.len();
        let mut peekable = times.peekable();
        let Some(first) = peekable.peek().copied() else {
            return Some(Self::Clock(vec![]));
        };
        match first {
            Time::Clock(_) => {
                let mut v = Vec::with_capacity(len);
                for t in peekable {
                    let Time::Clock(t) = t else {
                        return None;
                    };
                    v.push(t);
                }
                Some(Self::Clock(v))
            }
            Time::Beat(_) => {
                let mut v = Vec::with_capacity(len);
                for t in peekable {
                    let Time::Beat(t) = t else {
                        return None;
                    };
                    v.push(t);
                }
                Some(Self::Beat(v))
            }
        }
    }

    /// Creates [`SameUnitTimeVec`] from a list of Time.
    ///
    /// Unlike [`Self::from_iter`], since all values are proven to have the same unit, this is always
    /// valid.
    pub fn from_proven_iter<'id>(times: impl ExactSizeIterator<Item = SameUnitTime<'id>>) -> Self {
        Self::try_from_iter(times.map(|x| x.into())).expect("Proven to be same unit")
    }

    /// Gets the length of the collection.
    pub fn len(&self) -> usize {
        match self {
            Self::Clock(times) => times.len(),
            Self::Beat(times) => times.len(),
        }
    }

    /// Gets the length of the collection.
    pub fn is_empty(&self) -> bool {
        match self {
            Self::Clock(times) => times.is_empty(),
            Self::Beat(times) => times.is_empty(),
        }
    }

    /// Index into the vec.
    ///
    /// Standard vec panic rules apply, the index must not be out of bound.
    pub fn index(&self, i: usize) -> Time {
        match self {
            Self::Clock(times) => Time::Clock(ClockTime(times[i].0)),
            Self::Beat(times) => Time::Beat(BeatTime(times[i].0)),
        }
    }

    /// Check if a raw [Time] value has matching unit.
    pub fn unit_match(&self, t: Time) -> bool {
        matches!(
            (self, t),
            (SameUnitTimeVec::Clock(_), Time::Clock(_)) | (SameUnitTimeVec::Beat(_), Time::Beat(_))
        )
    }

    /// Try to insert a raw [`Time`] value into the vec.
    ///
    /// # Errors
    /// Returns an error if the index is out of bound, or if the time has non matching unit.
    pub fn try_insert(&mut self, index: usize, time: Time) -> Result<(), SameUnitTimeVecEditError> {
        match (self, time) {
            (SameUnitTimeVec::Clock(list), Time::Clock(t)) => {
                if index > list.len() {
                    return Err(SameUnitTimeVecEditError::OutOfBound);
                }
                list.insert(index, t);
                Ok(())
            }
            (SameUnitTimeVec::Beat(list), Time::Beat(t)) => {
                if index > list.len() {
                    return Err(SameUnitTimeVecEditError::OutOfBound);
                }
                list.insert(index, t);
                Ok(())
            }
            _ => Err(SameUnitTimeVecEditError::UnitMismatch),
        }
    }

    /// Try to set a raw [`Time`] value in the vec.
    ///
    /// # Errors
    /// Returns an error if the index is out of bound, or if the time has non matching unit.
    pub fn try_set(&mut self, index: usize, time: Time) -> Result<(), SameUnitTimeVecEditError> {
        match (self, time) {
            (SameUnitTimeVec::Clock(list), Time::Clock(t)) => {
                if index >= list.len() {
                    return Err(SameUnitTimeVecEditError::OutOfBound);
                }
                list[index] = t;
                Ok(())
            }
            (SameUnitTimeVec::Beat(list), Time::Beat(t)) => {
                if index >= list.len() {
                    return Err(SameUnitTimeVecEditError::OutOfBound);
                }
                list[index] = t;
                Ok(())
            }
            _ => Err(SameUnitTimeVecEditError::UnitMismatch),
        }
    }

    /// Removes a value from the vec.
    pub fn remove(&mut self, index: usize) -> Time {
        match self {
            SameUnitTimeVec::Clock(list) => Time::Clock(list.remove(index)),
            SameUnitTimeVec::Beat(list) => Time::Beat(list.remove(index)),
        }
    }

    /// Swap two values in the vec.
    pub fn swap(&mut self, i: usize, j: usize) {
        match self {
            SameUnitTimeVec::Clock(list) => list.swap(i, j),
            SameUnitTimeVec::Beat(list) => list.swap(i, j),
        }
    }

    /// Constructs a wrapper that allows proving values to have the same unit.
    ///
    /// See [SameUnitTime] for more details.
    pub fn read_with_guard<'id>(
        &'id self,
        g: generativity::Guard<'id>,
    ) -> SameUnitTimeVecRead<'id> {
        SameUnitTimeVecRead(self, g.into())
    }
}

/// A wrapper of [`SameUnitTimeVec`] that allows proving [`Time`] values to have matching unit.
///
/// See [`SameUnitTime`] for more details.
pub struct SameUnitTimeVecRead<'id>(&'id SameUnitTimeVec, generativity::Id<'id>);

impl<'id> SameUnitTimeVecRead<'id> {
    /// Index a a value of the vec.
    ///
    /// All values returned by this method are guaranteed to have the same unit.
    ///
    /// # Panics
    /// Standard vec indexing rule apply, the index must not be out of bound.
    pub fn index(&self, i: usize) -> SameUnitTime<'id> {
        SameUnitTime(self.0.index(i), self.1)
    }

    /// Proves that a raw [`Time`] value has the same unit with this vec.
    ///
    /// This reflexively proves that the value has the same unit as other values with the same
    /// 'id life time parameter.
    pub fn prove_same_unit(self, other: Time) -> Option<SameUnitTime<'id>> {
        match (self.0, other) {
            (SameUnitTimeVec::Clock(_), Time::Clock(_))
            | (SameUnitTimeVec::Beat(_), Time::Beat(_)) => Some(SameUnitTime(other, self.1)),
            _ => None,
        }
    }
}

#[derive(Debug)]
pub enum SameUnitTimeVecEditError {
    OutOfBound,
    UnitMismatch,
}

impl std::fmt::Display for SameUnitTimeVecEditError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SameUnitTimeVecEditError::OutOfBound => {
                write!(f, "Indexing a vec with an index that is out of bound")
            }
            SameUnitTimeVecEditError::UnitMismatch => {
                write!(
                    f,
                    "Adding an Time to a SameUnitVec that does not have matching unit"
                )
            }
        }
    }
}

impl std::error::Error for SameUnitTimeVecEditError {}

impl Default for SameUnitTimeVec {
    fn default() -> Self {
        Self::Clock(vec![])
    }
}

/// Addition of two non NaN floats returning a non NaN value.
///
/// If the raw addition produces NaN (inf - inf cases), then it panics in debug mode, or returns
/// inf in release mode.
fn non_nan_add(a: f64, b: f64) -> f64 {
    let r = a + b;
    debug_assert!(!r.is_nan());
    if r.is_nan() { f64::INFINITY } else { r }
}

/// Subtraction of two non NaN floats returning a non NaN value.
///
/// If the raw subtraction produces NaN (inf - inf cases), then it panics in debug mode, or returns
/// inf in release mode.
fn non_nan_sub(a: f64, b: f64) -> f64 {
    let r = a - b;
    debug_assert!(!r.is_nan());
    if r.is_nan() { f64::INFINITY } else { r }
}

/// Returns `None` if the result is NaN (0 * inf).
fn checked_mul(a: f64, b: f64) -> Option<f64> {
    let r = a * b;
    (!r.is_nan()).then_some(r)
}