Re: [RFC PATCH 2/4] rust: usb: add usb host interface and endpoint abstractions
From: Miguel Ojeda
Date: Tue Jul 14 2026 - 14:26:36 EST
On Tue, Jul 14, 2026 at 6:26 PM Alan Stern <stern@xxxxxxxxxxxxxxxxxxx> wrote:
>
> I'm aware that Rust has separate types for pointers that may be NULL and
> pointers that cannot be NULL. Putting that into the language helps
> prevent a lot of bugs. How would making the language be aware of
> whether a device is bound to a driver be similarly useful?
Generally speaking, different types can implement different methods,
which allows one to restrict what functions can be called in certain
cases, which prevents bugs.
Similarly, having different types allow one to put different
invariants on them, like the non-NULL you mention [*]. In turn, that
allows one to design APIs that require callers to pass the proof they
have the right type.
That is, even if something may be exactly the same underlying data
structure, the types being different allows to disambiguate this.
Otherwise, you may need to check or assume those facts, without
compiler support. In some cases, if those facts could lead to UB, then
it means one's API may need to be `unsafe` instead of a safe
abstraction, which make them more cumbersome and "dangerous" to use
for callers.
So, for instance,
https://rust.docs.kernel.org/kernel/device/struct.Bound.html
says
Some APIs, such as `dma::Coherent` or `Devres` rely on the `Device`
to be bound, which can be proven with the `Bound` device context.
And indeed there are methods that require such a `&Device<Bound>` like:
https://rust.docs.kernel.org/kernel/devres/struct.Devres.html#method.new
Then the person implementing a safe abstraction can actually rely on
the fact that it knows those facts to argue certain things -- the
compiler will check it. For instance, that a call to the C side will
not introduce UB. But you can use this to argue for other things,
unrelated to UB, like making correctness arguments.
I hope that clarifies a bit and serves as context for the rest of the
discussion.
[*] By the way, Rust's references guarantee way more than just not
being NULL! Not being NULL is just the "easy case" which ones can
dynamically check in other languages anyway.
Cheers,
Miguel