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
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ops::{Add, Sub};
pub type CycleDelta = i64;
pub type Cycles = u64;
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Cycle(i64);
impl fmt::Display for Cycle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Add<CycleDelta> for Cycle {
type Output = Cycle;
fn add(self, other: CycleDelta) -> Cycle {
let c = self.0.checked_add(other).expect("Cycle count overflow");
assert!(c >= 0, "Cycle count overflow");
Cycle(c)
}
}
impl Sub<CycleDelta> for Cycle {
type Output = Cycle;
fn sub(self, other: CycleDelta) -> Cycle {
let c = self.0.checked_sub(other).expect("Cycle count overflow");
assert!(c >= 0, "Cycle count overflow");
Cycle(c)
}
}
impl Sub for Cycle {
type Output = CycleDelta;
fn sub(self, other: Cycle) -> CycleDelta {
self.0.checked_sub(other.0).expect("Cycle count overflow")
}
}
impl Cycle {
pub fn t_zero() -> Cycle {
Cycle(0)
}
pub fn advance(self, cycles: Cycles) -> Cycle {
assert!(cycles <= (std::i64::MAX as u64), "Cycle count overflow");
Cycle(
self.0
.checked_add(cycles as i64)
.expect("Cycle count overflow"),
)
}
}
impl Into<u64> for Cycle {
fn into(self) -> u64 {
assert!(self.0 >= 0, "Cycle count negative");
self.0 as u64
}
}
impl Into<i64> for Cycle {
fn into(self) -> i64 {
self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn zero() {
let c = Cycle::t_zero();
assert_eq!(c, Cycle(0i64));
}
#[test]
fn advance() {
let c = Cycle::t_zero();
let c = c.advance(1234u64);
assert_eq!(c, Cycle(1234));
let c = c.advance(1u64);
assert_eq!(c, Cycle(1235));
}
#[test]
#[should_panic]
fn overflow() {
let c = Cycle::t_zero();
c.advance(std::u64::MAX);
}
#[test]
#[should_panic]
fn convert_negative() {
let a = 18_446_744_073_709_551_574u64;
let c = Cycle(-42);
let c: u64 = c.into();
assert_eq!(a, c);
}
#[test]
fn convert() {
let a = 1234u64;
let c = Cycle(1234);
let c: u64 = c.into();
assert_eq!(a, c);
let a = 1234i64;
let c = Cycle(1234);
let c: i64 = c.into();
assert_eq!(a, c);
}
#[allow(clippy::eq_op)]
#[test]
fn ops() {
let a = Cycle(21);
let b: CycleDelta = 21;
let c: CycleDelta = -2;
assert_eq!(a + b, Cycle(42));
assert_eq!(a - b, Cycle(0));
assert_eq!(a + c, Cycle(19));
assert_eq!(a - c, Cycle(23));
assert_eq!(a - a, 0 as CycleDelta);
}
}