Re: [PATCH v1] rust: time: Add examples with doctest for Delta

From: FUJITA Tomonori
Date: Wed Jul 02 2025 - 05:10:06 EST


On Wed, 02 Jul 2025 10:36:19 +0200
Andreas Hindborg <a.hindborg@xxxxxxxxxx> wrote:

> "FUJITA Tomonori" <fujita.tomonori@xxxxxxxxx> writes:
>
>> Add examples with doctest for Delta methods and associated
>> functions. These examples explicitly test overflow and saturation
>> behavior.
>>
>> Signed-off-by: FUJITA Tomonori <fujita.tomonori@xxxxxxxxx>
>> ---
>> rust/kernel/time.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++
>> 1 file changed, 67 insertions(+)
>>
>> diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
>> index 64c8dcf548d6..c6322275115a 100644
>> --- a/rust/kernel/time.rs
>> +++ b/rust/kernel/time.rs
>> @@ -228,11 +228,34 @@ impl Delta {
>> /// A span of time equal to zero.
>> pub const ZERO: Self = Self { nanos: 0 };
>>
>> + /// Create a new [`Delta`] from a number of nanoseconds.
>> + ///
>> + /// The `nanos` can range from [`i64::MIN`] to [`i64::MAX`].
>> + #[inline]
>> + pub const fn from_nanos(nanos: i64) -> Self {
>> + Self { nanos }
>> + }
>> +
>> /// Create a new [`Delta`] from a number of microseconds.
>> ///
>> /// The `micros` can range from -9_223_372_036_854_775 to 9_223_372_036_854_775.
>> /// If `micros` is outside this range, `i64::MIN` is used for negative values,
>> /// and `i64::MAX` is used for positive values due to saturation.
>> + ///
>> + /// # Examples
>> + ///
>> + /// ```
>> + /// let delta = kernel::time::Delta::from_micros(5);
>> + /// assert_eq!(delta.as_nanos(), 5_000);
>> + /// let delta = kernel::time::Delta::from_micros(9_223_372_036_854_775);
>> + /// assert_eq!(delta.as_nanos(), 9_223_372_036_854_775_000);
>> + /// let delta = kernel::time::Delta::from_micros(9_223_372_036_854_776);
>> + /// assert_eq!(delta.as_nanos(), i64::MAX);
>> + /// let delta = kernel::time::Delta::from_micros(-9_223_372_036_854_775);
>> + /// assert_eq!(delta.as_nanos(), -9_223_372_036_854_775_000);
>> + /// let delta = kernel::time::Delta::from_micros(-9_223_372_036_854_776);
>> + /// assert_eq!(delta.as_nanos(), i64::MIN);
>> + /// ```
>
>
> I think this kind of test would be better suited for the new `#[test]`
> macro. Would you agree?

I think that Miguel suggested adding examples but either is fine by me:

https://lore.kernel.org/lkml/CANiq72kiTwpcH6S0XaTEBnLxqyJ6EDVLoZPi9X+MWkanK5wq=w@xxxxxxxxxxxxxx/