From ca8ef80477914652c1f442c39dd240400e838f3b Mon Sep 17 00:00:00 2001 From: James Munns Date: Thu, 30 Nov 2023 14:05:05 +0100 Subject: [PATCH] Use named constants to clarify delay-stepdown behavior --- embedded-hal/src/delay.rs | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/embedded-hal/src/delay.rs b/embedded-hal/src/delay.rs index 8a1fc3c9d..213c42491 100644 --- a/embedded-hal/src/delay.rs +++ b/embedded-hal/src/delay.rs @@ -1,5 +1,10 @@ //! Delays. +/// Nanoseconds per microsecond +const NANOS_PER_MICRO: u32 = 1_000; +/// Nanoseconds per millisecond +const NANOS_PER_MILLI: u32 = 1_000_000; + /// Delay with up to nanosecond precision. pub trait DelayNs { /// Pauses execution for at minimum `ns` nanoseconds. Pause can be longer @@ -9,22 +14,30 @@ pub trait DelayNs { /// Pauses execution for at minimum `us` microseconds. Pause can be longer /// if the implementation requires it due to precision/timing issues. fn delay_us(&mut self, mut us: u32) { - while us > 4_294_967 { - us -= 4_294_967; - self.delay_ns(4_294_967_000); + const MAX_MICROS: u32 = u32::MAX / NANOS_PER_MICRO; + + // Avoid potential overflow if micro -> micro conversion is too large + while us > MAX_MICROS { + us -= MAX_MICROS; + self.delay_ns(MAX_MICROS * NANOS_PER_MICRO); } - self.delay_ns(us * 1_000); + + self.delay_ns(us * NANOS_PER_MICRO); } /// Pauses execution for at minimum `ms` milliseconds. Pause can be longer /// if the implementation requires it due to precision/timing issues. #[inline] fn delay_ms(&mut self, mut ms: u32) { - while ms > 4294 { - ms -= 4294; - self.delay_ns(4_294_000_000); + const MAX_MILLIS: u32 = u32::MAX / NANOS_PER_MILLI; + + // Avoid potential overflow if milli -> micro conversion is too large + while ms > MAX_MILLIS { + ms -= MAX_MILLIS; + self.delay_ns(MAX_MILLIS * NANOS_PER_MILLI); } - self.delay_ns(ms * 1_000_000); + + self.delay_ns(ms * NANOS_PER_MILLI); } }