Re: [TECH TOPIC] Rust for Linux

Miguel Ojeda
2021-07-19T17:45:23Z

On Mon, Jul 19, 2021 at 6:02 PM Vegard Nossum <vegard.nossum@oracle.com> wrote:
>
> Here you have try_writeb() (and error return) where there was just a
> writeb() without any error handling in the C version. Is this what
> Miguel was answering a bit down the thread where the address is computed
> ((value as u8) << offset) so it _needs_ to use the try_() version?

Not exactly: `((value as u8) << offset)` is the value -- the address
is still controlled by the `try_()` version.

However, the offset given is not a compile-time constant here, thus
the runtime-check is used. Or we could provide an `unsafe fn` which
means the caller would be responsible to guarantee the precondition.
But see next point.

(Actually, from a quick look, there are 3 or so `try_*()` that could
be using the non-`try_*()` version)

> If offset can be anything but a "correct" value here, should there be a
> check for that somewhere else and then the computed value can be
> subsequently treated as safe (i.e. there's a second try_writeb() in the
> function that now presumably does the runtime check a second time,
> redundantly)?

Indeed, that is a pattern that we use all the time to make things
safe, i.e. we create types that hold invariants.

Here, we could definitely keep the information that a given `offset`
is safe and then reuse that knowledge statically.

Ideally, Rust would allow using the loop variable as a compile-time
value if the range is statically known (without unrolling the loop
manually and without a macro).

Cheers,
Miguel