embedded-timers 0.4.0

Softwaretimers and -delays (ms/us) based on a Clock implementation
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
// Copyright Open Logistics Foundation
//
// Licensed under the Open Logistics Foundation License 1.3.
// For details on the licensing terms, see the LICENSE file.
// SPDX-License-Identifier: OLFL-1.3

//! Defines the [`Instant`] trait for clock users and corresponding implementations for clock
//! implementers
//!
//! The following types implementing the [`Instant`] trait are defined:
//! - [`TimespecInstant`] for a struct of `u32` seconds and `u32` nanoseconds
//! - [`Instant32`] for an instant using a single `u32` tick counter
//! - [`Instant64`] for an instant using a single `u64` tick counter
//! - If the `std` feature is enabled, the `Instant` trait is implemented on `std::time::Instant`

use core::time::Duration;

use core::any::Any;
use core::borrow::{Borrow, BorrowMut};
use core::fmt::Debug;
use core::hash::Hash;
use core::ops::{Add, AddAssign, Sub, SubAssign};
use core::panic::{RefUnwindSafe, UnwindSafe};

use core::convert::TryInto;

// Structural(Partial)Eq behind unstable feature, see https://github.com/rust-lang/rust/issues/31434
//use core::marker::{StructuralEq, StructuralPartialEq};

/// Trait for types which represent measurements of monotonically nondecreasing clocks
///
/// This is heavily inspired by the Rust stdlib's
/// [`std::time::Instant`](https://doc.rust-lang.org/stable/std/time/struct.Instant.html) type and
/// tries to replicate its behaviour wherever possible. In contrast to `std::time::Instant` which
/// relies on a globally available clock, this trait only describes the behavior which is available
/// without a global clock. Everything which requires a global clock is moved to the
/// [`Clock`](crate::clock::Clock) trait.
///
/// To be implemented on a given type, this trait requires that type to implement the same traits
/// as `std::time::Instant`. This might look like a huge constraint for implementers at first,
/// but it actually gives more possibilities to users. And it seems reasonable to require all these
/// traits because the underlying data structure will most probably just be a struct containing
/// some kind of numbers (which should not be NaN).
pub trait Instant:
      Sized
    + Add<Duration, Output=Self>
    + AddAssign<Duration>
    + Clone
    + Copy
    + Debug
    + Eq
    + Hash
    + Ord
    + PartialEq<Self>
    + PartialOrd<Self>
    // Structural(Partial)Eq behind unstable feature, see
    // https://github.com/rust-lang/rust/issues/31434
    //+ StructuralEq
    //+ StructuralPartialEq
    + Sub<Duration, Output=Self>
    + Sub<Self, Output=Duration>
    + SubAssign<Duration>
    + RefUnwindSafe
    + Send
    + Sync
    + Unpin
    + UnwindSafe
    + Any
    // TODO Do the following trait bounds even make sense?
    + Borrow<Self>
    + BorrowMut<Self>
    + From<Self>
    //+ core::borrow::ToOwned does not exist, only std::borrow::ToOwned
{
    /// Returns the amount of time elapsed from another instant to this one, or zero duration if
    /// that instant is later than this one.
    ///
    /// # Panics
    ///
    /// As in the current version of the Rust stdlib, this method saturates instead of panicking.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use core::time::Duration;
    /// use embedded_timers::instant::Instant;
    /// use embedded_timers::clock::Clock;
    /// # use embedded_timers::instant::Instant32;
    /// # fn sleep(_duration: Duration) {}
    /// # struct MyClock;
    /// # impl embedded_timers::clock::Clock for MyClock {
    /// #     type Instant = Instant32<1000>;
    /// #     fn now(&self) -> Instant32<1000> {
    /// #         Instant32::new(0)
    /// #     }
    /// # }
    ///
    /// let clock = MyClock;
    /// let now = clock.now();
    /// sleep(Duration::new(1, 0));
    /// let new_now = clock.now();
    /// println!("{:?}", new_now.duration_since(now));
    /// println!("{:?}", now.duration_since(new_now)); // 0ns
    /// ```
    #[must_use]
    fn duration_since(&self, earlier: Self) -> Duration {
        self.checked_duration_since(earlier).unwrap_or_default()
    }

    /// Returns the amount of time elapsed from another instant to this one, or None if that
    /// instant is later than this one.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use core::time::Duration;
    /// use embedded_timers::instant::Instant;
    /// use embedded_timers::clock::Clock;
    /// # use embedded_timers::instant::Instant32;
    /// # fn sleep(_duration: Duration) {}
    /// # struct MyClock;
    /// # impl embedded_timers::clock::Clock for MyClock {
    /// #     type Instant = Instant32<1000>;
    /// #     fn now(&self) -> Instant32<1000> {
    /// #         Instant32::new(0)
    /// #     }
    /// # }
    ///
    /// let clock = MyClock;
    /// let now = clock.now();
    /// sleep(Duration::new(1, 0));
    /// let new_now = clock.now();
    /// println!("{:?}", new_now.checked_duration_since(now));
    /// println!("{:?}", now.checked_duration_since(new_now)); // None
    /// ```
    #[must_use]
    fn checked_duration_since(&self, earlier: Self) -> Option<Duration>;

    /// Returns the amount of time elapsed from another instant to this one, or zero duration if
    /// that instant is later than this one.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use core::time::Duration;
    /// use embedded_timers::instant::Instant;
    /// use embedded_timers::clock::Clock;
    /// # use embedded_timers::instant::Instant32;
    /// # fn sleep(_duration: Duration) {}
    /// # struct MyClock;
    /// # impl embedded_timers::clock::Clock for MyClock {
    /// #     type Instant = Instant32<1000>;
    /// #     fn now(&self) -> Instant32<1000> {
    /// #         Instant32::new(0)
    /// #     }
    /// # }
    ///
    /// let clock = MyClock;
    /// let now = clock.now();
    /// sleep(Duration::new(1, 0));
    /// let new_now = clock.now();
    /// println!("{:?}", new_now.saturating_duration_since(now));
    /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
    /// ```
    #[must_use]
    fn saturating_duration_since(&self, earlier: Self) -> Duration {
        self.checked_duration_since(earlier).unwrap_or_default()
    }

    /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
    /// `Self` (which means it's inside the bounds of the underlying data structure), `None`
    /// otherwise.
    fn checked_add(&self, duration: Duration) -> Option<Self>;

    /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
    /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
    /// otherwise.
    fn checked_sub(&self, duration: Duration) -> Option<Self>;
}

/// An `Instant` type inspired by the `timespec` struct from the C standard library
///
/// This instant type is implemented in a similar way as the [`Duration`] type because they both
/// use a struct of seconds and (subsecond) nanoseconds to represent time. This has the great
/// benefit that additions and subtractions do not require divisions, see the documentation to
/// [`Instant32`] and [`Instant64`].
///
/// The main drawback of this instant type might be that creating these instants is harder. It can
/// be done in basically two ways:
/// 1. The underlying clock uses a simple integer tick counter. In these cases, creating each
///    instant requires the division which is saved when working with the instants. Depending on
///    the use case, this might be more or less efficient than using [`Instant32`] or [`Instant64`].
/// 2. The underlying clock works on a similar seconds+nanoseconds struct directly. In these cases,
///    creating an instant is easy but incrementing the underlying value in the clock tick
///    interrupt gets harder. It is harder because the clock tick interrupt handler needs to take
///    care of the nanosecond overflow which happens once per second and which needs to be properly
///    synchronized with the contexts which request instants. Note though, that this might be the
///    same problem as implementing a clock for [`Instant32`] or [`Instant64`] on platforms that do
///    not support the corresponding atomic types. Especially on widespread 32 bit platforms, the
///    [`AtomicU64`](https://doc.rust-lang.org/core/sync/atomic/struct.AtomicU64.html) might be
///    missing.
///
/// Also, if you are especially concerned about data sizes, [`Instant32`] might be more appropriate
/// for you because this type uses a 64 bit representation, see below.
///
/// The seconds and nanoseconds are both stored as `u32` values. For the nanoseconds, this should
/// be obvious. For the seconds, using a 32 bit integer might remind of the [`year 2038
/// problem`](https://en.wikipedia.org/wiki/Year_2038_problem) but this is only relevant when
/// working with wall clock times. Since `Instant` is about working with monotonic clocks which can
/// always be measured since program or system start, this would only be relevant if the program or
/// system was designed to run for longer than about 136 years. So this should affect nearly no
/// users at all. Therefore, saving additional bits seems reasonable.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct TimespecInstant {
    secs: u32,
    nanos: u32,
}

impl TimespecInstant {
    /// Create a new TimespecInstant
    pub fn new(secs: u32, nanos: u32) -> Self {
        Self { secs, nanos }
    }
}

impl Instant for TimespecInstant {
    fn checked_duration_since(&self, earlier: Self) -> Option<Duration> {
        let slf = Duration::new(self.secs as u64, self.nanos);
        let early = Duration::new(earlier.secs as u64, earlier.nanos);
        slf.checked_sub(early)
    }

    fn checked_add(&self, duration: Duration) -> Option<Self> {
        let sum = Duration::new(self.secs as u64, self.nanos).checked_add(duration)?;
        Some(TimespecInstant {
            secs: sum.as_secs().try_into().ok()?,
            nanos: sum.subsec_nanos(),
        })
    }

    fn checked_sub(&self, duration: Duration) -> Option<Self> {
        let diff = Duration::new(self.secs as u64, self.nanos).checked_add(duration)?;
        Some(TimespecInstant {
            secs: diff.as_secs().try_into().ok()?,
            nanos: diff.subsec_nanos(),
        })
    }
}

impl core::ops::Add<Duration> for TimespecInstant {
    type Output = TimespecInstant;

    /// # Panics
    ///
    /// This function may panic if the resulting point in time cannot be represented by the
    /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
    fn add(self, other: Duration) -> TimespecInstant {
        self.checked_add(other)
            .expect("overflow when adding duration to instant")
    }
}

impl core::ops::AddAssign<Duration> for TimespecInstant {
    fn add_assign(&mut self, other: Duration) {
        *self = *self + other;
    }
}

impl core::ops::Sub<Duration> for TimespecInstant {
    type Output = TimespecInstant;

    fn sub(self, other: Duration) -> TimespecInstant {
        self.checked_sub(other)
            .expect("overflow when subtracting duration from instant")
    }
}

impl core::ops::SubAssign<Duration> for TimespecInstant {
    fn sub_assign(&mut self, other: Duration) {
        *self = *self - other;
    }
}

impl core::ops::Sub<TimespecInstant> for TimespecInstant {
    type Output = Duration;

    /// Returns the amount of time elapsed from another instant to this one, or zero duration if
    /// that instant is later than this one.
    ///
    /// # Panics
    ///
    /// As in the current version of the Rust stdlib, this method saturates instead of panicking.
    fn sub(self, other: TimespecInstant) -> Duration {
        self.duration_since(other)
    }
}

macro_rules! impl_instant {
    ($instant_name:ident, $primitive_type:ident) => {
        /// An `Instant` type using a single unsigned integer tick counter
        ///
        /// For this type, it might be easy to create these instants and to handle the underlying
        /// clock value, especially if the corresponding atomic type is available, see the
        /// documentation to [`TimespecInstant`].
        ///
        /// The main drawback might be that all additions and subtractions require divisions which
        /// might be inefficient on some platforms (when using an integer type larger than the word
        /// width of the processor):
        /// 1. Subtracting two instants yields a [`Duration`] which is a struct of seconds and
        ///    (subsecond) nanoseconds. So this requires division and modulo to convert the simple
        ///    tick difference into a `Duration`.
        /// 2. Adding/subtracting a `Duration` to/from an instant requires to convert the seconds
        ///    and nanoseconds into the corresponding ticks. Converting the seconds only requires
        ///    multiplication with `TICKS_PER_SEC`, but converting the nanoseconds requires
        ///    division by `nanos_per_sec` (which is calculated internally). This division is only
        ///    a 32 bit division though.
        ///
        /// This instant type is generic on the clock frequency `TICKS_PER_SEC`. For example, in
        /// order to implement a millisecond clock, set `TICKS_PER_SEC` to 1000.
        // TODO Check how the output from the derived Debug impl looks like and if a manual one is
        // better
        #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
        pub struct $instant_name<const TICKS_PER_SEC: u32> {
            ticks: $primitive_type,
        }

        impl<const TICKS_PER_SEC: u32> $instant_name<TICKS_PER_SEC> {
            /// Create a new Instant from the given number of ticks
            pub fn new(ticks: $primitive_type) -> Self {
                Self { ticks }
            }
        }

        impl<const TICKS_PER_SEC: u32> Instant for $instant_name<TICKS_PER_SEC> {
            fn checked_duration_since(&self, earlier: Self) -> Option<Duration> {
                let ticks: $primitive_type = self.ticks.checked_sub(earlier.ticks)?;
                let secs: $primitive_type = ticks / TICKS_PER_SEC as $primitive_type;
                let remaining: $primitive_type = ticks % TICKS_PER_SEC as $primitive_type;
                let remaining: u32 = remaining
                    .try_into()
                    .expect("more than u32::MAX subsec ticks");
                let nanos_per_tick: u32 = 1_000_000_000 / TICKS_PER_SEC;
                let nanos = remaining * nanos_per_tick;
                Some(Duration::new(secs.into(), nanos))
            }

            fn checked_add(&self, duration: Duration) -> Option<Self> {
                let mut ticks: $primitive_type = self.ticks;
                let secs: $primitive_type = duration.as_secs().try_into().ok()?;
                let sec_ticks = secs.checked_mul(TICKS_PER_SEC.into())?;
                ticks = ticks.checked_add(sec_ticks)?;
                let nanos: u32 = duration.subsec_nanos();
                let nanos_per_tick: u32 = 1_000_000_000 / TICKS_PER_SEC;
                let nano_ticks: u32 = nanos / nanos_per_tick;
                ticks = ticks.checked_add(nano_ticks.into())?;
                Some($instant_name { ticks })
            }

            fn checked_sub(&self, duration: Duration) -> Option<Self> {
                let mut ticks: $primitive_type = self.ticks;
                let secs: $primitive_type = duration.as_secs().try_into().ok()?;
                let sec_ticks = secs.checked_mul(TICKS_PER_SEC.into())?;
                ticks = ticks.checked_sub(sec_ticks)?;
                let nanos: u32 = duration.subsec_nanos();
                let nanos_per_tick: u32 = 1_000_000_000 / TICKS_PER_SEC;
                let nano_ticks: u32 = nanos / nanos_per_tick;
                ticks = ticks.checked_sub(nano_ticks.into())?;
                Some($instant_name { ticks })
            }
        }

        impl<const TICKS_PER_SEC: u32> core::ops::Add<Duration> for $instant_name<TICKS_PER_SEC> {
            type Output = $instant_name<TICKS_PER_SEC>;

            /// # Panics
            ///
            /// This function may panic if the resulting point in time cannot be represented by the
            /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
            fn add(self, other: Duration) -> $instant_name<TICKS_PER_SEC> {
                self.checked_add(other)
                    .expect("overflow when adding duration to instant")
            }
        }

        impl<const TICKS_PER_SEC: u32> core::ops::AddAssign<Duration>
            for $instant_name<TICKS_PER_SEC>
        {
            fn add_assign(&mut self, other: Duration) {
                *self = *self + other;
            }
        }

        impl<const TICKS_PER_SEC: u32> core::ops::Sub<Duration> for $instant_name<TICKS_PER_SEC> {
            type Output = $instant_name<TICKS_PER_SEC>;

            fn sub(self, other: Duration) -> $instant_name<TICKS_PER_SEC> {
                self.checked_sub(other)
                    .expect("overflow when subtracting duration from instant")
            }
        }

        impl<const TICKS_PER_SEC: u32> core::ops::SubAssign<Duration>
            for $instant_name<TICKS_PER_SEC>
        {
            fn sub_assign(&mut self, other: Duration) {
                *self = *self - other;
            }
        }

        impl<const TICKS_PER_SEC: u32> core::ops::Sub<$instant_name<TICKS_PER_SEC>>
            for $instant_name<TICKS_PER_SEC>
        {
            type Output = Duration;

            /// Returns the amount of time elapsed from another instant to this one, or zero
            /// duration if that instant is later than this one.
            ///
            /// # Panics
            ///
            /// As in the current version of the Rust stdlib, this method saturates instead of
            /// panicking.
            fn sub(self, other: $instant_name<TICKS_PER_SEC>) -> Duration {
                self.duration_since(other)
            }
        }
    };
}

impl_instant!(Instant32, u32);
impl_instant!(Instant64, u64);

#[cfg(feature = "std")]
impl Instant for std::time::Instant {
    fn checked_duration_since(&self, earlier: Self) -> Option<Duration> {
        self.checked_duration_since(earlier)
    }

    fn checked_add(&self, duration: Duration) -> Option<Self> {
        self.checked_add(duration)
    }

    fn checked_sub(&self, duration: Duration) -> Option<Self> {
        self.checked_sub(duration)
    }
}