Skip to content

Commit 112ee62

Browse files
committed
Refactor Thread::sleep.
1 parent bf21610 commit 112ee62

File tree

1 file changed

+11
-17
lines changed

1 file changed

+11
-17
lines changed

src/libstd/sys/unix/freertos/thread.rs

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -100,26 +100,20 @@ impl Thread {
100100
}
101101

102102
pub fn sleep(dur: Duration) {
103-
let secs = dur.as_secs();
104-
let nanos = dur.subsec_nanos();
103+
let tick_rate = unsafe { xPortGetTickRateHz() };
105104

106-
let mut remaining_ms = u128::from(secs) * 1_000 + (u128::from(nanos) + 999999) / 1000000;
105+
let mut ticks_to_delay: u64 = dur
106+
.as_secs()
107+
.checked_mul(u64::from(tick_rate))
108+
.and_then(|ms| ms.checked_add(u64::from(dur.subsec_nanos() / tick_rate)))
109+
.expect("overflow converting duration to ticks");
107110

108-
unsafe {
109-
let ms_per_tick = u128::from(1000 / xPortGetTickRateHz());
110-
111-
while remaining_ms > 0 {
112-
let ticks_to_delay = (remaining_ms + ms_per_tick - 1) / ms_per_tick;
113-
114-
if ticks_to_delay > u128::from(crate::u32::MAX) {
115-
remaining_ms -= ms_per_tick * u128::from(crate::u32::MAX);
116-
vTaskDelay(crate::u32::MAX);
117-
} else {
118-
remaining_ms = 0;
119-
vTaskDelay(ticks_to_delay as u32);
120-
}
121-
}
111+
while ticks_to_delay > u64::from(crate::u32::MAX) {
112+
ticks_to_delay -= u64::from(crate::u32::MAX);
113+
unsafe { vTaskDelay(crate::u32::MAX) };
122114
}
115+
116+
unsafe { vTaskDelay(ticks_to_delay as u32) };
123117
}
124118

125119
pub fn join(self) {

0 commit comments

Comments
 (0)