Skip to content

Commit 2ceb3a7

Browse files
committed
Add Instant::try_from_* constructor functions
1 parent 7c49f48 commit 2ceb3a7

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

embassy-time/src/instant.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,37 @@ impl Instant {
5050
}
5151
}
5252

53+
/// Try to create an Instant from a microsecond count since system boot.
54+
/// Fails if the number of microseconds is too large.
55+
pub const fn try_from_micros(micros: u64) -> Option<Self> {
56+
let Some(value) = micros.checked_mul(TICK_HZ / GCD_1M) else {
57+
return None;
58+
};
59+
Some(Self {
60+
ticks: value / (1_000_000 / GCD_1M),
61+
})
62+
}
63+
64+
/// Try to create an Instant from a millisecond count since system boot.
65+
/// Fails if the number of milliseconds is too large.
66+
pub const fn try_from_millis(millis: u64) -> Option<Self> {
67+
let Some(value) = millis.checked_mul(TICK_HZ / GCD_1K) else {
68+
return None;
69+
};
70+
Some(Self {
71+
ticks: value / (1000 / GCD_1K),
72+
})
73+
}
74+
75+
/// Try to create an Instant from a second count since system boot.
76+
/// Fails if the number of seconds is too large.
77+
pub const fn try_from_secs(seconds: u64) -> Option<Self> {
78+
let Some(ticks) = seconds.checked_mul(TICK_HZ) else {
79+
return None;
80+
};
81+
Some(Self { ticks })
82+
}
83+
5384
/// Tick count since system boot.
5485
pub const fn as_ticks(&self) -> u64 {
5586
self.ticks

0 commit comments

Comments
 (0)