Replace unwraps in doctests with graceful handling
Subsystems (3)
v3 cover Replace unwraps in doctests with graceful handling
In the following patches, I touch on error handling in the documentation tests/examples. There are multiple occurrences of unwraps which can be replaced by a question mark operator which should simplify the code. Also, people typically tend to copy & paste code from the examples (citation needed). If we leave the unwraps there, I think we can convey the wrong impression, that it is OK to use unwraps unless the programmer has a really good reason to use them.
Changes since v2:
- Fix typos in commit messages
- Remove unused import
Changes since RFC/v1:
- Remove opinionated changes from rust/kernel/rbtree.rs.
- Run clippy
- Add description to each commit message body with rationale.
- Link to RFC/v1: https://lore.kernel.org/rust-for-linux/[email protected]/
Daniel Sedlak (4):
rust: kernel: init: replace unwraps with the question mark operators
rust: kernel: rbtree: remove unwrap in asserts
rust: kernel: page: remove unnecessary helper function from doctest
rust: kernel: str: replace unwraps with the question mark operators
rust/kernel/init.rs | 6 ++++-- rust/kernel/page.rs | 6 ++---- rust/kernel/rbtree.rs | 46 +++++++++++++++++++++---------------------- rust/kernel/str.rs | 28 +++++++++++++++----------- 4 files changed, 46 insertions(+), 40 deletions(-)
Signature · 1 line
2.47.0
PATCH v3 1/4 rust: kernel: init: replace unwraps with the question mark operators
Use ? operator in the doctest. Since it is in the examples, using unwraps can convey a wrong impression that unwrapping is safe behavior, thus this patch removes this unwrapping.
--- rust/kernel/init.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
rust/kernel/init.rs +4 -2
@@ -1076,8 +1076,9 @@ pub fn uninit<T, E>() -> impl Init<MaybeUninit<T>, E> {/// ```rust /// use kernel::{alloc::KBox, error::Error, init::init_array_from_fn}; /// let array: KBox<[usize; 1_000]> = -/// KBox::init::<Error>(init_array_from_fn(|i| i), GFP_KERNEL).unwrap(); +/// KBox::init::<Error>(init_array_from_fn(|i| i), GFP_KERNEL)?; /// assert_eq!(array.len(), 1_000); +/// # Ok::<(), Error>(()) /// ``` pub fn init_array_from_fn <I ,const N :usize ,T ,E >( mut make_init: impl FnMut(usize) -> I,
@@ -1120,8 +1121,9 @@ pub fn init_array_from_fn<I, const N: usize, T, E>(/// ```rust /// use kernel::{sync::{Arc, Mutex}, init::pin_init_array_from_fn, new_mutex}; /// let array: Arc<[Mutex<usize>; 1_000]> = -/// Arc::pin_init(pin_init_array_from_fn(|i| new_mutex!(i)), GFP_KERNEL).unwrap(); +/// Arc::pin_init(pin_init_array_from_fn(|i| new_mutex!(i)), GFP_KERNEL)?; /// assert_eq!(array.len(), 1_000); +/// # Ok::<(), Error>(()) /// ``` pub fn pin_init_array_from_fn <I ,const N :usize ,T ,E >( mut make_init: impl FnMut(usize) -> I,
Signature · 1 line
2.47.0
Re: [PATCH v3 1/4] rust: kernel: init: replace unwraps with the question mark operators
Quoted 8 lines · Daniel Sedlak
Use
?operator in the doctest. Since it is in the examples, using unwraps can convey a wrong impression that unwrapping is safe behavior, thus this patch removes this unwrapping.
PATCH v3 2/4 rust: kernel: rbtree: remove unwrap in asserts
In reply to Daniel SedlakRemove unwrap in asserts and replace it with Option::Some matching. By doing it this way, the examples are more descriptive, so it disambiguates the return type of the get(...) and next(...), because the unwrap(...) can also be called on Result.
--- rust/kernel/rbtree.rs | 46 +++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 23 deletions(-)
rust/kernel/rbtree.rs +23 -23
@@ -36,17 +36,17 @@/// /// // Check the nodes we just inserted. /// { -/// assert_eq!(tree.get(&10).unwrap(), &100); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30).unwrap(), &300); +/// assert_eq!(tree.get(&10), Some(&100)); +/// assert_eq!(tree.get(&20), Some(&200)); +/// assert_eq!(tree.get(&30), Some(&300)); /// } /// /// // Iterate over the nodes we just inserted. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &100)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); -/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert_eq!(iter.next(), Some((&10, &100))); +/// assert_eq!(iter.next(), Some((&20, &200))); +/// assert_eq!(iter.next(), Some((&30, &300))); /// assert!(iter.next().is_none()); /// } ///
@@ -61,9 +61,9 @@/// // Check that the tree reflects the replacement. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &1000)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); -/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert_eq!(iter.next(), Some((&10, &1000))); +/// assert_eq!(iter.next(), Some((&20, &200))); +/// assert_eq!(iter.next(), Some((&30, &300))); /// assert!(iter.next().is_none()); /// } ///
@@ -73,9 +73,9 @@/// // Check that the tree reflects the update. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &1000)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); -/// assert_eq!(iter.next().unwrap(), (&30, &3000)); +/// assert_eq!(iter.next(), Some((&10, &1000))); +/// assert_eq!(iter.next(), Some((&20, &200))); +/// assert_eq!(iter.next(), Some((&30, &3000))); /// assert!(iter.next().is_none()); /// } ///
@@ -85,8 +85,8 @@/// // Check that the tree reflects the removal. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); -/// assert_eq!(iter.next().unwrap(), (&30, &3000)); +/// assert_eq!(iter.next(), Some((&20, &200))); +/// assert_eq!(iter.next(), Some((&30, &3000))); /// assert!(iter.next().is_none()); /// } ///
@@ -128,20 +128,20 @@/// // Check the nodes we just inserted. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &100)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); -/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert_eq!(iter.next(), Some((&10, &100))); +/// assert_eq!(iter.next(), Some((&20, &200))); +/// assert_eq!(iter.next(), Some((&30, &300))); /// assert!(iter.next().is_none()); /// } /// /// // Remove a node, getting back ownership of it. -/// let existing = tree.remove(&30).unwrap(); +/// let existing = tree.remove(&30); /// /// // Check that the tree reflects the removal. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &100)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next(), Some((&10, &100))); +/// assert_eq!(iter.next(), Some((&20, &200))); /// assert!(iter.next().is_none()); /// } ///
@@ -155,9 +155,9 @@/// // Check that the tree reflect the new insertion. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &100)); -/// assert_eq!(iter.next().unwrap(), (&15, &150)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next(), Some((&10, &100))); +/// assert_eq!(iter.next(), Some((&15, &150))); +/// assert_eq!(iter.next(), Some((&20, &200))); /// assert!(iter.next().is_none()); /// } ///
Signature · 1 line
2.47.0
Re: [PATCH v3 2/4] rust: kernel: rbtree: remove unwrap in asserts
Quoted 8 lines · Daniel Sedlak
Remove
unwrapin asserts and replace it withOption::Somematching. By doing it this way, the examples are more descriptive, so it disambiguates the return type of theget(...)andnext(...), because theunwrap(...)can also be called onResult.Signed-off-by Daniel Sedlak <[email protected]>
PATCH v3 3/4 rust: kernel: page: remove unnecessary helper function from doctest
In reply to Daniel SedlakDoctest in the page.rs contained helper function dox which acted as a wrapper for using the ? operator. However, this is not needed because doctests are implicitly wrapped in function see [1].
Signed-off: Signed-off-by: Daniel Sedlak <[email protected]>
--- rust/kernel/page.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-)
rust/kernel/page.rs +2 -4
@@ -57,9 +57,8 @@ impl Page {/// ``` /// use kernel::page::Page; /// -/// # fn dox() -> Result<(), kernel::alloc::AllocError> { /// let page = Page::alloc_page(GFP_KERNEL)?; -/// # Ok(()) } +/// # Ok::<(), kernel::alloc::AllocError>(()) /// ``` /// /// Allocate memory for a page and zero its contents.
@@ -67,9 +66,8 @@ impl Page {/// ``` /// use kernel::page::Page; /// -/// # fn dox() -> Result<(), kernel::alloc::AllocError> { /// let page = Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?; -/// # Ok(()) } +/// # Ok::<(), kernel::alloc::AllocError>(()) /// ``` pub fn alloc_page (flags:Flags ) ->Result <Self ,AllocError > {// SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it
Signature · 1 line
2.47.0
PATCH v3 4/4 rust: kernel: str: replace unwraps with the question mark operators
In reply to Daniel SedlakSimplify the error handling by replacing unwraps with the question mark operator. Furthermore, unwraps can convey a wrong impression that unwrapping is safe behavior, thus this patch removes this unwrapping.
--- rust/kernel/str.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-)
rust/kernel/str.rs +17 -11
@@ -39,12 +39,13 @@ impl fmt::Display for BStr {/// ``` /// # use kernel::{fmt, b_str, str::{BStr, CString}}; /// let ascii = b_str!("Hello, BStr!"); -/// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{}", ascii))?; /// assert_eq!(s.as_bytes(), "Hello, BStr!".as_bytes()); /// /// let non_ascii = b_str!("🦀"); -/// let s = CString::try_from_fmt(fmt!("{}", non_ascii)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{}", non_ascii))?; /// assert_eq!(s.as_bytes(), "\\xf0\\x9f\\xa6\\x80".as_bytes()); +/// # Ok::<(), kernel::error::Error>(()) /// ``` fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result {for &bin &self.0 {
@@ -70,12 +71,13 @@ impl fmt::Debug for BStr {/// # use kernel::{fmt, b_str, str::{BStr, CString}}; /// // Embedded double quotes are escaped. /// let ascii = b_str!("Hello, \"BStr\"!"); -/// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{:?}", ascii))?; /// assert_eq!(s.as_bytes(), "\"Hello, \\\"BStr\\\"!\"".as_bytes()); /// /// let non_ascii = b_str!("😺"); -/// let s = CString::try_from_fmt(fmt!("{:?}", non_ascii)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{:?}", non_ascii))?; /// assert_eq!(s.as_bytes(), "\"\\xf0\\x9f\\x98\\xba\"".as_bytes()); +/// # Ok::<(), kernel::error::Error>(()) /// ``` fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result { f.write_char ('"' )?;
@@ -273,8 +275,9 @@ pub const fn as_bytes_with_nul(&self) -> &[u8] {/// /// ``` /// # use kernel::str::CStr; -/// let cstr = CStr::from_bytes_with_nul(b"foo\0").unwrap(); +/// let cstr = CStr::from_bytes_with_nul(b"foo\0")?; /// assert_eq!(cstr.to_str(), Ok("foo")); +/// # Ok::<(), kernel::error::Error>(()) /// ``` #[inline] pub fn to_str (&self) ->Result <&str , core::str::Utf8Error > {
@@ -384,12 +387,13 @@ impl fmt::Display for CStr {/// # use kernel::str::CStr; /// # use kernel::str::CString; /// let penguin = c_str!("🐧"); -/// let s = CString::try_from_fmt(fmt!("{}", penguin)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{}", penguin))?; /// assert_eq!(s.as_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes()); /// /// let ascii = c_str!("so \"cool\""); -/// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{}", ascii))?; /// assert_eq!(s.as_bytes_with_nul(), "so \"cool\"\0".as_bytes()); +/// # Ok::<(), kernel::error::Error>(()) /// ``` fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result {for &cin self.as_bytes () {
@@ -413,13 +417,14 @@ impl fmt::Debug for CStr {/// # use kernel::str::CStr; /// # use kernel::str::CString; /// let penguin = c_str!("🐧"); -/// let s = CString::try_from_fmt(fmt!("{:?}", penguin)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{:?}", penguin))?; /// assert_eq!(s.as_bytes_with_nul(), "\"\\xf0\\x9f\\x90\\xa7\"\0".as_bytes()); /// /// // Embedded double quotes are escaped. /// let ascii = c_str!("so \"cool\""); -/// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{:?}", ascii))?; /// assert_eq!(s.as_bytes_with_nul(), "\"so \\\"cool\\\"\"\0".as_bytes()); +/// # Ok::<(), kernel::error::Error>(()) /// ``` fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result { f.write_str ("\"" )?;
@@ -799,16 +804,17 @@ fn write_str(&mut self, s: &str) -> fmt::Result {/// ``` /// use kernel::{str::CString, fmt}; /// -/// let s = CString::try_from_fmt(fmt!("{}{}{}", "abc", 10, 20)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{}{}{}", "abc", 10, 20))?; /// assert_eq!(s.as_bytes_with_nul(), "abc1020\0".as_bytes()); /// /// let tmp = "testing"; -/// let s = CString::try_from_fmt(fmt!("{tmp}{}", 123)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{tmp}{}", 123))?; /// assert_eq!(s.as_bytes_with_nul(), "testing123\0".as_bytes()); /// /// // This fails because it has an embedded `NUL` byte. /// let s = CString::try_from_fmt(fmt!("a\0b{}", 123)); /// assert_eq!(s.is_ok(), false); +/// # Ok::<(), kernel::error::Error>(()) /// ``` pub struct CString { buf:KVec <u8 >,
Signature · 1 line
2.47.0
Miguel Ojeda
AppliedQuoted 8 lines · Daniel Sedlak
In the following patches, I touch on error handling in the documentation tests/examples. There are multiple occurrences of unwraps which can be replaced by a question mark operator which should simplify the code. Also, people typically tend to copy & paste code from the examples (citation needed). If we leave the unwraps there, I think we can convey the wrong impression, that it is OK to use unwraps unless the programmer has a really good reason to use them.
Applied to rust-next -- thanks everyone!
[ Slightly reworded commit. - Miguel ]
[ Fixed typo in SoB. Slightly reworded commit. - Miguel ]
[ Reworded commit slightly. - Miguel ]
Daniel: in the third patch, there was a broken Signed-off tag (with a "proper" SoB in the same line) -- I fixed it as mentioned above, but if you didn't intend to sign off the patch, please let me know, thanks!
Cheers,
Miguel