Re: [PATCH v8 4/7] rust: time: Add wrapper for fsleep function
From: Alice Ryhl
Date: Wed Jan 22 2025 - 05:48:06 EST
On Wed, Jan 22, 2025 at 11:44 AM FUJITA Tomonori
<fujita.tomonori@xxxxxxxxx> wrote:
>
> >> >> A range can be used for a custom type?
> >> >
> >> > I was thinking of doing it through `as_nanos()`, but it may read
> >> > worse, so please ignore it if so.
> >>
> >> Ah, it might work. The following doesn't work. Seems that we need to
> >> add another const like MAX_DELTA_NANOS or something. No strong
> >> preference but I feel the current is simpler.
> >>
> >> let delta = match delta.as_nanos() {
> >> 0..=MAX_DELTA.as_nanos() as i32 => delta,
> >> _ => MAX_DELTA,
> >> };
> >
> > Could you do Delta::min(delta, MAX_DELTA).as_nanos() ?
>
> We need Delta type here so you meant:
>
> let delta = std::cmp::min(delta, MAX_DELTA);
If `Delta` implements the `Ord` trait, then you can write `Delta::min`
to take the minimum of two deltas. It's equivalent to `std::cmp::min`,
of course.
> We also need to convert a negative delta to MAX_DELTA so we could do:
>
> let delta = if delta.is_negative() {
> MAX_DELTA
> } else {
> min(delta, MAX_DELTA)
> };
>
> looks a bit readable than the original code?
At that point we might as well write
if delta.is_negative() || delta > MAX_DELTA
and skip the call to `min`.
Alice