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
//! An instant of time

use crate::{
    duration::{self, Duration},
    fixed_point::FixedPoint,
    ConversionError,
};
use core::{cmp::Ordering, convert::TryFrom, ops};
use num::traits::{WrappingAdd, WrappingSub};

/// Represents an instant of time relative to a specific [`Clock`](clock/trait.Clock.html)
///
/// # Example
///
/// Typically an `Instant` will be obtained from a [`Clock`](clock/trait.Clock.html)
///
/// ```rust
/// # use embedded_time::{Fraction, traits::*, Instant};
/// # #[derive(Debug)]
/// # struct SomeClock;
/// # impl embedded_time::Clock for SomeClock {
/// #     type T = u32;
/// #     type ImplError = ();
/// #     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
/// #     fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {Ok(Instant::<Self>::new(23))}
/// # }
/// let some_clock = SomeClock;
/// let some_instant = some_clock.try_now().unwrap();
/// ```
///
/// However, an `Instant` can also be constructed directly. In this case the constructed `Instant`
/// is `23 * SomeClock::SCALING_FACTOR` seconds since the clock's epoch
///
/// ```rust,no_run
/// # use embedded_time::{Fraction, Instant};
/// # #[derive(Debug)]
/// # struct SomeClock;
/// # impl embedded_time::Clock for SomeClock {
/// #     type T = u32;
/// #     type ImplError = ();
/// #     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
/// #     fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
/// # }
/// Instant::<SomeClock>::new(23);
/// ```
#[derive(Debug)]
pub struct Instant<Clock: crate::Clock> {
    ticks: Clock::T,
}

impl<Clock: crate::Clock> Instant<Clock> {
    /// Construct a new Instant from the provided [`Clock`](clock/trait.Clock.html)
    pub fn new(ticks: Clock::T) -> Self {
        Self { ticks }
    }

    /// Returns the [`Duration`] since the given `Instant`
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use embedded_time::{Fraction, duration::units::*, rate::units::*, Instant, ConversionError, duration};
    /// # use core::convert::TryInto;
    /// # #[derive(Debug)]
    /// #
    /// struct Clock;
    /// impl embedded_time::Clock for Clock {
    ///     type T = u32;
    /// #   type ImplError = ();
    ///     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
    ///     // ...
    ///
    /// # fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
    /// }
    ///
    /// assert_eq!(Instant::<Clock>::new(5).duration_since(&Instant::<Clock>::new(3)).unwrap().try_into(),
    ///     Ok(Microseconds(2_000_u64)));
    ///
    /// assert_eq!(Instant::<Clock>::new(3).duration_since(&Instant::<Clock>::new(5)),
    ///     Err(ConversionError::NegDuration));
    /// ```
    ///
    /// # Errors
    ///
    /// - [`ConversionError::NegDuration`] : `Instant` is in the future
    // TODO: add example
    ///
    /// - [`ConversionError::Overflow`] : problem coverting to the desired [`Duration`]
    // TODO: add example
    ///
    /// - [`ConversionError::ConversionFailure`] : problem coverting to the desired [`Duration`]
    // TODO: add example
    pub fn duration_since(
        &self,
        other: &Self,
    ) -> Result<duration::Generic<Clock::T>, ConversionError> {
        if self >= other {
            Ok(duration::Generic::new(
                self.ticks.wrapping_sub(&other.ticks),
                Clock::SCALING_FACTOR,
            ))
        } else {
            Err(ConversionError::NegDuration)
        }
    }

    /// Returns the [`Duration`] until the given `Instant`
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use embedded_time::{Fraction, duration::units::*, rate::units::*, Instant, ConversionError};
    /// # #[derive(Debug)]
    /// #
    /// struct Clock;
    /// impl embedded_time::Clock for Clock {
    ///     type T = u32;
    /// # type ImplError = ();
    ///     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
    ///     // ...
    /// # fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
    /// }
    ///
    /// assert_eq!(Instant::<Clock>::new(5).duration_until::<Microseconds<u64>>(&Instant::<Clock>::new(7)),
    ///     Ok(Microseconds(2_000_u64)));
    ///
    /// assert_eq!(Instant::<Clock>::new(7).duration_until::<Microseconds<u64>>(&Instant::<Clock>::new(5)),
    ///     Err(ConversionError::NegDuration));
    /// ```
    ///
    /// # Errors
    ///
    /// - [`ConversionError::NegDuration`] : `Instant` is in the past
    // TODO: add example
    ///
    /// - [`ConversionError::Overflow`] : problem coverting to the desired [`Duration`]
    // TODO: add example
    ///
    /// - [`ConversionError::ConversionFailure`] : problem coverting to the desired [`Duration`]
    // TODO: add example
    pub fn duration_until<Dur: Duration>(&self, other: &Self) -> Result<Dur, ConversionError>
    where
        Dur: FixedPoint + TryFrom<duration::Generic<Clock::T>, Error = ConversionError>,
        Dur::T: TryFrom<Clock::T>,
    {
        if self <= other {
            Dur::try_from(duration::Generic::new(
                other.ticks.wrapping_sub(&self.ticks),
                Clock::SCALING_FACTOR,
            ))
        } else {
            Err(ConversionError::NegDuration)
        }
    }

    /// Returns the [`Duration`] (in the provided units) since the beginning of time (the
    /// [`Clock`](clock/trait.Clock.html)'s 0)
    ///
    /// If it is a _wrapping_ clock, the result is meaningless.
    pub fn duration_since_epoch(&self) -> duration::Generic<Clock::T> {
        self.duration_since(&Self {
            ticks: Clock::T::from(0),
        })
        .unwrap()
    }

    /// Add a [`Duration`] to an `Instant` resulting in a new, later `Instant`
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use embedded_time::{Fraction, duration::units::*, rate::units::*, Instant};
    /// # #[derive(Debug)]
    /// struct Clock;
    /// impl embedded_time::Clock for Clock {
    ///     type T = u32;
    /// # type ImplError = ();
    ///     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
    ///     // ...
    /// # fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
    /// }
    ///
    /// assert_eq!(Instant::<Clock>::new(800) + Milliseconds(700_u32), Instant::<Clock>::new(1_500_u32));
    /// assert_eq!(Instant::<Clock>::new(5_000) + Milliseconds(700_u64), Instant::<Clock>::new(5_700_u32));
    ///
    /// // maximum duration allowed
    /// assert_eq!(Instant::<Clock>::new(0) + Milliseconds(u32::MAX / 2),
    /// Instant::<Clock>::new(u32::MAX/2));
    /// ```
    ///
    /// # Errors
    ///
    /// [`ConversionError::Overflow`] : The duration is more than half the wrap-around period of the
    /// clock
    ///
    /// ```rust
    /// # use embedded_time::{Fraction, duration::units::*, rate::units::*, Instant, ConversionError};
    /// # #[derive(Debug)]
    /// struct Clock;
    /// impl embedded_time::Clock for Clock {
    ///     type T = u32;
    /// # type ImplError = ();
    ///     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
    ///     // ...
    /// # fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
    /// }
    ///
    /// assert_eq!(Instant::<Clock>::new(0).checked_add_duration(Milliseconds(u32::MAX/2 + 1)),
    ///     Err(ConversionError::Overflow));
    /// ```
    pub fn checked_add_duration<Dur: Duration>(self, duration: Dur) -> Result<Self, ConversionError>
    where
        Dur: FixedPoint,
        Clock::T: TryFrom<Dur::T>,
    {
        let add_ticks: Clock::T = duration.into_ticks(Clock::SCALING_FACTOR)?;
        if add_ticks <= (<Clock::T as num::Bounded>::max_value() / 2.into()) {
            Ok(Self {
                ticks: self.ticks.wrapping_add(&add_ticks),
            })
        } else {
            Err(ConversionError::Overflow)
        }
    }

    /// Subtracts a [`Duration`] from an `Instant` resulting in a new, earlier `Instant`
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use embedded_time::{Fraction, duration::units::*, rate::units::*, Instant};
    /// # #[derive(Debug)]
    /// struct Clock;
    /// impl embedded_time::Clock for Clock {
    ///     type T = u32;
    /// # type ImplError = ();
    ///     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
    ///     // ...
    /// # fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
    /// }
    ///
    /// assert_eq!(Instant::<Clock>::new(800) - Milliseconds(700_u32), Instant::<Clock>::new(100));
    /// assert_eq!(Instant::<Clock>::new(5_000) - Milliseconds(700_u64), Instant::<Clock>::new(4_300));
    ///
    /// // maximum duration allowed
    /// assert_eq!(Instant::<Clock>::new(u32::MAX) - Milliseconds(i32::MAX as u32),
    /// Instant::<Clock>::new(u32::MAX/2 + 1));
    /// ```
    ///
    /// # Errors
    ///
    /// [`ConversionError::Overflow`] : The duration is more than half the wrap-around period of the
    /// clock
    ///
    /// ```rust
    /// # use embedded_time::{Fraction, duration::units::*, rate::units::*, Instant, ConversionError};
    /// # #[derive(Debug)]
    /// struct Clock;
    /// impl embedded_time::Clock for Clock {
    ///     type T = u32;
    /// # type ImplError = ();
    ///     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
    ///     // ...
    /// # fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
    /// }
    ///
    /// assert_eq!(Instant::<Clock>::new(u32::MAX).checked_sub_duration(Milliseconds(u32::MAX/2 + 1)),
    ///     Err(ConversionError::Overflow));
    /// ```
    pub fn checked_sub_duration<Dur: Duration>(self, duration: Dur) -> Result<Self, ConversionError>
    where
        Dur: FixedPoint,
        Clock::T: TryFrom<Dur::T>,
    {
        let sub_ticks: Clock::T = duration.into_ticks(Clock::SCALING_FACTOR)?;
        if sub_ticks <= (<Clock::T as num::Bounded>::max_value() / 2.into()) {
            Ok(Self {
                ticks: self.ticks.wrapping_sub(&sub_ticks),
            })
        } else {
            Err(ConversionError::Overflow)
        }
    }
}

impl<Clock: crate::Clock> Copy for Instant<Clock> {}

impl<Clock: crate::Clock> Clone for Instant<Clock> {
    fn clone(&self) -> Self {
        Self { ticks: self.ticks }
    }
}

impl<Clock: crate::Clock> PartialEq for Instant<Clock> {
    fn eq(&self, other: &Self) -> bool {
        self.ticks == other.ticks
    }
}

impl<Clock: crate::Clock> Eq for Instant<Clock> {}

impl<Clock: crate::Clock> PartialOrd for Instant<Clock> {
    /// Calculates the difference between two `Instant`s resulting in a [`Duration`]
    ///
    /// ```rust
    /// # use embedded_time::{Fraction, duration::units::*, rate::units::*, Instant};
    /// # #[derive(Debug)]
    /// struct Clock;
    /// impl embedded_time::Clock for Clock {
    ///     type T = u32;
    /// # type ImplError = ();
    ///     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
    ///     // ...
    /// # fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
    /// }
    ///
    /// assert!(Instant::<Clock>::new(5) > Instant::<Clock>::new(3));
    /// assert!(Instant::<Clock>::new(5) == Instant::<Clock>::new(5));
    /// assert!(Instant::<Clock>::new(u32::MAX) < Instant::<Clock>::new(u32::MIN));
    /// ```
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(&other))
    }
}

impl<Clock: crate::Clock> Ord for Instant<Clock> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.ticks
            .wrapping_sub(&other.ticks)
            .cmp(&(<Clock::T as num::Bounded>::max_value() / 2.into()))
            .reverse()
    }
}

impl<Clock: crate::Clock, Dur: Duration> ops::Add<Dur> for Instant<Clock>
where
    Clock::T: TryFrom<Dur::T>,
    Dur: FixedPoint,
{
    type Output = Self;

    /// Add a [`Duration`] to an `Instant` resulting in a new, later `Instant`
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use embedded_time::{Fraction, duration::units::*, rate::units::*, Instant};
    /// # #[derive(Debug)]
    /// struct Clock;
    /// impl embedded_time::Clock for Clock {
    ///     type T = u32;
    /// # type ImplError = ();
    ///     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
    ///     // ...
    /// # fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
    /// }
    ///
    /// assert_eq!(Instant::<Clock>::new(1) + Seconds(3_u32),
    ///     Instant::<Clock>::new(3_001));
    /// assert_eq!(Instant::<Clock>::new(1) + Milliseconds(700_u32),
    ///     Instant::<Clock>::new(701));
    /// assert_eq!(Instant::<Clock>::new(1) + Milliseconds(700_u64),
    ///     Instant::<Clock>::new(701));
    ///
    /// // maximum duration allowed
    /// assert_eq!(Instant::<Clock>::new(0) + Milliseconds(i32::MAX as u32),
    ///    Instant::<Clock>::new(u32::MAX/2));
    /// ```
    ///
    /// # Panics
    ///
    /// Virtually the same reason the integer operation would panic. Namely, if the
    /// result overflows the type. Specifically, if the duration is more than half
    /// the wrap-around period of the clock.
    ///
    /// ```rust,should_panic
    /// # use embedded_time::{Fraction, duration::units::*, rate::units::*, Instant};
    /// # #[derive(Debug)]
    /// struct Clock;
    /// impl embedded_time::Clock for Clock {
    ///     type T = u32;
    /// # type ImplError = ();
    ///     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
    ///     // ...
    /// # fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
    /// }
    ///
    /// Instant::<Clock>::new(0) + Milliseconds(u32::MAX/2 + 1);
    /// ```
    fn add(self, rhs: Dur) -> Self::Output {
        self.checked_add_duration(rhs).unwrap()
    }
}

impl<Clock: crate::Clock, Dur: Duration> ops::Sub<Dur> for Instant<Clock>
where
    Clock::T: TryFrom<Dur::T>,
    Dur: FixedPoint,
{
    type Output = Self;

    /// Subtract a [`Duration`] from an `Instant` resulting in a new, earlier `Instant`
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use embedded_time::{Fraction, duration::units::*, rate::units::*, Instant};
    /// # #[derive(Debug)]
    /// struct Clock;
    /// impl embedded_time::Clock for Clock {
    ///     type T = u32;
    /// # type ImplError = ();
    ///     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
    ///     // ...
    /// # fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
    /// }
    ///
    /// assert_eq!(Instant::<Clock>::new(5_001) - Seconds(3_u32),
    ///     Instant::<Clock>::new(2_001));
    /// assert_eq!(Instant::<Clock>::new(800) - Milliseconds(700_u32),
    ///     Instant::<Clock>::new(100));
    /// assert_eq!(Instant::<Clock>::new(5_000) - Milliseconds(700_u64),
    ///     Instant::<Clock>::new(4_300));
    ///
    /// // maximum duration allowed
    /// assert_eq!(Instant::<Clock>::new(u32::MAX) - Milliseconds(i32::MAX as u32),
    ///     Instant::<Clock>::new(u32::MAX/2 + 1));
    /// ```
    ///
    /// # Panics
    ///
    /// Virtually the same reason the integer operation would panic. Namely, if the
    /// result overflows the type. Specifically, if the duration is more than half
    /// the wrap-around period of the clock.
    ///
    /// ```rust,should_panic
    /// # use embedded_time::{Fraction, duration::units::*, rate::units::*, Instant};
    /// # #[derive(Debug)]
    /// struct Clock;
    /// impl embedded_time::Clock for Clock {
    ///     type T = u32;
    /// # type ImplError = ();
    ///     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);
    ///     // ...
    /// # fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error<Self::ImplError>> {unimplemented!()}
    /// }
    ///
    /// Instant::<Clock>::new(u32::MAX) - Milliseconds(u32::MAX/2 + 1);
    /// ```
    fn sub(self, rhs: Dur) -> Self::Output {
        self.checked_sub_duration(rhs).unwrap()
    }
}

#[cfg(test)]
mod tests {
    use crate::{self as time, duration, ConversionError, Fraction, Instant};

    #[derive(Debug)]
    struct Clock;

    impl time::Clock for Clock {
        type T = u32;
        type ImplError = ();
        const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000);

        fn try_now(&self) -> Result<Instant<Self>, time::clock::Error<Self::ImplError>> {
            unimplemented!()
        }
    }

    #[test]
    fn duration_since() {
        let diff = Instant::<Clock>::new(5).duration_since(&Instant::<Clock>::new(3));
        assert_eq!(
            diff,
            Ok(duration::Generic::new(2_u32, Fraction::new(1, 1_000)))
        );

        let diff = Instant::<Clock>::new(5).duration_since(&Instant::<Clock>::new(6));
        assert_eq!(diff, Err(ConversionError::NegDuration));
    }
}