Skip to content

Commit

Permalink
Unrolled build for rust-lang#134593
Browse files Browse the repository at this point in the history
Rollup merge of rust-lang#134593 - kornelski:less-unwrap, r=jhpratt

Less unwrap() in documentation

I think the common use of `.unwrap()` in examples makes it overrepresented, looking like a more typical way of error handling than it really is in real programs.

Therefore, this PR changes a bunch of examples to use different error handling methods, primarily the `?` operator. Additionally, `unwrap()` docs warn that it might abort the program.
  • Loading branch information
rust-timer authored Dec 21, 2024
2 parents 73c278f + 7b42bc0 commit 44b9a94
Show file tree
Hide file tree
Showing 12 changed files with 76 additions and 50 deletions.
3 changes: 1 addition & 2 deletions library/alloc/src/collections/binary_heap/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,8 +531,7 @@ impl<T: Ord, A: Allocator> BinaryHeap<T, A> {
/// heap.push(1);
/// heap.push(5);
/// heap.push(2);
/// {
/// let mut val = heap.peek_mut().unwrap();
/// if let Some(mut val) = heap.peek_mut() {
/// *val = 0;
/// }
/// assert_eq!(heap.peek(), Some(&2));
Expand Down
12 changes: 7 additions & 5 deletions library/core/src/cell/once.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,9 @@ impl<T> OnceCell<T> {
///
/// let value = cell.get_mut_or_try_init(|| "1234".parse());
/// assert_eq!(value, Ok(&mut 1234));
/// *value.unwrap() += 2;
///
/// let Ok(value) = value else { return; };
/// *value += 2;
/// assert_eq!(cell.get(), Some(&1236))
/// ```
#[unstable(feature = "once_cell_get_mut", issue = "121641")]
Expand Down Expand Up @@ -304,8 +306,8 @@ impl<T> OnceCell<T> {
/// assert_eq!(cell.into_inner(), None);
///
/// let cell = OnceCell::new();
/// cell.set("hello".to_string()).unwrap();
/// assert_eq!(cell.into_inner(), Some("hello".to_string()));
/// let _ = cell.set("hello".to_owned());
/// assert_eq!(cell.into_inner(), Some("hello".to_owned()));
/// ```
#[inline]
#[stable(feature = "once_cell", since = "1.70.0")]
Expand All @@ -332,8 +334,8 @@ impl<T> OnceCell<T> {
/// assert_eq!(cell.take(), None);
///
/// let mut cell = OnceCell::new();
/// cell.set("hello".to_string()).unwrap();
/// assert_eq!(cell.take(), Some("hello".to_string()));
/// let _ = cell.set("hello".to_owned());
/// assert_eq!(cell.take(), Some("hello".to_owned()));
/// assert_eq!(cell.get(), None);
/// ```
#[inline]
Expand Down
11 changes: 7 additions & 4 deletions library/core/src/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,9 @@ pub trait Write {
/// }
///
/// let mut buf = String::new();
/// writer(&mut buf, "hola").unwrap();
/// writer(&mut buf, "hola")?;
/// assert_eq!(&buf, "hola");
/// # std::fmt::Result::Ok(())
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn write_str(&mut self, s: &str) -> Result;
Expand All @@ -179,9 +180,10 @@ pub trait Write {
/// }
///
/// let mut buf = String::new();
/// writer(&mut buf, 'a').unwrap();
/// writer(&mut buf, 'b').unwrap();
/// writer(&mut buf, 'a')?;
/// writer(&mut buf, 'b')?;
/// assert_eq!(&buf, "ab");
/// # std::fmt::Result::Ok(())
/// ```
#[stable(feature = "fmt_write_char", since = "1.1.0")]
fn write_char(&mut self, c: char) -> Result {
Expand All @@ -208,8 +210,9 @@ pub trait Write {
/// }
///
/// let mut buf = String::new();
/// writer(&mut buf, "world").unwrap();
/// writer(&mut buf, "world")?;
/// assert_eq!(&buf, "world");
/// # std::fmt::Result::Ok(())
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
Expand Down
3 changes: 2 additions & 1 deletion library/core/src/iter/sources/once.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use crate::iter::{FusedIterator, TrustedLen};
/// use std::fs;
/// use std::path::PathBuf;
///
/// let dirs = fs::read_dir(".foo").unwrap();
/// let dirs = fs::read_dir(".foo")?;
///
/// // we need to convert from an iterator of DirEntry-s to an iterator of
/// // PathBufs, so we use map
Expand All @@ -50,6 +50,7 @@ use crate::iter::{FusedIterator, TrustedLen};
/// for f in files {
/// println!("{f:?}");
/// }
/// # std::io::Result::Ok(())
/// ```
#[stable(feature = "iter_once", since = "1.2.0")]
pub fn once<T>(value: T) -> Once<T> {
Expand Down
6 changes: 3 additions & 3 deletions library/core/src/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2564,7 +2564,7 @@ pub trait Iterator {
/// # Example
///
/// ```
/// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap();
/// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);
/// assert_eq!(reduced, 45);
///
/// // Which is equivalent to doing it with `fold`:
Expand Down Expand Up @@ -3087,7 +3087,7 @@ pub trait Iterator {
/// [2.4, f32::NAN, 1.3]
/// .into_iter()
/// .reduce(f32::max)
/// .unwrap(),
/// .unwrap_or(0.),
/// 2.4
/// );
/// ```
Expand Down Expand Up @@ -3123,7 +3123,7 @@ pub trait Iterator {
/// [2.4, f32::NAN, 1.3]
/// .into_iter()
/// .reduce(f32::min)
/// .unwrap(),
/// .unwrap_or(0.),
/// 1.3
/// );
/// ```
Expand Down
8 changes: 7 additions & 1 deletion library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -937,10 +937,16 @@ impl<T> Option<T> {
/// Returns the contained [`Some`] value, consuming the `self` value.
///
/// Because this function may panic, its use is generally discouraged.
/// Panics are meant for unrecoverable errors, and
/// [may abort the entire program][panic-abort].
///
/// Instead, prefer to use pattern matching and handle the [`None`]
/// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
/// [`unwrap_or_default`].
/// [`unwrap_or_default`]. In functions returning `Option`, you can use
/// [the `?` (try) operator][try-option].
///
/// [panic-abort]: https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html
/// [try-option]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-the--operator-can-be-used
/// [`unwrap_or`]: Option::unwrap_or
/// [`unwrap_or_else`]: Option::unwrap_or_else
/// [`unwrap_or_default`]: Option::unwrap_or_default
Expand Down
9 changes: 6 additions & 3 deletions library/core/src/ptr/const_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,11 +502,12 @@ impl<T: ?Sized> *const T {
/// let mut out = String::new();
/// while ptr != end_rounded_up {
/// unsafe {
/// write!(&mut out, "{}, ", *ptr).unwrap();
/// write!(&mut out, "{}, ", *ptr)?;
/// }
/// ptr = ptr.wrapping_offset(step);
/// }
/// assert_eq!(out.as_str(), "1, 3, 5, ");
/// # std::fmt::Result::Ok(())
/// ```
#[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
#[must_use = "returns a new pointer rather than modifying its argument"]
Expand Down Expand Up @@ -1125,11 +1126,12 @@ impl<T: ?Sized> *const T {
/// let mut out = String::new();
/// while ptr != end_rounded_up {
/// unsafe {
/// write!(&mut out, "{}, ", *ptr).unwrap();
/// write!(&mut out, "{}, ", *ptr)?;
/// }
/// ptr = ptr.wrapping_add(step);
/// }
/// assert_eq!(out, "1, 3, 5, ");
/// # std::fmt::Result::Ok(())
/// ```
#[stable(feature = "pointer_methods", since = "1.26.0")]
#[must_use = "returns a new pointer rather than modifying its argument"]
Expand Down Expand Up @@ -1203,11 +1205,12 @@ impl<T: ?Sized> *const T {
/// let mut out = String::new();
/// while ptr != start_rounded_down {
/// unsafe {
/// write!(&mut out, "{}, ", *ptr).unwrap();
/// write!(&mut out, "{}, ", *ptr)?;
/// }
/// ptr = ptr.wrapping_sub(step);
/// }
/// assert_eq!(out, "5, 3, 1, ");
/// # std::fmt::Result::Ok(())
/// ```
#[stable(feature = "pointer_methods", since = "1.26.0")]
#[must_use = "returns a new pointer rather than modifying its argument"]
Expand Down
11 changes: 8 additions & 3 deletions library/core/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1065,10 +1065,15 @@ impl<T, E> Result<T, E> {
/// Returns the contained [`Ok`] value, consuming the `self` value.
///
/// Because this function may panic, its use is generally discouraged.
/// Instead, prefer to use pattern matching and handle the [`Err`]
/// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
/// [`unwrap_or_default`].
/// Panics are meant for unrecoverable errors, and
/// [may abort the entire program][panic-abort].
///
/// Instead, prefer to use [the `?` (try) operator][try-operator], or pattern matching
/// to handle the [`Err`] case explicitly, or call [`unwrap_or`],
/// [`unwrap_or_else`], or [`unwrap_or_default`].
///
/// [panic-abort]: https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html
/// [try-operator]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator
/// [`unwrap_or`]: Result::unwrap_or
/// [`unwrap_or_else`]: Result::unwrap_or_else
/// [`unwrap_or_default`]: Result::unwrap_or_default
Expand Down
5 changes: 3 additions & 2 deletions library/core/src/str/converts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,11 @@ use crate::{mem, ptr};
/// // some bytes, in a vector
/// let sparkle_heart = vec![240, 159, 146, 150];
///
/// // We know these bytes are valid, so just use `unwrap()`.
/// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
/// // We can use the ? (try) operator to check if the bytes are valid
/// let sparkle_heart = str::from_utf8(&sparkle_heart)?;
///
/// assert_eq!("💖", sparkle_heart);
/// # Ok::<_, str::Utf8Error>(())
/// ```
///
/// Incorrect bytes:
Expand Down
4 changes: 2 additions & 2 deletions library/core/src/sync/atomic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
//! // This is fine: `join` synchronizes the code in a way such that the atomic
//! // store happens-before the non-atomic write.
//! let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store
//! handle.join().unwrap(); // synchronize
//! handle.join().expect("thread won't panic"); // synchronize
//! s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write
//! });
//!
Expand All @@ -103,7 +103,7 @@
//! // This is fine: `join` synchronizes the code in a way such that
//! // the 1-byte store happens-before the 2-byte store.
//! let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed));
//! handle.join().unwrap();
//! handle.join().expect("thread won't panic");
//! s.spawn(|| unsafe {
//! let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic);
//! differently_sized.store(2, Ordering::Relaxed);
Expand Down
25 changes: 15 additions & 10 deletions library/std/src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1083,7 +1083,7 @@ pub trait Read {
/// let f = BufReader::new(File::open("foo.txt")?);
///
/// for byte in f.bytes() {
/// println!("{}", byte.unwrap());
/// println!("{}", byte?);
/// }
/// Ok(())
/// }
Expand Down Expand Up @@ -1995,15 +1995,16 @@ pub trait Seek {
/// .write(true)
/// .read(true)
/// .create(true)
/// .open("foo.txt").unwrap();
/// .open("foo.txt")?;
///
/// let hello = "Hello!\n";
/// write!(f, "{hello}").unwrap();
/// f.rewind().unwrap();
/// write!(f, "{hello}")?;
/// f.rewind()?;
///
/// let mut buf = String::new();
/// f.read_to_string(&mut buf).unwrap();
/// f.read_to_string(&mut buf)?;
/// assert_eq!(&buf, hello);
/// # std::io::Result::Ok(())
/// ```
#[stable(feature = "seek_rewind", since = "1.55.0")]
fn rewind(&mut self) -> Result<()> {
Expand Down Expand Up @@ -2212,8 +2213,9 @@ fn skip_until<R: BufRead + ?Sized>(r: &mut R, delim: u8) -> Result<usize> {
///
/// let stdin = io::stdin();
/// for line in stdin.lock().lines() {
/// println!("{}", line.unwrap());
/// println!("{}", line?);
/// }
/// # std::io::Result::Ok(())
/// ```
///
/// If you have something that implements [`Read`], you can use the [`BufReader`
Expand All @@ -2236,7 +2238,8 @@ fn skip_until<R: BufRead + ?Sized>(r: &mut R, delim: u8) -> Result<usize> {
/// let f = BufReader::new(f);
///
/// for line in f.lines() {
/// println!("{}", line.unwrap());
/// let line = line?;
/// println!("{line}");
/// }
///
/// Ok(())
Expand Down Expand Up @@ -2274,14 +2277,15 @@ pub trait BufRead: Read {
/// let stdin = io::stdin();
/// let mut stdin = stdin.lock();
///
/// let buffer = stdin.fill_buf().unwrap();
/// let buffer = stdin.fill_buf()?;
///
/// // work with buffer
/// println!("{buffer:?}");
///
/// // ensure the bytes we worked with aren't returned again later
/// let length = buffer.len();
/// stdin.consume(length);
/// # std::io::Result::Ok(())
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn fill_buf(&mut self) -> Result<&[u8]>;
Expand Down Expand Up @@ -2327,12 +2331,13 @@ pub trait BufRead: Read {
/// let stdin = io::stdin();
/// let mut stdin = stdin.lock();
///
/// while stdin.has_data_left().unwrap() {
/// while stdin.has_data_left()? {
/// let mut line = String::new();
/// stdin.read_line(&mut line).unwrap();
/// stdin.read_line(&mut line)?;
/// // work with line
/// println!("{line:?}");
/// }
/// # std::io::Result::Ok(())
/// ```
#[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
fn has_data_left(&mut self) -> Result<bool> {
Expand Down
Loading

0 comments on commit 44b9a94

Please sign in to comment.