Re: [PATCH] rust: alloc: Add doctest for `ArrayLayout`

From: Miguel Ojeda
Date: Tue Dec 10 2024 - 06:22:41 EST


On Wed, Dec 4, 2024 at 12:57 PM Dirk Behme <dirk.behme@xxxxxxxxxxxx> wrote:
>
> Slightly off-topic here, but should we try to document that somehow?
>
> What's about something like [1] below? If it is ok, I can make a proper
> patch for it :)

Sure, please send it! :)

(In general, I think we should avoid repeating "general Rust
knowledge", but as long as there is kernel-specific content, like your
paragraphs below, then it is good to have.)

> +``Error`` as its error type.

I see this first part comes from the `Result` docs we have, right? I
think the rest makes sense in Doc/ as you have it; on the other hand,
we try to avoid duplication. We could perhaps move everything to the
`Result` (or `kernel::error` module) docs, and just link it from Doc/
-- that would give us the ability to easily have intra-doc links on
the methods like `unwrap()` and to test the examples.

(I noticed because I was about to suggest linking/qualifying the type
above, but if we had it in the code docs, we would already get that
for free.)

> +The ``?``-operator versus ``unwrap(``) and ``expect()``
> +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> +
> +Calling a function that returns ``Result`` needs the caller to handle
> +the returned ``Result``.

A (kernel-specific) example could help here, even if "abstract", e.g.:

fn f() -> Result {
if ... {
return Err(EINVAL);
}

Ok(())
}

This immediately maps to the usual approach in C code. In fact, you
could add the C equivalent here for comparison.

Perhaps even give another abstract one where kernel C would need
`goto` to cleanup.

> +This can be done "manually" by using ``match``. Using ``match`` to decode
> +the ``Result`` is similar to C where all the return value decoding and the
> +error handling is done explicitly by writing handling code for each
> +error to cover. Using ``match`` the error and success handling can be
> implemented
> +in all detail as required.

Another one would be great here too, so that they see the verbosity vs. `?`.

> +Instead of the verbose ``match`` the ``?``-operator or
> ``unwrap()``/``expect()``
> +can be used to handle the ``Result`` "automatically". However, in the
> kernel
> +context, the usage of ``unwrap()`` or ``expect()`` has a side effect
> which is often
> +not wanted: The ``panic!`` called when using ``unwrap()`` or
> ``expect()``. While the
> +console output from ``panic!`` is nice and quite helpful for debugging
> the error,
> +stopping the whole Linux system due to the kernel panic is often not
> desired.

Perhaps link to any relevant C side docs here.

Perhaps we could also mention briefly other approaches used sometimes,
e.g. `unwrap_or()` and `unwrap_unchecked()`, ideally linking to the
Rust book or similar.

Thanks!

Cheers,
Miguel