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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
#![no_std]

use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
use core::time;

/// Type to use for storing femtoseconds
///
/// In webassembly, using u128 results in exceedingly slow runtimes, so we use u64 instead
/// which is enough for 5 hours of simulation time.
#[cfg(not(target_arch = "wasm32"))]
pub type Femtos = u128;
#[cfg(target_arch = "wasm32")]
pub type Femtos = u64;

/// Represents a duration of time in femtoseconds
///
/// The `Duration` type is used to represent lengths of time and is
/// intentionally similar to `std::time::Duration`, but which records
/// time as femtoseconds to keep accurancy when dealing with partial
/// nanosecond clock divisons.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Duration {
    femtos: Femtos,
}

impl Duration {
    /// A duration of zero (0) time
    pub const ZERO: Self = Self::from_femtos(0);

    /// A duration of the maximum possible length in femtoseconds (`Femtos::MAX`)
    ///
    /// This will be equivalent to either u64::MAX or u128::MAX femtoseconds
    pub const MAX: Self = Self::from_femtos(Femtos::MAX);

    /// The number of femtoseconds in 1 second as `Femtos`
    pub const FEMTOS_PER_SEC: Femtos = 1_000_000_000_000_000;

    /// The number of femtoseconds in 1 millisecond as `Femtos`
    pub const FEMTOS_PER_MILLISEC: Femtos = 1_000_000_000_000;

    /// The number of femtoseconds in 1 microsecond as `Femtos`
    pub const FEMTOS_PER_MICROSEC: Femtos = 1_000_000_000;

    /// The number of femtoseconds in 1 nanosecond as `Femtos`
    pub const FEMTOS_PER_NANOSEC: Femtos = 1_000_000;

    /// The number of femtoseconds in 1 picosecond as `Femtos`
    pub const FEMTOS_PER_PICOSEC: Femtos = 1_000;

    /// Creates a new `Duration` from the specified number of seconds
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_secs(123);
    ///
    /// assert_eq!(123, duration.as_secs());
    /// ```
    #[inline]
    pub const fn from_secs(secs: u64) -> Self {
        Self {
            femtos: secs as Femtos * Self::FEMTOS_PER_SEC,
        }
    }

    /// Creates a new `Duration` from the specified number of milliseconds
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_millis(123);
    ///
    /// assert_eq!(123, duration.as_millis());
    /// ```
    #[inline]
    pub const fn from_millis(millisecs: u64) -> Self {
        Self {
            femtos: millisecs as Femtos * Self::FEMTOS_PER_MILLISEC,
        }
    }

    /// Creates a new `Duration` from the specified number of microseconds
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_micros(123);
    ///
    /// assert_eq!(123, duration.as_micros());
    /// ```
    #[inline]
    pub const fn from_micros(microsecs: u64) -> Self {
        Self {
            femtos: microsecs as Femtos * Self::FEMTOS_PER_MICROSEC,
        }
    }

    /// Creates a new `Duration` from the specified number of nanoseconds
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_nanos(123);
    ///
    /// assert_eq!(123, duration.as_nanos());
    /// ```
    #[inline]
    pub const fn from_nanos(nanosecs: u64) -> Self {
        Self {
            femtos: nanosecs as Femtos * Self::FEMTOS_PER_NANOSEC,
        }
    }

    /// Creates a new `Duration` from the specified number of picoseconds
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_picos(123);
    ///
    /// assert_eq!(123, duration.as_picos());
    /// ```
    #[inline]
    pub const fn from_picos(picosecs: u128) -> Self {
        Self {
            femtos: picosecs as Femtos * Self::FEMTOS_PER_PICOSEC,
        }
    }

    /// Creates a new `Duration` from the specified number of femtoseconds
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_femtos(123);
    ///
    /// assert_eq!(123, duration.as_femtos());
    /// ```
    #[inline]
    pub const fn from_femtos(femtos: Femtos) -> Self {
        Self { femtos }
    }

    /// Returns the number of _whole_ seconds contained by this `Duration`.
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_femtos(123_465_789_012_345_678);
    /// assert_eq!(duration.as_secs(), 123);
    /// ```
    #[inline]
    pub const fn as_secs(self) -> u64 {
        (self.femtos / Self::FEMTOS_PER_SEC) as u64
    }

    /// Returns the number of _whole_ milliseconds contained by this `Duration`.
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_femtos(123_465_789_012_345_678);
    /// assert_eq!(duration.as_millis(), 123_465);
    /// ```
    #[inline]
    pub const fn as_millis(self) -> u64 {
        (self.femtos / Self::FEMTOS_PER_MILLISEC) as u64
    }

    /// Returns the number of _whole_ microseconds contained by this `Duration`.
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_femtos(123_465_789_012_345_678);
    /// assert_eq!(duration.as_micros(), 123_465_789);
    /// ```
    #[inline]
    pub const fn as_micros(self) -> u64 {
        (self.femtos / Self::FEMTOS_PER_MICROSEC) as u64
    }

    /// Returns the number of _whole_ nanoseconds contained by this `Duration`.
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_femtos(123_465_789_012_345_678);
    /// assert_eq!(duration.as_nanos(), 123_465_789_012);
    /// ```
    #[inline]
    pub const fn as_nanos(self) -> u64 {
        (self.femtos / Self::FEMTOS_PER_NANOSEC) as u64
    }

    /// Returns the number of _whole_ picoseconds contained by this `Duration`.
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_femtos(123_465_789_012_345_678);
    /// assert_eq!(duration.as_picos(), 123_465_789_012_345);
    /// ```
    #[inline]
    #[allow(clippy::unnecessary_cast)]
    pub const fn as_picos(self) -> u128 {
        (self.femtos / Self::FEMTOS_PER_PICOSEC) as u128
    }

    /// Returns the number of _whole_ femtoseconds contained by this `Duration`.
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// let duration = Duration::from_femtos(123_465_789_012_345_678);
    /// assert_eq!(duration.as_femtos(), 123_465_789_012_345_678);
    /// ```
    #[inline]
    pub const fn as_femtos(self) -> Femtos {
        self.femtos
    }

    /// Checked `Duration` addition.  Computes `self + rhs`, returning [`None`]
    /// if an overflow occured.
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::{Duration, Femtos};
    ///
    /// assert_eq!(Duration::from_secs(1).checked_add(Duration::from_secs(1)), Some(Duration::from_secs(2)));
    /// assert_eq!(Duration::from_secs(1).checked_add(Duration::from_femtos(Femtos::MAX)), None);
    /// ```
    #[inline]
    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
        match self.femtos.checked_add(rhs.femtos) {
            Some(femtos) => Some(Self::from_femtos(femtos)),
            None => None,
        }
    }

    /// Checked `Duration` subtraction.  Computes `self - rhs`, returning [`None`]
    /// if an overflow occured.
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Duration;
    ///
    /// assert_eq!(Duration::from_secs(1).checked_sub(Duration::from_secs(1)), Some(Duration::ZERO));
    /// assert_eq!(Duration::from_femtos(1).checked_sub(Duration::from_femtos(2)), None);
    /// ```
    #[inline]
    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
        match self.femtos.checked_sub(rhs.femtos) {
            Some(femtos) => Some(Self::from_femtos(femtos)),
            None => None,
        }
    }
}

impl Add for Duration {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        self.checked_add(rhs)
            .expect("clock duration overflow during addition")
    }
}

impl AddAssign for Duration {
    fn add_assign(&mut self, rhs: Self) {
        *self = *self + rhs;
    }
}

impl Sub for Duration {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        self.checked_sub(rhs)
            .expect("clock duration overflow during subtraction")
    }
}

impl SubAssign for Duration {
    fn sub_assign(&mut self, rhs: Self) {
        *self = *self - rhs;
    }
}

impl Mul<u32> for Duration {
    type Output = Self;

    fn mul(self, rhs: u32) -> Self::Output {
        Self::from_femtos(self.femtos * rhs as Femtos)
    }
}

impl MulAssign<u32> for Duration {
    fn mul_assign(&mut self, rhs: u32) {
        *self = Self::from_femtos(self.femtos * rhs as Femtos);
    }
}

impl Mul<u64> for Duration {
    type Output = Self;

    fn mul(self, rhs: u64) -> Self::Output {
        Self::from_femtos(self.femtos * rhs as Femtos)
    }
}

impl MulAssign<u64> for Duration {
    fn mul_assign(&mut self, rhs: u64) {
        *self = Self::from_femtos(self.femtos * rhs as Femtos);
    }
}

impl Div<u32> for Duration {
    type Output = Self;

    fn div(self, rhs: u32) -> Self::Output {
        Self::from_femtos(self.femtos / rhs as Femtos)
    }
}

impl DivAssign<u32> for Duration {
    fn div_assign(&mut self, rhs: u32) {
        *self = Self::from_femtos(self.femtos / rhs as Femtos);
    }
}

impl Div<u64> for Duration {
    type Output = Self;

    fn div(self, rhs: u64) -> Self::Output {
        Self::from_femtos(self.femtos / rhs as Femtos)
    }
}

impl DivAssign<u64> for Duration {
    fn div_assign(&mut self, rhs: u64) {
        *self = Self::from_femtos(self.femtos / rhs as Femtos);
    }
}

impl Div<Duration> for Duration {
    type Output = u64;

    fn div(self, rhs: Duration) -> Self::Output {
        (self.femtos / rhs.femtos) as u64
    }
}

impl From<Duration> for time::Duration {
    fn from(value: Duration) -> Self {
        time::Duration::from_nanos(value.as_nanos())
    }
}

impl From<time::Duration> for Duration {
    fn from(value: time::Duration) -> Self {
        Duration::from_nanos(value.as_nanos() as u64)
    }
}

/// Represents time from the start of the simulation
///
/// `Instant` is for representing the current running clock.  It uses a
/// duration to represent the time from simulation start, and is monotonic.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Instant(Duration);

impl Instant {
    /// An `Instant` representing the start of time (t = 0)
    pub const START: Self = Self(Duration::ZERO);
    /// An `Instant` representing the greatest possible time (t = `Femtos::MAX`)
    pub const FOREVER: Self = Self(Duration::MAX);

    /// Returns a `Duration` equivalent to the amount of time elapsed since the earliest
    /// possible time (t = 0).
    #[inline]
    pub const fn as_duration(self) -> Duration {
        self.0
    }

    /// Returns the `Duration` that has elapsed between this `Instant` and `other`.
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::{Instant, Duration};
    ///
    /// let now = Instant::START + Duration::from_secs(1);
    /// assert_eq!(now.duration_since(Instant::START), Duration::from_secs(1));
    /// ```
    #[inline]
    pub fn duration_since(self, other: Self) -> Duration {
        self.0 - other.0
    }

    /// Checked `Instant` addition.  Computes `self + duration`, returning [`None`]
    /// if an overflow occured.
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::{Instant, Duration, Femtos};
    ///
    /// assert_eq!(
    ///     Instant::START.checked_add(Duration::from_secs(1)).map(|i| i.as_duration()),
    ///     Some(Duration::from_secs(1))
    /// );
    /// assert_eq!(Instant::FOREVER.checked_add(Duration::from_femtos(1)), None);
    /// ```
    #[inline]
    pub const fn checked_add(self, duration: Duration) -> Option<Self> {
        match self.0.checked_add(duration) {
            Some(duration) => Some(Self(duration)),
            None => None,
        }
    }

    /// Checked `Instant` subtraction.  Computes `self - duration`, returning [`None`]
    /// if an overflow occured.
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::{Instant, Duration, Femtos};
    ///
    /// assert_eq!(
    ///     Instant::FOREVER.checked_sub(Duration::from_femtos(1)).map(|i| i.as_duration()),
    ///     Some(Duration::from_femtos(Femtos::MAX - 1))
    /// );
    /// assert_eq!(Instant::START.checked_sub(Duration::from_secs(1)), None);
    /// ```
    #[inline]
    pub const fn checked_sub(self, duration: Duration) -> Option<Self> {
        match self.0.checked_sub(duration) {
            Some(duration) => Some(Self(duration)),
            None => None,
        }
    }
}

impl Add<Duration> for Instant {
    type Output = Self;

    fn add(self, rhs: Duration) -> Self::Output {
        Self(self.0.add(rhs))
    }
}

impl AddAssign<Duration> for Instant {
    fn add_assign(&mut self, rhs: Duration) {
        *self = Self(self.0.add(rhs));
    }
}

/// Represents a frequency in Hz
///
/// Clocks are usually given as a frequency, but durations are needed when dealing with clocks
/// and clock durations.  This type makes it easier to create a clock of a given frequency and
/// convert it to a `Duration`
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Frequency {
    hertz: u32,
}

impl Frequency {
    /// Creates a new `Frequency` from the specified number of hertz
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Frequency;
    ///
    /// Frequency::from_hz(123);
    /// ```
    #[inline]
    pub const fn from_hz(hertz: u32) -> Self {
        Self { hertz }
    }

    /// Creates a new `Frequency` from the specified number of kilohertz
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Frequency;
    ///
    /// Frequency::from_khz(123);
    /// ```
    #[inline]
    pub const fn from_khz(khz: u32) -> Self {
        Self { hertz: khz * 1_000 }
    }

    /// Creates a new `Frequency` from the specified number of megahertz
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::Frequency;
    ///
    /// Frequency::from_mhz(123);
    /// ```
    #[inline]
    pub const fn from_mhz(mhz: u32) -> Self {
        Self {
            hertz: mhz * 1_000_000,
        }
    }

    /// Returns the frequency is hertz
    #[inline]
    pub const fn as_hz(self) -> u32 {
        self.hertz
    }

    /// Returns the frequency is kilohertz
    #[inline]
    pub const fn as_khz(self) -> u32 {
        self.hertz / 1_000
    }

    /// Returns the frequency is megahertz
    #[inline]
    pub const fn as_mhz(self) -> u32 {
        self.hertz / 1_000_000
    }

    /// Returns the `Duration` equivalent to the time period between cycles of
    /// the given `Frequency`
    ///
    /// # Examples
    ///
    /// ```
    /// use femtos::{Duration, Frequency};
    ///
    /// assert_eq!(Frequency::from_hz(1).period_duration(), Duration::from_secs(1));
    /// ```
    #[inline]
    pub const fn period_duration(self) -> Duration {
        Duration::from_femtos(Duration::FEMTOS_PER_SEC / self.hertz as Femtos)
    }
}

impl Mul<u32> for Frequency {
    type Output = Self;

    fn mul(self, rhs: u32) -> Self::Output {
        Self::from_hz(self.hertz * rhs)
    }
}

impl MulAssign<u32> for Frequency {
    fn mul_assign(&mut self, rhs: u32) {
        *self = Self::from_hz(self.hertz * rhs);
    }
}

impl Div<u32> for Frequency {
    type Output = Self;

    fn div(self, rhs: u32) -> Self::Output {
        Self::from_hz(self.hertz / rhs)
    }
}

impl DivAssign<u32> for Frequency {
    fn div_assign(&mut self, rhs: u32) {
        *self = Self::from_hz(self.hertz / rhs);
    }
}