Re: [PATCH v9 7/8] rust: Add read_poll_timeout functions

From: FUJITA Tomonori
Date: Tue Jan 28 2025 - 23:53:38 EST


On Tue, 28 Jan 2025 11:49:48 +0100
Fiona Behrens <me@xxxxxxxxxx> wrote:

>> +#[track_caller]
>> +pub fn read_poll_timeout<Op, Cond, T: Copy>(
>> + mut op: Op,
>> + mut cond: Cond,
>> + sleep_delta: Delta,
>> + timeout_delta: Option<Delta>,
>> +) -> Result<T>
>> +where
>> + Op: FnMut() -> Result<T>,
>> + Cond: FnMut(&T) -> bool,
>> +{
>> + let start = Instant::now();
>> + let sleep = !sleep_delta.is_zero();
>> +
>> + if sleep {
>> + might_sleep(Location::caller());
>> + }
>> +
>> + loop {
>> + let val = op()?;
>> + if cond(&val) {
>> + // Unlike the C version, we immediately return.
>> + // We know the condition is met so we don't need to check again.
>> + return Ok(val);
>> + }
>> + if let Some(timeout_delta) = timeout_delta {
>> + if start.elapsed() > timeout_delta {
>> + // Unlike the C version, we immediately return.
>> + // We have just called `op()` so we don't need to call it again.
>> + return Err(ETIMEDOUT);
>> + }
>> + }
>> + if sleep {
>> + fsleep(sleep_delta);
>> + }
>> + // fsleep() could be busy-wait loop so we always call cpu_relax().
>> + cpu_relax();
>> + }
>> +}
>
> I wonder if it makes sense to then switch `Delta` to wrap a `NonZeroI64` and forbid deltas with 0 nanoseconds with that and use the niche optimization. Not sure if we make other apis horrible by that, but this would prevent deltas that encode no time passing.

I think that there are valid use casese for a zero Delta type.

About this function, using zero Delta for sleep_delta means busy
polling. Sevaral drivers use the C version of this function in that
manner.

Using zero Delta for timeout_delta means checking a condition only
once.