fastimer_core/lib.rs
1// Copyright 2024 FastLabs Developers
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! # Fastimer Core APIs
16//!
17//! Core traits:
18//!
19//! * [`MakeDelay`]: a trait for creating delay futures.
20//! * [`Spawn`]: a trait for spawning futures, this is useful for scheduling tasks.
21//!
22//! Utility functions:
23//!
24//! * [`far_future`]: create a far future instant.
25//! * [`make_instant_from`]: create an instant from the given instant and a duration.
26//! * [`make_instant_from_now`]: create an instant from [`Instant::now`] and a duration.
27
28use std::future::Future;
29use std::time::Duration;
30use std::time::Instant;
31
32/// Create a far future instant.
33pub fn far_future() -> Instant {
34 // Roughly 30 years from now.
35 // API does not provide a way to obtain max `Instant`
36 // or convert specific date in the future to instant.
37 // 1000 years overflows on macOS, 100 years overflows on FreeBSD.
38 Instant::now() + Duration::from_secs(86400 * 365 * 30)
39}
40
41/// Create an instant from the given instant and a duration.
42pub fn make_instant_from(now: Instant, dur: Duration) -> Instant {
43 now.checked_add(dur).unwrap_or_else(far_future)
44}
45
46/// Create an instant from [`Instant::now`] and a duration.
47pub fn make_instant_from_now(dur: Duration) -> Instant {
48 make_instant_from(Instant::now(), dur)
49}
50
51/// A trait for creating delay futures.
52pub trait MakeDelay {
53 /// The future returned by the `delay`/`delay_until` method.
54 type Delay: Future<Output = ()> + Send;
55
56 /// Create a future that completes at the specified instant.
57 fn delay_until(&self, at: Instant) -> Self::Delay;
58
59 /// Create a future that completes after the specified duration.
60 fn delay(&self, duration: Duration) -> Self::Delay {
61 self.delay_until(make_instant_from_now(duration))
62 }
63}
64
65/// A trait for spawning futures.
66pub trait Spawn {
67 /// Spawn a future and return a cancellable future.
68 fn spawn<F: Future<Output = ()> + Send + 'static>(&self, future: F);
69}