Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

rust: error: improve `to_result` documentation

Core functions like `to_result` should have good documentation.

Thus improve it, including adding an example of how to perform early
returns with it.

Reviewed-by: Benno Lossin <lossin@kernel.org>
Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>

+37 -2
+37 -2
rust/kernel/error.rs
··· 392 392 /// [Rust documentation]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html 393 393 pub type Result<T = (), E = Error> = core::result::Result<T, E>; 394 394 395 - /// Converts an integer as returned by a C kernel function to an error if it's negative, and 396 - /// `Ok(())` otherwise. 395 + /// Converts an integer as returned by a C kernel function to a [`Result`]. 396 + /// 397 + /// If the integer is negative, an [`Err`] with an [`Error`] as given by [`Error::from_errno`] is 398 + /// returned. This means the integer must be `>= -MAX_ERRNO`. 399 + /// 400 + /// Otherwise, it returns [`Ok`]. 401 + /// 402 + /// It is a bug to pass an out-of-range negative integer. `Err(EINVAL)` is returned in such a case. 403 + /// 404 + /// # Examples 405 + /// 406 + /// This function may be used to easily perform early returns with the [`?`] operator when working 407 + /// with C APIs within Rust abstractions: 408 + /// 409 + /// ``` 410 + /// # use kernel::error::to_result; 411 + /// # mod bindings { 412 + /// # #![expect(clippy::missing_safety_doc)] 413 + /// # use kernel::prelude::*; 414 + /// # pub(super) unsafe fn f1() -> c_int { 0 } 415 + /// # pub(super) unsafe fn f2() -> c_int { EINVAL.to_errno() } 416 + /// # } 417 + /// fn f() -> Result { 418 + /// // SAFETY: ... 419 + /// to_result(unsafe { bindings::f1() })?; 420 + /// 421 + /// // SAFETY: ... 422 + /// to_result(unsafe { bindings::f2() })?; 423 + /// 424 + /// // ... 425 + /// 426 + /// Ok(()) 427 + /// } 428 + /// # assert_eq!(f(), Err(EINVAL)); 429 + /// ``` 430 + /// 431 + /// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator 397 432 pub fn to_result(err: crate::ffi::c_int) -> Result { 398 433 if err < 0 { 399 434 Err(Error::from_errno(err))