diff --git a/library/alloc/src/borrow.rs b/library/alloc/src/borrow.rs index 83a1385599bec..7ca1024b8794f 100644 --- a/library/alloc/src/borrow.rs +++ b/library/alloc/src/borrow.rs @@ -145,11 +145,17 @@ where /// ``` /// use std::borrow::Cow; /// -/// struct Items<'a, X: 'a> where [X]: ToOwned> { +/// struct Items<'a, X: 'a> +/// where +/// [X]: ToOwned>, +/// { /// values: Cow<'a, [X]>, /// } /// -/// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned> { +/// impl<'a, X: Clone + 'a> Items<'a, X> +/// where +/// [X]: ToOwned>, +/// { /// fn new(v: Cow<'a, [X]>) -> Self { /// Items { values: v } /// } @@ -265,10 +271,7 @@ impl Cow<'_, B> { /// let mut cow = Cow::Borrowed("foo"); /// cow.to_mut().make_ascii_uppercase(); /// - /// assert_eq!( - /// cow, - /// Cow::Owned(String::from("FOO")) as Cow - /// ); + /// assert_eq!(cow, Cow::Owned(String::from("FOO")) as Cow); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn to_mut(&mut self) -> &mut ::Owned { @@ -298,10 +301,7 @@ impl Cow<'_, B> { /// let s = "Hello world!"; /// let cow = Cow::Borrowed(s); /// - /// assert_eq!( - /// cow.into_owned(), - /// String::from(s) - /// ); + /// assert_eq!(cow.into_owned(), String::from(s)); /// ``` /// /// Calling `into_owned` on a `Cow::Owned` returns the owned data. The data is moved out of the @@ -313,10 +313,7 @@ impl Cow<'_, B> { /// let s = "Hello world!"; /// let cow: Cow = Cow::Owned(String::from(s)); /// - /// assert_eq!( - /// cow.into_owned(), - /// String::from(s) - /// ); + /// assert_eq!(cow.into_owned(), String::from(s)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_owned(self) -> ::Owned { diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index b7e7d5a38a5b1..395fc76101a67 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -2246,8 +2246,7 @@ impl<'a, E: Error + Send + Sync + 'a> From for Box::from(an_error); - /// assert!( - /// mem::size_of::>() == mem::size_of_val(&a_boxed_error)) + /// assert!(mem::size_of::>() == mem::size_of_val(&a_boxed_error)) /// ``` fn from(err: E) -> Box { Box::new(err) @@ -2267,8 +2266,7 @@ impl From for Box { /// /// let a_string_error = "a string error".to_string(); /// let a_boxed_error = Box::::from(a_string_error); - /// assert!( - /// mem::size_of::>() == mem::size_of_val(&a_boxed_error)) + /// assert!(mem::size_of::>() == mem::size_of_val(&a_boxed_error)) /// ``` #[inline] fn from(err: String) -> Box { @@ -2335,8 +2333,7 @@ impl<'a> From<&str> for Box { /// /// let a_str_error = "a str error"; /// let a_boxed_error = Box::::from(a_str_error); - /// assert!( - /// mem::size_of::>() == mem::size_of_val(&a_boxed_error)) + /// assert!(mem::size_of::>() == mem::size_of_val(&a_boxed_error)) /// ``` #[inline] fn from(err: &str) -> Box { @@ -2374,14 +2371,13 @@ impl<'a, 'b> From> for Box { /// # Examples /// /// ``` + /// use std::borrow::Cow; /// use std::error::Error; /// use std::mem; - /// use std::borrow::Cow; /// /// let a_cow_str_error = Cow::from("a str error"); /// let a_boxed_error = Box::::from(a_cow_str_error); - /// assert!( - /// mem::size_of::>() == mem::size_of_val(&a_boxed_error)) + /// assert!(mem::size_of::>() == mem::size_of_val(&a_boxed_error)) /// ``` fn from(err: Cow<'b, str>) -> Box { From::from(String::from(err)) @@ -2396,9 +2392,9 @@ impl<'a> From> for Box { /// # Examples /// /// ``` + /// use std::borrow::Cow; /// use std::error::Error; /// use std::mem; - /// use std::borrow::Cow; /// /// let a_cow_str_error = Cow::from("a str error"); /// let a_boxed_error = Box::::from(a_cow_str_error); diff --git a/library/alloc/src/collections/binary_heap.rs b/library/alloc/src/collections/binary_heap.rs index 4583bc9a158ef..a1ff8aa65d2ad 100644 --- a/library/alloc/src/collections/binary_heap.rs +++ b/library/alloc/src/collections/binary_heap.rs @@ -34,8 +34,7 @@ //! // Notice that the we flip the ordering on costs. //! // In case of a tie we compare positions - this step is necessary //! // to make implementations of `PartialEq` and `Ord` consistent. -//! other.cost.cmp(&self.cost) -//! .then_with(|| self.position.cmp(&other.position)) +//! other.cost.cmp(&self.cost).then_with(|| self.position.cmp(&other.position)) //! } //! } //! @@ -71,10 +70,14 @@ //! // Examine the frontier with lower cost nodes first (min-heap) //! while let Some(State { cost, position }) = heap.pop() { //! // Alternatively we could have continued to find all shortest paths -//! if position == goal { return Some(cost); } +//! if position == goal { +//! return Some(cost); +//! } //! //! // Important as we may have already found a better way -//! if cost > dist[position] { continue; } +//! if cost > dist[position] { +//! continue; +//! } //! //! // For each node we can reach, see if we can find a way with //! // a lower cost going through this node @@ -118,19 +121,16 @@ //! // Chosen for its efficiency. //! let graph = vec![ //! // Node 0 -//! vec![Edge { node: 2, cost: 10 }, -//! Edge { node: 1, cost: 1 }], +//! vec![Edge { node: 2, cost: 10 }, Edge { node: 1, cost: 1 }], //! // Node 1 //! vec![Edge { node: 3, cost: 2 }], //! // Node 2 -//! vec![Edge { node: 1, cost: 1 }, -//! Edge { node: 3, cost: 3 }, -//! Edge { node: 4, cost: 1 }], +//! vec![Edge { node: 1, cost: 1 }, Edge { node: 3, cost: 3 }, Edge { node: 4, cost: 1 }], //! // Node 3 -//! vec![Edge { node: 0, cost: 7 }, -//! Edge { node: 4, cost: 2 }], +//! vec![Edge { node: 0, cost: 7 }, Edge { node: 4, cost: 2 }], //! // Node 4 -//! vec![]]; +//! vec![], +//! ]; //! //! assert_eq!(shortest_path(&graph, 0, 1), Some(1)); //! assert_eq!(shortest_path(&graph, 0, 3), Some(3)); @@ -229,8 +229,8 @@ mod tests; /// value instead of the greatest one. /// /// ``` -/// use std::collections::BinaryHeap; /// use std::cmp::Reverse; +/// use std::collections::BinaryHeap; /// /// let mut heap = BinaryHeap::new(); /// @@ -877,7 +877,6 @@ impl BinaryHeap { /// heap.push(5); /// heap.push(2); /// assert_eq!(heap.peek(), Some(&5)); - /// /// ``` /// /// # Time complexity diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs index c4c75e46a2a3b..32c1e736c6a07 100644 --- a/library/alloc/src/collections/btree/map.rs +++ b/library/alloc/src/collections/btree/map.rs @@ -89,15 +89,14 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT; /// let mut movie_reviews = BTreeMap::new(); /// /// // review some movies. -/// movie_reviews.insert("Office Space", "Deals with real issues in the workplace."); -/// movie_reviews.insert("Pulp Fiction", "Masterpiece."); -/// movie_reviews.insert("The Godfather", "Very enjoyable."); +/// movie_reviews.insert("Office Space", "Deals with real issues in the workplace."); +/// movie_reviews.insert("Pulp Fiction", "Masterpiece."); +/// movie_reviews.insert("The Godfather", "Very enjoyable."); /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot."); /// /// // check for a specific one. /// if !movie_reviews.contains_key("Les Misérables") { -/// println!("We've got {} reviews, but Les Misérables ain't one.", -/// movie_reviews.len()); +/// println!("We've got {} reviews, but Les Misérables ain't one.", movie_reviews.len()); /// } /// /// // oops, this review has a lot of spelling mistakes, let's delete it. @@ -107,8 +106,8 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT; /// let to_find = ["Up!", "Office Space"]; /// for movie in &to_find { /// match movie_reviews.get(movie) { -/// Some(review) => println!("{movie}: {review}"), -/// None => println!("{movie} is unreviewed.") +/// Some(review) => println!("{movie}: {review}"), +/// None => println!("{movie} is unreviewed."), /// } /// } /// @@ -126,12 +125,8 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT; /// ``` /// use std::collections::BTreeMap; /// -/// let solar_distance = BTreeMap::from([ -/// ("Mercury", 0.4), -/// ("Venus", 0.7), -/// ("Earth", 1.0), -/// ("Mars", 1.5), -/// ]); +/// let solar_distance = +/// BTreeMap::from([("Mercury", 0.4), ("Venus", 0.7), ("Earth", 1.0), ("Mars", 1.5)]); /// ``` /// /// `BTreeMap` implements an [`Entry API`], which allows for complex @@ -622,8 +617,8 @@ impl BTreeMap { /// ``` /// # #![feature(allocator_api)] /// # #![feature(btreemap_alloc)] - /// use std::collections::BTreeMap; /// use std::alloc::Global; + /// use std::collections::BTreeMap; /// /// let mut map = BTreeMap::new_in(Global); /// @@ -1076,7 +1071,7 @@ impl BTreeMap { /// ``` /// use std::collections::BTreeMap; /// - /// let mut map: BTreeMap = (0..8).map(|x| (x, x*10)).collect(); + /// let mut map: BTreeMap = (0..8).map(|x| (x, x * 10)).collect(); /// // Keep only the elements with even-numbered keys. /// map.retain(|&k, _| k % 2 == 0); /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)])); @@ -2281,11 +2276,7 @@ impl BTreeMap { /// ``` /// use std::collections::BTreeMap; /// - /// let mut map = BTreeMap::from([ - /// ("a", 1), - /// ("b", 2), - /// ("c", 3), - /// ]); + /// let mut map = BTreeMap::from([("a", 1), ("b", 2), ("c", 3)]); /// /// // add 10 to the value if the key isn't "a" /// for (key, value) in map.iter_mut() { @@ -2365,8 +2356,7 @@ impl BTreeMap { /// } /// /// let values: Vec = a.values().cloned().collect(); - /// assert_eq!(values, [String::from("hello!"), - /// String::from("goodbye!")]); + /// assert_eq!(values, [String::from("hello!"), String::from("goodbye!")]); /// ``` #[stable(feature = "map_values_mut", since = "1.10.0")] pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> { diff --git a/library/alloc/src/collections/btree/map/entry.rs b/library/alloc/src/collections/btree/map/entry.rs index 370b58864af8f..ae08258a74d9a 100644 --- a/library/alloc/src/collections/btree/map/entry.rs +++ b/library/alloc/src/collections/btree/map/entry.rs @@ -246,14 +246,10 @@ impl<'a, K: Ord, V, A: Allocator + Clone> Entry<'a, K, V, A> { /// /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); /// - /// map.entry("poneyland") - /// .and_modify(|e| { *e += 1 }) - /// .or_insert(42); + /// map.entry("poneyland").and_modify(|e| *e += 1).or_insert(42); /// assert_eq!(map["poneyland"], 42); /// - /// map.entry("poneyland") - /// .and_modify(|e| { *e += 1 }) - /// .or_insert(42); + /// map.entry("poneyland").and_modify(|e| *e += 1).or_insert(42); /// assert_eq!(map["poneyland"], 43); /// ``` #[stable(feature = "entry_and_modify", since = "1.26.0")] @@ -316,8 +312,8 @@ impl<'a, K: Ord, V, A: Allocator + Clone> VacantEntry<'a, K, V, A> { /// # Examples /// /// ``` - /// use std::collections::BTreeMap; /// use std::collections::btree_map::Entry; + /// use std::collections::BTreeMap; /// /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); /// @@ -336,8 +332,8 @@ impl<'a, K: Ord, V, A: Allocator + Clone> VacantEntry<'a, K, V, A> { /// # Examples /// /// ``` - /// use std::collections::BTreeMap; /// use std::collections::btree_map::Entry; + /// use std::collections::BTreeMap; /// /// let mut map: BTreeMap<&str, u32> = BTreeMap::new(); /// @@ -406,8 +402,8 @@ impl<'a, K: Ord, V, A: Allocator + Clone> OccupiedEntry<'a, K, V, A> { /// # Examples /// /// ``` - /// use std::collections::BTreeMap; /// use std::collections::btree_map::Entry; + /// use std::collections::BTreeMap; /// /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); /// map.entry("poneyland").or_insert(12); @@ -430,8 +426,8 @@ impl<'a, K: Ord, V, A: Allocator + Clone> OccupiedEntry<'a, K, V, A> { /// # Examples /// /// ``` - /// use std::collections::BTreeMap; /// use std::collections::btree_map::Entry; + /// use std::collections::BTreeMap; /// /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); /// map.entry("poneyland").or_insert(12); @@ -456,8 +452,8 @@ impl<'a, K: Ord, V, A: Allocator + Clone> OccupiedEntry<'a, K, V, A> { /// # Examples /// /// ``` - /// use std::collections::BTreeMap; /// use std::collections::btree_map::Entry; + /// use std::collections::BTreeMap; /// /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); /// map.entry("poneyland").or_insert(12); @@ -486,8 +482,8 @@ impl<'a, K: Ord, V, A: Allocator + Clone> OccupiedEntry<'a, K, V, A> { /// # Examples /// /// ``` - /// use std::collections::BTreeMap; /// use std::collections::btree_map::Entry; + /// use std::collections::BTreeMap; /// /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); /// map.entry("poneyland").or_insert(12); @@ -510,8 +506,8 @@ impl<'a, K: Ord, V, A: Allocator + Clone> OccupiedEntry<'a, K, V, A> { /// # Examples /// /// ``` - /// use std::collections::BTreeMap; /// use std::collections::btree_map::Entry; + /// use std::collections::BTreeMap; /// /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); /// map.entry("poneyland").or_insert(12); @@ -531,8 +527,8 @@ impl<'a, K: Ord, V, A: Allocator + Clone> OccupiedEntry<'a, K, V, A> { /// # Examples /// /// ``` - /// use std::collections::BTreeMap; /// use std::collections::btree_map::Entry; + /// use std::collections::BTreeMap; /// /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); /// map.entry("poneyland").or_insert(12); diff --git a/library/alloc/src/collections/btree/set.rs b/library/alloc/src/collections/btree/set.rs index b8e5cf8eb5a82..6463f96cfdfd9 100644 --- a/library/alloc/src/collections/btree/set.rs +++ b/library/alloc/src/collections/btree/set.rs @@ -56,8 +56,7 @@ use crate::alloc::{Allocator, Global}; /// /// // Check for a specific one. /// if !books.contains("The Winds of Winter") { -/// println!("We have {} books, but The Winds of Winter ain't one.", -/// books.len()); +/// println!("We have {} books, but The Winds of Winter ain't one.", books.len()); /// } /// /// // Remove a book. @@ -359,8 +358,8 @@ impl BTreeSet { /// # #![allow(unused_mut)] /// # #![feature(allocator_api)] /// # #![feature(btreemap_alloc)] - /// use std::collections::BTreeSet; /// use std::alloc::Global; + /// use std::collections::BTreeSet; /// /// let mut set: BTreeSet = BTreeSet::new_in(Global); /// ``` diff --git a/library/alloc/src/collections/linked_list.rs b/library/alloc/src/collections/linked_list.rs index f2f5dffc25d3a..f5196ce56580b 100644 --- a/library/alloc/src/collections/linked_list.rs +++ b/library/alloc/src/collections/linked_list.rs @@ -709,7 +709,7 @@ impl LinkedList { /// assert_eq!(dl.front(), Some(&1)); /// /// match dl.front_mut() { - /// None => {}, + /// None => {} /// Some(x) => *x = 5, /// } /// assert_eq!(dl.front(), Some(&5)); @@ -761,7 +761,7 @@ impl LinkedList { /// assert_eq!(dl.back(), Some(&1)); /// /// match dl.back_mut() { - /// None => {}, + /// None => {} /// Some(x) => *x = 5, /// } /// assert_eq!(dl.back(), Some(&5)); diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index 2a57dad89a770..4637bee550a44 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -1236,13 +1236,13 @@ impl VecDeque { /// /// let mut deque: VecDeque<_> = [1, 2, 3].into(); /// for v in deque.range_mut(2..) { - /// *v *= 2; + /// *v *= 2; /// } /// assert_eq!(deque, [1, 2, 6]); /// /// // A full range covers all contents /// for v in deque.range_mut(..) { - /// *v *= 2; + /// *v *= 2; /// } /// assert_eq!(deque, [2, 4, 12]); /// ``` @@ -2219,11 +2219,13 @@ impl VecDeque { /// /// let mut buf = VecDeque::new(); /// buf.extend(1..5); - /// buf.retain_mut(|x| if *x % 2 == 0 { - /// *x += 1; - /// true - /// } else { - /// false + /// buf.retain_mut(|x| { + /// if *x % 2 == 0 { + /// *x += 1; + /// true + /// } else { + /// false + /// } /// }); /// assert_eq!(buf, [3, 5]); /// ``` @@ -2301,7 +2303,10 @@ impl VecDeque { /// assert_eq!(buf, [5, 10]); /// /// let mut state = 100; - /// buf.resize_with(5, || { state += 1; state }); + /// buf.resize_with(5, || { + /// state += 1; + /// state + /// }); /// assert_eq!(buf, [5, 10, 101, 102, 103]); /// ``` #[stable(feature = "vec_resize_with", since = "1.33.0")] @@ -2617,8 +2622,8 @@ impl VecDeque { /// /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into(); /// - /// assert_eq!(deque.binary_search(&13), Ok(9)); - /// assert_eq!(deque.binary_search(&4), Err(7)); + /// assert_eq!(deque.binary_search(&13), Ok(9)); + /// assert_eq!(deque.binary_search(&4), Err(7)); /// assert_eq!(deque.binary_search(&100), Err(13)); /// let r = deque.binary_search(&1); /// assert!(matches!(r, Ok(1..=4))); @@ -2678,8 +2683,8 @@ impl VecDeque { /// /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into(); /// - /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9)); - /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7)); + /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9)); + /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7)); /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13)); /// let r = deque.binary_search_by(|x| x.cmp(&1)); /// assert!(matches!(r, Ok(1..=4))); @@ -2731,12 +2736,25 @@ impl VecDeque { /// ``` /// use std::collections::VecDeque; /// - /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1), - /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13), - /// (1, 21), (2, 34), (4, 55)].into(); - /// - /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9)); - /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7)); + /// let deque: VecDeque<_> = [ + /// (0, 0), + /// (2, 1), + /// (4, 1), + /// (5, 1), + /// (3, 1), + /// (1, 2), + /// (2, 3), + /// (4, 5), + /// (5, 8), + /// (3, 13), + /// (1, 21), + /// (2, 34), + /// (4, 55), + /// ] + /// .into(); + /// + /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9)); + /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7)); /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13)); /// let r = deque.binary_search_by_key(&1, |&(a, b)| b); /// assert!(matches!(r, Ok(1..=4))); diff --git a/library/alloc/src/ffi/c_str.rs b/library/alloc/src/ffi/c_str.rs index 11bd4c4dc1ba8..c51252f0f919d 100644 --- a/library/alloc/src/ffi/c_str.rs +++ b/library/alloc/src/ffi/c_str.rs @@ -567,12 +567,14 @@ impl CString { /// # Examples /// /// ``` - /// use std::ffi::{CString, CStr}; + /// use std::ffi::{CStr, CString}; /// /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed"); /// let cstr = c_string.as_c_str(); - /// assert_eq!(cstr, - /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed")); + /// assert_eq!( + /// cstr, + /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed") + /// ); /// ``` #[inline] #[must_use] @@ -586,12 +588,14 @@ impl CString { /// # Examples /// /// ``` - /// use std::ffi::{CString, CStr}; + /// use std::ffi::{CStr, CString}; /// /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed"); /// let boxed = c_string.into_boxed_c_str(); - /// assert_eq!(&*boxed, - /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed")); + /// assert_eq!( + /// &*boxed, + /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed") + /// ); /// ``` #[must_use = "`self` will be dropped if the result is not used"] #[stable(feature = "into_boxed_c_str", since = "1.20.0")] @@ -622,10 +626,9 @@ impl CString { /// /// ``` /// use std::ffi::CString; - /// assert_eq!( - /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) }, - /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) } - /// ); + /// assert_eq!(unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) }, unsafe { + /// CString::from_vec_unchecked(b"abc".to_vec()) + /// }); /// ``` #[must_use] #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")] @@ -656,8 +659,7 @@ impl CString { /// ``` /// use std::ffi::CString; /// assert_eq!( - /// CString::from_vec_with_nul(b"abc\0".to_vec()) - /// .expect("CString::from_vec_with_nul failed"), + /// CString::from_vec_with_nul(b"abc\0".to_vec()).expect("CString::from_vec_with_nul failed"), /// CString::new(b"abc".to_vec()).expect("CString::new failed") /// ); /// ``` @@ -1077,8 +1079,8 @@ impl CStr { /// use std::borrow::Cow; /// use std::ffi::CStr; /// - /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0") - /// .expect("CStr::from_bytes_with_nul failed"); + /// let cstr = + /// CStr::from_bytes_with_nul(b"Hello World\0").expect("CStr::from_bytes_with_nul failed"); /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World")); /// ``` /// @@ -1089,11 +1091,8 @@ impl CStr { /// use std::ffi::CStr; /// /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0") - /// .expect("CStr::from_bytes_with_nul failed"); - /// assert_eq!( - /// cstr.to_string_lossy(), - /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str> - /// ); + /// .expect("CStr::from_bytes_with_nul failed"); + /// assert_eq!(cstr.to_string_lossy(), Cow::Owned(String::from("Hello �World")) as Cow<'_, str>); /// ``` #[rustc_allow_incoherent_impl] #[must_use = "this returns the result of the operation, \ diff --git a/library/alloc/src/fmt.rs b/library/alloc/src/fmt.rs index 799ce9d5daa88..b5ec968308d40 100644 --- a/library/alloc/src/fmt.rs +++ b/library/alloc/src/fmt.rs @@ -12,19 +12,19 @@ //! Some examples of the [`format!`] extension are: //! //! ``` -//! format!("Hello"); // => "Hello" -//! format!("Hello, {}!", "world"); // => "Hello, world!" -//! format!("The number is {}", 1); // => "The number is 1" -//! format!("{:?}", (3, 4)); // => "(3, 4)" -//! format!("{value}", value=4); // => "4" +//! format!("Hello"); // => "Hello" +//! format!("Hello, {}!", "world"); // => "Hello, world!" +//! format!("The number is {}", 1); // => "The number is 1" +//! format!("{:?}", (3, 4)); // => "(3, 4)" +//! format!("{value}", value = 4); // => "4" //! let people = "Rustaceans"; -//! format!("Hello {people}!"); // => "Hello Rustaceans!" -//! format!("{} {}", 1, 2); // => "1 2" -//! format!("{:04}", 42); // => "0042" with leading zeros -//! format!("{:#?}", (100, 200)); // => "( -//! // 100, -//! // 200, -//! // )" +//! format!("Hello {people}!"); // => "Hello Rustaceans!" +//! format!("{} {}", 1, 2); // => "1 2" +//! format!("{:04}", 42); // => "0042" with leading zeros +//! format!("{:#?}", (100, 200)); // => "( +//! // 100, +//! // 200, +//! // )" //! ``` //! //! From these, you can see that the first argument is a format string. It is @@ -77,9 +77,9 @@ //! For example, the following [`format!`] expressions all use named arguments: //! //! ``` -//! format!("{argument}", argument = "test"); // => "test" -//! format!("{name} {}", 1, name = 2); // => "2 1" -//! format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b" +//! format!("{argument}", argument = "test"); // => "test" +//! format!("{name} {}", 1, name = 2); // => "2 1" +//! format!("{a} {c} {b}", a = "a", b = 'b', c = 3); // => "a 3 b" //! ``` //! //! If a named parameter does not appear in the argument list, `format!` will @@ -87,7 +87,7 @@ //! //! ``` //! let argument = 2 + 2; -//! format!("{argument}"); // => "4" +//! format!("{argument}"); // => "4" //! //! fn make_string(a: u32, b: &str) -> String { //! format!("{b} {a}") @@ -133,10 +133,10 @@ //! ## Fill/Alignment //! //! ``` -//! assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !"); +//! assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !"); //! assert_eq!(format!("Hello {:-<5}!", "x"), "Hello x----!"); -//! assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !"); -//! assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!"); +//! assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !"); +//! assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!"); //! ``` //! //! The optional fill character and alignment is provided normally in conjunction with the @@ -169,7 +169,7 @@ //! ``` //! assert_eq!(format!("Hello {:+}!", 5), "Hello +5!"); //! assert_eq!(format!("{:#x}!", 27), "0x1b!"); -//! assert_eq!(format!("Hello {:05}!", 5), "Hello 00005!"); +//! assert_eq!(format!("Hello {:05}!", 5), "Hello 00005!"); //! assert_eq!(format!("Hello {:05}!", -5), "Hello -0005!"); //! assert_eq!(format!("{:#010x}!", 27), "0x0000001b!"); //! ``` @@ -242,15 +242,15 @@ //! //! // Hello {next arg -> arg 0 ("x")} is {second of next two args -> arg 2 (0.01) with precision //! // specified in first of next two args -> arg 1 (5)} -//! println!("Hello {} is {:.*}", "x", 5, 0.01); +//! println!("Hello {} is {:.*}", "x", 5, 0.01); //! //! // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision //! // specified in next arg -> arg 0 (5)} -//! println!("Hello {1} is {2:.*}", 5, "x", 0.01); +//! println!("Hello {1} is {2:.*}", 5, "x", 0.01); //! //! // Hello {next arg -> arg 0 ("x")} is {arg 2 (0.01) with precision //! // specified in next arg -> arg 1 (5)} -//! println!("Hello {} is {2:.*}", "x", 5, 0.01); +//! println!("Hello {} is {2:.*}", "x", 5, 0.01); //! //! // Hello {next arg -> arg 0 ("x")} is {arg "number" (0.01) with precision specified //! // in arg "prec" (5)} @@ -260,9 +260,9 @@ //! While these: //! //! ``` -//! println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56); -//! println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56"); -//! println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56"); +//! println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name = 1234.56); +//! println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name = "1234.56"); +//! println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name = "1234.56"); //! ``` //! //! print three significantly different things: @@ -427,8 +427,8 @@ //! fn main() { //! let myvector = Vector2D { x: 3, y: 4 }; //! -//! println!("{myvector}"); // => "(3, 4)" -//! println!("{myvector:?}"); // => "Vector2D {x: 3, y:4}" +//! println!("{myvector}"); // => "(3, 4)" +//! println!("{myvector:?}"); // => "Vector2D {x: 3, y:4}" //! println!("{myvector:10.3b}"); // => " 5.000" //! } //! ``` diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 006d813e5f9fa..a419f683a3025 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -104,23 +104,13 @@ //! //! fn main() { //! // Create a reference-counted `Owner`. -//! let gadget_owner: Rc = Rc::new( -//! Owner { -//! name: "Gadget Man".to_string(), -//! } -//! ); +//! let gadget_owner: Rc = Rc::new(Owner { name: "Gadget Man".to_string() }); //! //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc` //! // gives us a new pointer to the same `Owner` allocation, incrementing //! // the reference count in the process. -//! let gadget1 = Gadget { -//! id: 1, -//! owner: Rc::clone(&gadget_owner), -//! }; -//! let gadget2 = Gadget { -//! id: 2, -//! owner: Rc::clone(&gadget_owner), -//! }; +//! let gadget1 = Gadget { id: 1, owner: Rc::clone(&gadget_owner) }; +//! let gadget2 = Gadget { id: 2, owner: Rc::clone(&gadget_owner) }; //! //! // Dispose of our local variable `gadget_owner`. //! drop(gadget_owner); @@ -157,9 +147,9 @@ //! [`RefCell`] enforces Rust's borrowing rules at runtime. //! //! ``` +//! use std::cell::RefCell; //! use std::rc::Rc; //! use std::rc::Weak; -//! use std::cell::RefCell; //! //! struct Owner { //! name: String, @@ -177,26 +167,12 @@ //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through //! // a shared reference. -//! let gadget_owner: Rc = Rc::new( -//! Owner { -//! name: "Gadget Man".to_string(), -//! gadgets: RefCell::new(vec![]), -//! } -//! ); +//! let gadget_owner: Rc = +//! Rc::new(Owner { name: "Gadget Man".to_string(), gadgets: RefCell::new(vec![]) }); //! //! // Create `Gadget`s belonging to `gadget_owner`, as before. -//! let gadget1 = Rc::new( -//! Gadget { -//! id: 1, -//! owner: Rc::clone(&gadget_owner), -//! } -//! ); -//! let gadget2 = Rc::new( -//! Gadget { -//! id: 2, -//! owner: Rc::clone(&gadget_owner), -//! } -//! ); +//! let gadget1 = Rc::new(Gadget { id: 1, owner: Rc::clone(&gadget_owner) }); +//! let gadget2 = Rc::new(Gadget { id: 2, owner: Rc::clone(&gadget_owner) }); //! //! // Add the `Gadget`s to their `Owner`. //! { @@ -209,7 +185,6 @@ //! //! // Iterate over our `Gadget`s, printing their details out. //! for gadget_weak in gadget_owner.gadgets.borrow().iter() { -//! //! // `gadget_weak` is a `Weak`. Since `Weak` pointers can't //! // guarantee the allocation still exists, we need to call //! // `upgrade`, which returns an `Option>`. @@ -1095,9 +1070,7 @@ impl Rc { /// use std::rc::Rc; /// /// let mut x = Rc::new(String::new()); - /// unsafe { - /// Rc::get_mut_unchecked(&mut x).push_str("foo") - /// } + /// unsafe { Rc::get_mut_unchecked(&mut x).push_str("foo") } /// assert_eq!(*x, "foo"); /// ``` #[inline] @@ -1154,11 +1127,11 @@ impl Rc { /// /// let mut data = Rc::new(5); /// - /// *Rc::make_mut(&mut data) += 1; // Won't clone anything + /// *Rc::make_mut(&mut data) += 1; // Won't clone anything /// let mut other_data = Rc::clone(&data); // Won't clone inner data - /// *Rc::make_mut(&mut data) += 1; // Clones inner data - /// *Rc::make_mut(&mut data) += 1; // Won't clone anything - /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything + /// *Rc::make_mut(&mut data) += 1; // Clones inner data + /// *Rc::make_mut(&mut data) += 1; // Won't clone anything + /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything /// /// // Now `data` and `other_data` point to different allocations. /// assert_eq!(*data, 8); @@ -1545,11 +1518,11 @@ unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc { /// } /// } /// - /// let foo = Rc::new(Foo); + /// let foo = Rc::new(Foo); /// let foo2 = Rc::clone(&foo); /// - /// drop(foo); // Doesn't print anything - /// drop(foo2); // Prints "dropped!" + /// drop(foo); // Doesn't print anything + /// drop(foo2); // Prints "dropped!" /// ``` fn drop(&mut self) { unsafe { @@ -1719,8 +1692,8 @@ impl PartialOrd for Rc { /// # Examples /// /// ``` - /// use std::rc::Rc; /// use std::cmp::Ordering; + /// use std::rc::Rc; /// /// let five = Rc::new(5); /// @@ -1813,8 +1786,8 @@ impl Ord for Rc { /// # Examples /// /// ``` - /// use std::rc::Rc; /// use std::cmp::Ordering; + /// use std::rc::Rc; /// /// let five = Rc::new(5); /// @@ -2058,9 +2031,11 @@ impl iter::FromIterator for Rc<[T]> { /// /// ```rust /// # use std::rc::Rc; - /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0) + /// let evens: Rc<[u8]> = (0..10) + /// .filter(|&x| x % 2 == 0) /// .collect::>() // The first set of allocations happens here. /// .into(); // A second allocation for `Rc<[T]>` happens here. + /// // /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]); /// ``` /// @@ -2075,6 +2050,7 @@ impl iter::FromIterator for Rc<[T]> { /// ```rust /// # use std::rc::Rc; /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here. + /// // /// # assert_eq!(&*evens, &*(0..10).collect::>()); /// ``` fn from_iter>(iter: I) -> Self { @@ -2206,8 +2182,8 @@ impl Weak { /// # Examples /// /// ``` - /// use std::rc::Rc; /// use std::ptr; + /// use std::rc::Rc; /// /// let strong = Rc::new("hello".to_owned()); /// let weak = Rc::downgrade(&strong); @@ -2487,8 +2463,8 @@ unsafe impl<#[may_dangle] T: ?Sized> Drop for Weak { /// let weak_foo = Rc::downgrade(&foo); /// let other_weak_foo = Weak::clone(&weak_foo); /// - /// drop(weak_foo); // Doesn't print anything - /// drop(foo); // Prints "dropped!" + /// drop(weak_foo); // Doesn't print anything + /// drop(foo); // Prints "dropped!" /// /// assert!(other_weak_foo.upgrade().is_none()); /// ``` diff --git a/library/alloc/src/slice.rs b/library/alloc/src/slice.rs index a5e7bf2a1a9f3..95c3bc3f72796 100644 --- a/library/alloc/src/slice.rs +++ b/library/alloc/src/slice.rs @@ -667,11 +667,15 @@ impl [u8] { /// pub struct Foo(Vec, Vec); /// /// impl std::borrow::Borrow<[u32]> for Foo { -/// fn borrow(&self) -> &[u32] { &self.0 } +/// fn borrow(&self) -> &[u32] { +/// &self.0 +/// } /// } /// /// impl std::borrow::Borrow<[String]> for Foo { -/// fn borrow(&self) -> &[String] { &self.1 } +/// fn borrow(&self) -> &[String] { +/// &self.1 +/// } /// } /// ``` #[unstable(feature = "slice_concat_trait", issue = "27747")] diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index c9ba8921f6ecc..5f3fb8705d256 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -219,7 +219,7 @@ use crate::vec::Vec; /// function which takes a [`&str`] by using an ampersand (`&`): /// /// ``` -/// fn takes_str(s: &str) { } +/// fn takes_str(s: &str) {} /// /// let s = String::from("Hello"); /// @@ -276,7 +276,6 @@ use crate::vec::Vec; /// use std::mem; /// /// let story = String::from("Once upon a time..."); -/// // FIXME Update this when vec_into_raw_parts is stabilized /// // Prevent automatically dropping the String's data /// let mut story = mem::ManuallyDrop::new(story); @@ -420,8 +419,7 @@ pub struct FromUtf8Error { /// /// ``` /// // 𝄞muic -/// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, -/// 0xD800, 0x0069, 0x0063]; +/// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, 0xD800, 0x0069, 0x0063]; /// /// assert!(String::from_utf16(v).is_err()); /// ``` @@ -667,14 +665,11 @@ impl String { /// /// ``` /// // 𝄞music - /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, - /// 0x0073, 0x0069, 0x0063]; - /// assert_eq!(String::from("𝄞music"), - /// String::from_utf16(v).unwrap()); + /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0x0069, 0x0063]; + /// assert_eq!(String::from("𝄞music"), String::from_utf16(v).unwrap()); /// /// // 𝄞muic - /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, - /// 0xD800, 0x0069, 0x0063]; + /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, 0xD800, 0x0069, 0x0063]; /// assert!(String::from_utf16(v).is_err()); /// ``` #[cfg(not(no_global_oom_handling))] @@ -710,12 +705,9 @@ impl String { /// /// ``` /// // 𝄞music - /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, - /// 0x0073, 0xDD1E, 0x0069, 0x0063, - /// 0xD834]; + /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834]; /// - /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"), - /// String::from_utf16_lossy(v)); + /// assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"), String::from_utf16_lossy(v)); /// ``` #[cfg(not(no_global_oom_handling))] #[must_use] @@ -791,7 +783,6 @@ impl String { /// /// unsafe { /// let s = String::from("hello"); - /// // FIXME Update this when vec_into_raw_parts is stabilized /// // Prevent automatically dropping the String's data /// let mut s = mem::ManuallyDrop::new(s); @@ -833,9 +824,7 @@ impl String { /// // some bytes, in a vector /// let sparkle_heart = vec![240, 159, 146, 150]; /// - /// let sparkle_heart = unsafe { - /// String::from_utf8_unchecked(sparkle_heart) - /// }; + /// let sparkle_heart = unsafe { String::from_utf8_unchecked(sparkle_heart) }; /// /// assert_eq!("💖", sparkle_heart); /// ``` diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 81cd770748854..a443ab70d6e8f 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -194,7 +194,6 @@ macro_rules! acquire { /// # Examples /// /// Sharing some immutable data between threads: -/// // Note that we **do not** run these tests here. The windows builders get super // unhappy if a thread outlives the main thread and then exits at the same time // (something deadlocks) so we just avoid this entirely by not running these @@ -219,8 +218,8 @@ macro_rules! acquire { /// [`AtomicUsize`]: core::sync::atomic::AtomicUsize "sync::atomic::AtomicUsize" /// /// ```no_run -/// use std::sync::Arc; /// use std::sync::atomic::{AtomicUsize, Ordering}; +/// use std::sync::Arc; /// use std::thread; /// /// let val = Arc::new(AtomicUsize::new(5)); @@ -1418,11 +1417,11 @@ impl Arc { /// /// let mut data = Arc::new(5); /// - /// *Arc::make_mut(&mut data) += 1; // Won't clone anything + /// *Arc::make_mut(&mut data) += 1; // Won't clone anything /// let mut other_data = Arc::clone(&data); // Won't clone inner data - /// *Arc::make_mut(&mut data) += 1; // Clones inner data - /// *Arc::make_mut(&mut data) += 1; // Won't clone anything - /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything + /// *Arc::make_mut(&mut data) += 1; // Clones inner data + /// *Arc::make_mut(&mut data) += 1; // Won't clone anything + /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything /// /// // Now `data` and `other_data` point to different allocations. /// assert_eq!(*data, 8); @@ -1599,9 +1598,7 @@ impl Arc { /// use std::sync::Arc; /// /// let mut x = Arc::new(String::new()); - /// unsafe { - /// Arc::get_mut_unchecked(&mut x).push_str("foo") - /// } + /// unsafe { Arc::get_mut_unchecked(&mut x).push_str("foo") } /// assert_eq!(*x, "foo"); /// ``` #[inline] @@ -1662,11 +1659,11 @@ unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc { /// } /// } /// - /// let foo = Arc::new(Foo); + /// let foo = Arc::new(Foo); /// let foo2 = Arc::clone(&foo); /// - /// drop(foo); // Doesn't print anything - /// drop(foo2); // Prints "dropped!" + /// drop(foo); // Doesn't print anything + /// drop(foo2); // Prints "dropped!" /// ``` #[inline] fn drop(&mut self) { @@ -1827,8 +1824,8 @@ impl Weak { /// # Examples /// /// ``` - /// use std::sync::Arc; /// use std::ptr; + /// use std::sync::Arc; /// /// let strong = Arc::new("hello".to_owned()); /// let weak = Arc::downgrade(&strong); @@ -2195,8 +2192,8 @@ unsafe impl<#[may_dangle] T: ?Sized> Drop for Weak { /// let weak_foo = Arc::downgrade(&foo); /// let other_weak_foo = Weak::clone(&weak_foo); /// - /// drop(weak_foo); // Doesn't print anything - /// drop(foo); // Prints "dropped!" + /// drop(weak_foo); // Doesn't print anything + /// drop(foo); // Prints "dropped!" /// /// assert!(other_weak_foo.upgrade().is_none()); /// ``` @@ -2311,8 +2308,8 @@ impl PartialOrd for Arc { /// # Examples /// /// ``` - /// use std::sync::Arc; /// use std::cmp::Ordering; + /// use std::sync::Arc; /// /// let five = Arc::new(5); /// @@ -2399,8 +2396,8 @@ impl Ord for Arc { /// # Examples /// /// ``` - /// use std::sync::Arc; /// use std::cmp::Ordering; + /// use std::sync::Arc; /// /// let five = Arc::new(5); /// @@ -2664,9 +2661,11 @@ impl iter::FromIterator for Arc<[T]> { /// /// ```rust /// # use std::sync::Arc; - /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0) + /// let evens: Arc<[u8]> = (0..10) + /// .filter(|&x| x % 2 == 0) /// .collect::>() // The first set of allocations happens here. /// .into(); // A second allocation for `Arc<[T]>` happens here. + /// // /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]); /// ``` /// @@ -2681,6 +2680,7 @@ impl iter::FromIterator for Arc<[T]> { /// ```rust /// # use std::sync::Arc; /// let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here. + /// // /// # assert_eq!(&*evens, &*(0..10).collect::>()); /// ``` fn from_iter>(iter: I) -> Self { diff --git a/library/alloc/src/vec/in_place_collect.rs b/library/alloc/src/vec/in_place_collect.rs index 87d61deb1eb2f..e62a3dce230e9 100644 --- a/library/alloc/src/vec/in_place_collect.rs +++ b/library/alloc/src/vec/in_place_collect.rs @@ -101,10 +101,10 @@ //! # #[allow(dead_code)] //! /// Converts a usize vec into an isize one. //! pub fn cast(vec: Vec) -> Vec { -//! // Does not allocate, free or panic. On optlevel>=2 it does not loop. -//! // Of course this particular case could and should be written with `into_raw_parts` and -//! // `from_raw_parts` instead. -//! vec.into_iter().map(|u| u as isize).collect() +//! // Does not allocate, free or panic. On optlevel>=2 it does not loop. +//! // Of course this particular case could and should be written with `into_raw_parts` and +//! // `from_raw_parts` instead. +//! vec.into_iter().map(|u| u as isize).collect() //! } //! ``` //! @@ -114,26 +114,27 @@ //! /// returns an empty Vec backed by the original allocation. Otherwise it returns a new //! /// empty vec. //! pub fn recycle_allocation(src: Vec) -> Vec { -//! src.into_iter().filter_map(|_| None).collect() +//! src.into_iter().filter_map(|_| None).collect() //! } //! ``` //! //! ```rust //! let vec = vec![13usize; 1024]; -//! let _ = vec.into_iter() -//! .enumerate() -//! .filter_map(|(idx, val)| if idx % 2 == 0 { Some(val+idx) } else {None}) -//! .collect::>(); +//! let _ = vec +//! .into_iter() +//! .enumerate() +//! .filter_map(|(idx, val)| if idx % 2 == 0 { Some(val + idx) } else { None }) +//! .collect::>(); //! //! // is equivalent to the following, but doesn't require bounds checks //! //! let mut vec = vec![13usize; 1024]; //! let mut write_idx = 0; //! for idx in 0..vec.len() { -//! if idx % 2 == 0 { -//! vec[write_idx] = vec[idx] + idx; -//! write_idx += 1; -//! } +//! if idx % 2 == 0 { +//! vec[write_idx] = vec[idx] + idx; +//! write_idx += 1; +//! } //! } //! vec.truncate(write_idx); //! ``` diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 834c8f58cb2a9..13f55f4d8240a 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -535,7 +535,6 @@ impl Vec { /// use std::mem; /// /// let v = vec![1, 2, 3]; - /// // FIXME Update this when vec_into_raw_parts is stabilized /// // Prevent running `v`'s destructor so we are in complete control /// // of the allocation. @@ -730,7 +729,6 @@ impl Vec { /// v.push(1); /// v.push(2); /// v.push(3); - /// // FIXME Update this when vec_into_raw_parts is stabilized /// // Prevent running `v`'s destructor so we are in complete control /// // of the allocation. @@ -1350,9 +1348,7 @@ impl Vec { /// the inner vectors were not freed prior to the `set_len` call: /// /// ``` - /// let mut vec = vec![vec![1, 0, 0], - /// vec![0, 1, 0], - /// vec![0, 0, 1]]; + /// let mut vec = vec![vec![1, 0, 0], vec![0, 1, 0], vec![0, 0, 1]]; /// // SAFETY: /// // 1. `old_len..0` is empty so no elements need to be initialized. /// // 2. `0 <= capacity` always holds whatever `capacity` is. @@ -1571,11 +1567,13 @@ impl Vec { /// /// ``` /// let mut vec = vec![1, 2, 3, 4]; - /// vec.retain_mut(|x| if *x <= 3 { - /// *x += 1; - /// true - /// } else { - /// false + /// vec.retain_mut(|x| { + /// if *x <= 3 { + /// *x += 1; + /// true + /// } else { + /// false + /// } /// }); /// assert_eq!(vec, [2, 3, 4]); /// ``` @@ -1858,7 +1856,7 @@ impl Vec { /// #![feature(vec_push_within_capacity)] /// /// use std::collections::TryReserveError; - /// fn from_iter_fallible(iter: impl Iterator) -> Result, TryReserveError> { + /// fn from_iter_fallible(iter: impl Iterator) -> Result, TryReserveError> { /// let mut vec = Vec::new(); /// for value in iter { /// if let Err(value) = vec.push_within_capacity(value) { @@ -2152,7 +2150,10 @@ impl Vec { /// /// let mut vec = vec![]; /// let mut p = 1; - /// vec.resize_with(4, || { p *= 2; p }); + /// vec.resize_with(4, || { + /// p *= 2; + /// p + /// }); /// assert_eq!(vec, [2, 4, 8, 16]); /// ``` #[cfg(not(no_global_oom_handling))] diff --git a/library/core/benches/num/int_log/mod.rs b/library/core/benches/num/int_log/mod.rs index 3c01e2998cd2f..996d244cc5c0c 100644 --- a/library/core/benches/num/int_log/mod.rs +++ b/library/core/benches/num/int_log/mod.rs @@ -18,7 +18,7 @@ macro_rules! int_log_bench { #[bench] fn $random(bench: &mut Bencher) { let mut rng = crate::bench_rng(); - /* Exponentially distributed random numbers from the whole range of the type. */ + /* Exponentially distributed random numbers from the whole range of the type. */ let numbers: Vec<$t> = (0..256) .map(|_| { let x = rng.gen::<$t>() >> rng.gen_range(0, <$t>::BITS); @@ -35,7 +35,7 @@ macro_rules! int_log_bench { #[bench] fn $random_small(bench: &mut Bencher) { let mut rng = crate::bench_rng(); - /* Exponentially distributed random numbers from the range 0..256. */ + /* Exponentially distributed random numbers from the range 0..256. */ let numbers: Vec<$t> = (0..256) .map(|_| { let x = (rng.gen::() >> rng.gen_range(0, u8::BITS)) as $t; diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 1a379ecc11c01..b2322e2e66768 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -48,8 +48,8 @@ //! use runtime reflection instead. //! //! ```rust -//! use std::fmt::Debug; //! use std::any::Any; +//! use std::fmt::Debug; //! //! // Logger function for any type that implements Debug. //! fn log(value: &T) { @@ -111,7 +111,7 @@ //! //! ``` //! # #![feature(provide_any)] -//! use std::any::{Provider, Demand, request_ref}; +//! use std::any::{request_ref, Demand, Provider}; //! //! // Definition of MyTrait, a data provider. //! trait MyTrait: Provider { @@ -790,13 +790,12 @@ pub trait Provider { /// /// ```rust /// # #![feature(provide_any)] - /// use std::any::{Provider, Demand}; + /// use std::any::{Demand, Provider}; /// # struct SomeConcreteType { field: String, num_field: i32 } /// /// impl Provider for SomeConcreteType { /// fn provide<'a>(&'a self, demand: &mut Demand<'a>) { - /// demand.provide_ref::(&self.field) - /// .provide_value::(self.num_field); + /// demand.provide_ref::(&self.field).provide_value::(self.num_field); /// } /// } /// ``` @@ -812,7 +811,7 @@ pub trait Provider { /// /// ```rust /// # #![feature(provide_any)] -/// use std::any::{Provider, request_value}; +/// use std::any::{request_value, Provider}; /// /// fn get_string(provider: &impl Provider) -> String { /// request_value::(provider).unwrap() @@ -834,7 +833,7 @@ where /// /// ```rust /// # #![feature(provide_any)] -/// use std::any::{Provider, request_ref}; +/// use std::any::{request_ref, Provider}; /// /// fn get_str(provider: &impl Provider) -> &str { /// request_ref::(provider).unwrap() @@ -886,7 +885,7 @@ impl<'a> Demand<'a> { /// ```rust /// #![feature(provide_any)] /// - /// use std::any::{Provider, Demand}; + /// use std::any::{Demand, Provider}; /// # struct SomeConcreteType { field: u8 } /// /// impl Provider for SomeConcreteType { @@ -912,7 +911,7 @@ impl<'a> Demand<'a> { /// ```rust /// #![feature(provide_any)] /// - /// use std::any::{Provider, Demand}; + /// use std::any::{Demand, Provider}; /// # struct SomeConcreteType { field: String } /// /// impl Provider for SomeConcreteType { @@ -939,7 +938,7 @@ impl<'a> Demand<'a> { /// ```rust /// #![feature(provide_any)] /// - /// use std::any::{Provider, Demand}; + /// use std::any::{Demand, Provider}; /// # struct SomeConcreteType { field: String } /// /// impl Provider for SomeConcreteType { @@ -963,18 +962,14 @@ impl<'a> Demand<'a> { /// ```rust /// #![feature(provide_any)] /// - /// use std::any::{Provider, Demand}; + /// use std::any::{Demand, Provider}; /// # struct SomeConcreteType { business: String, party: String } /// # fn today_is_a_weekday() -> bool { true } /// /// impl Provider for SomeConcreteType { /// fn provide<'a>(&'a self, demand: &mut Demand<'a>) { /// demand.provide_ref_with::(|| { - /// if today_is_a_weekday() { - /// &self.business - /// } else { - /// &self.party - /// } + /// if today_is_a_weekday() { &self.business } else { &self.party } /// }); /// } /// } @@ -1021,7 +1016,7 @@ impl<'a> Demand<'a> { /// ```rust /// #![feature(provide_any)] /// - /// use std::any::{Provider, Demand}; + /// use std::any::{Demand, Provider}; /// /// struct Parent(Option); /// @@ -1092,7 +1087,7 @@ impl<'a> Demand<'a> { /// ```rust /// #![feature(provide_any)] /// - /// use std::any::{Provider, Demand}; + /// use std::any::{Demand, Provider}; /// /// struct Parent(Option); /// diff --git a/library/core/src/array/iter.rs b/library/core/src/array/iter.rs index b91c630183d4f..82eda55cde2c4 100644 --- a/library/core/src/array/iter.rs +++ b/library/core/src/array/iter.rs @@ -194,11 +194,7 @@ impl IntoIter { /// use std::array::IntoIter; /// /// pub fn get_bytes(b: bool) -> IntoIter { - /// if b { - /// [1, 2, 3, 4].into_iter() - /// } else { - /// IntoIter::empty() - /// } + /// if b { [1, 2, 3, 4].into_iter() } else { IntoIter::empty() } /// } /// /// assert_eq!(get_bytes(true).collect::>(), vec![1, 2, 3, 4]); diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index eae0e1c761866..a3cd04e8eaebc 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -490,7 +490,10 @@ impl [T; N] { /// /// let x = [1, 2, 3]; /// let mut temp = 0; - /// let y = x.map(|v| { temp += 1; v * temp }); + /// let y = x.map(|v| { + /// temp += 1; + /// v * temp + /// }); /// assert_eq!(y, [1, 4, 9]); /// /// let x = ["Ferris", "Bueller's", "Day", "Off"]; @@ -660,9 +663,9 @@ impl [T; N] { /// let v = [1, 2, 3, 4, 5, 6]; /// /// { - /// let (left, right) = v.split_array_ref::<0>(); - /// assert_eq!(left, &[]); - /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]); + /// let (left, right) = v.split_array_ref::<0>(); + /// assert_eq!(left, &[]); + /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]); /// } /// /// { @@ -738,9 +741,9 @@ impl [T; N] { /// let v = [1, 2, 3, 4, 5, 6]; /// /// { - /// let (left, right) = v.rsplit_array_ref::<0>(); - /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]); - /// assert_eq!(right, &[]); + /// let (left, right) = v.rsplit_array_ref::<0>(); + /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]); + /// assert_eq!(right, &[]); /// } /// /// { diff --git a/library/core/src/async_iter/mod.rs b/library/core/src/async_iter/mod.rs index 0c6f637711b37..036624c04f28c 100644 --- a/library/core/src/async_iter/mod.rs +++ b/library/core/src/async_iter/mod.rs @@ -101,11 +101,7 @@ //! self.count += 1; //! //! // Check to see if we've finished counting or not. -//! if self.count < 6 { -//! Poll::Ready(Some(self.count)) -//! } else { -//! Poll::Ready(None) -//! } +//! if self.count < 6 { Poll::Ready(Some(self.count)) } else { Poll::Ready(None) } //! } //! } //! ``` diff --git a/library/core/src/bool.rs b/library/core/src/bool.rs index db1c505ba3851..7102396eaf20f 100644 --- a/library/core/src/bool.rs +++ b/library/core/src/bool.rs @@ -21,7 +21,9 @@ impl bool { /// /// ``` /// let mut a = 0; - /// let mut function_with_side_effects = || { a += 1; }; + /// let mut function_with_side_effects = || { + /// a += 1; + /// }; /// /// true.then_some(function_with_side_effects()); /// false.then_some(function_with_side_effects()); @@ -53,8 +55,12 @@ impl bool { /// ``` /// let mut a = 0; /// - /// true.then(|| { a += 1; }); - /// false.then(|| { a += 1; }); + /// true.then(|| { + /// a += 1; + /// }); + /// false.then(|| { + /// a += 1; + /// }); /// /// // `a` is incremented once because the closure is evaluated lazily by /// // `then`. diff --git a/library/core/src/borrow.rs b/library/core/src/borrow.rs index fdd56cb4eaa8e..d6d7fb3911f69 100644 --- a/library/core/src/borrow.rs +++ b/library/core/src/borrow.rs @@ -70,7 +70,8 @@ /// /// impl HashMap { /// pub fn insert(&self, key: K, value: V) -> Option -/// where K: Hash + Eq +/// where +/// K: Hash + Eq, /// { /// # unimplemented!() /// // ... @@ -79,7 +80,7 @@ /// pub fn get(&self, k: &Q) -> Option<&V> /// where /// K: Borrow, -/// Q: Hash + Eq + ?Sized +/// Q: Hash + Eq + ?Sized, /// { /// # unimplemented!() /// // ... @@ -124,7 +125,7 @@ /// } /// } /// -/// impl Eq for CaseInsensitiveString { } +/// impl Eq for CaseInsensitiveString {} /// ``` /// /// Because two equal values need to produce the same hash value, the diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index f2975d054572c..144b150c5acd2 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -106,14 +106,12 @@ //! //! struct Graph { //! edges: Vec<(i32, i32)>, -//! span_tree_cache: RefCell>> +//! span_tree_cache: RefCell>>, //! } //! //! impl Graph { //! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> { -//! self.span_tree_cache.borrow_mut() -//! .get_or_insert_with(|| self.calc_span_tree()) -//! .clone() +//! self.span_tree_cache.borrow_mut().get_or_insert_with(|| self.calc_span_tree()).clone() //! } //! //! fn calc_span_tree(&self) -> Vec<(i32, i32)> { @@ -133,9 +131,9 @@ //! //! ``` //! use std::cell::Cell; -//! use std::ptr::NonNull; -//! use std::process::abort; //! use std::marker::PhantomData; +//! use std::process::abort; +//! use std::ptr::NonNull; //! //! struct Rc { //! ptr: NonNull>, @@ -151,15 +149,11 @@ //! impl Clone for Rc { //! fn clone(&self) -> Rc { //! self.inc_strong(); -//! Rc { -//! ptr: self.ptr, -//! phantom: PhantomData, -//! } +//! Rc { ptr: self.ptr, phantom: PhantomData } //! } //! } //! //! trait RcBoxPtr { -//! //! fn inner(&self) -> &RcBox; //! //! fn strong(&self) -> usize { @@ -167,20 +161,14 @@ //! } //! //! fn inc_strong(&self) { -//! self.inner() -//! .strong -//! .set(self.strong() -//! .checked_add(1) -//! .unwrap_or_else(|| abort() )); +//! self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| abort())); //! } //! } //! //! impl RcBoxPtr for Rc { -//! fn inner(&self) -> &RcBox { -//! unsafe { -//! self.ptr.as_ref() -//! } -//! } +//! fn inner(&self) -> &RcBox { +//! unsafe { self.ptr.as_ref() } +//! } //! } //! ``` //! @@ -222,10 +210,7 @@ pub use once::OnceCell; /// special_field: Cell, /// } /// -/// let my_struct = SomeStruct { -/// regular_field: 0, -/// special_field: Cell::new(1), -/// }; +/// let my_struct = SomeStruct { regular_field: 0, special_field: Cell::new(1) }; /// /// let new_value = 100; /// @@ -1374,7 +1359,7 @@ impl<'b, T: ?Sized> Ref<'b, T> { /// # Examples /// /// ``` - /// use std::cell::{RefCell, Ref}; + /// use std::cell::{Ref, RefCell}; /// /// let c = RefCell::new((5, 'b')); /// let b1: Ref<(u32, char)> = c.borrow(); @@ -1403,7 +1388,7 @@ impl<'b, T: ?Sized> Ref<'b, T> { /// # Examples /// /// ``` - /// use std::cell::{RefCell, Ref}; + /// use std::cell::{Ref, RefCell}; /// /// let c = RefCell::new(vec![1, 2, 3]); /// let b1: Ref> = c.borrow(); @@ -1471,7 +1456,7 @@ impl<'b, T: ?Sized> Ref<'b, T> { /// /// ``` /// #![feature(cell_leak)] - /// use std::cell::{RefCell, Ref}; + /// use std::cell::{Ref, RefCell}; /// let cell = RefCell::new(0); /// /// let value = Ref::leak(cell.borrow()); @@ -1838,10 +1823,10 @@ impl fmt::Display for RefMut<'_, T> { /// ```rust,no_run /// # use std::cell::UnsafeCell; /// unsafe fn not_allowed(ptr: &UnsafeCell) -> &mut T { -/// let t = ptr as *const UnsafeCell as *mut T; -/// // This is undefined behavior, because the `*mut T` pointer -/// // was not obtained through `.get()` nor `.raw_get()`: -/// unsafe { &mut *t } +/// let t = ptr as *const UnsafeCell as *mut T; +/// // This is undefined behavior, because the `*mut T` pointer +/// // was not obtained through `.get()` nor `.raw_get()`: +/// unsafe { &mut *t } /// } /// ``` /// @@ -1852,7 +1837,7 @@ impl fmt::Display for RefMut<'_, T> { /// // Safety: the caller must ensure that there are no references that /// // point to the *contents* of the `UnsafeCell`. /// unsafe fn get_mut(ptr: &UnsafeCell) -> &mut T { -/// unsafe { &mut *ptr.get() } +/// unsafe { &mut *ptr.get() } /// } /// ``` /// @@ -1862,9 +1847,9 @@ impl fmt::Display for RefMut<'_, T> { /// ```rust /// # use std::cell::UnsafeCell; /// fn get_shared(ptr: &mut T) -> &UnsafeCell { -/// let t = ptr as *mut T as *const UnsafeCell; -/// // SAFETY: `T` and `UnsafeCell` have the same memory layout -/// unsafe { &*t } +/// let t = ptr as *mut T as *const UnsafeCell; +/// // SAFETY: `T` and `UnsafeCell` have the same memory layout +/// unsafe { &*t } /// } /// ``` /// @@ -1905,8 +1890,8 @@ impl fmt::Display for RefMut<'_, T> { /// /// ```rust /// #![forbid(unsafe_code)] // with exclusive accesses, -/// // `UnsafeCell` is a transparent no-op wrapper, -/// // so no need for `unsafe` here. +/// // `UnsafeCell` is a transparent no-op wrapper, +/// // so no need for `unsafe` here. /// use std::cell::UnsafeCell; /// /// let mut x: UnsafeCell = 42.into(); @@ -2041,7 +2026,9 @@ impl UnsafeCell { /// use std::mem::MaybeUninit; /// /// let m = MaybeUninit::>::uninit(); - /// unsafe { UnsafeCell::raw_get(m.as_ptr()).write(5); } + /// unsafe { + /// UnsafeCell::raw_get(m.as_ptr()).write(5); + /// } /// let uc = unsafe { m.assume_init() }; /// /// assert_eq!(uc.into_inner(), 5); diff --git a/library/core/src/cell/once.rs b/library/core/src/cell/once.rs index 3c39394dd8c8e..9281aefe2b397 100644 --- a/library/core/src/cell/once.rs +++ b/library/core/src/cell/once.rs @@ -17,9 +17,7 @@ use crate::mem; /// let cell = OnceCell::new(); /// assert!(cell.get().is_none()); /// -/// let value: &String = cell.get_or_init(|| { -/// "Hello, World!".to_string() -/// }); +/// let value: &String = cell.get_or_init(|| "Hello, World!".to_string()); /// assert_eq!(value, "Hello, World!"); /// assert!(cell.get().is_some()); /// ``` @@ -149,9 +147,7 @@ impl OnceCell { /// let cell = OnceCell::new(); /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); /// assert!(cell.get().is_none()); - /// let value = cell.get_or_try_init(|| -> Result { - /// Ok(92) - /// }); + /// let value = cell.get_or_try_init(|| -> Result { Ok(92) }); /// assert_eq!(value, Ok(&92)); /// assert_eq!(cell.get(), Some(&92)) /// ``` diff --git a/library/core/src/char/methods.rs b/library/core/src/char/methods.rs index bb83599369c13..26008a0698f74 100644 --- a/library/core/src/char/methods.rs +++ b/library/core/src/char/methods.rs @@ -56,21 +56,11 @@ impl char { /// use std::char::decode_utf16; /// /// // 𝄞music - /// let v = [ - /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834, - /// ]; + /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834]; /// /// assert_eq!( - /// decode_utf16(v) - /// .map(|r| r.map_err(|e| e.unpaired_surrogate())) - /// .collect::>(), - /// vec![ - /// Ok('𝄞'), - /// Ok('m'), Ok('u'), Ok('s'), - /// Err(0xDD1E), - /// Ok('i'), Ok('c'), - /// Err(0xD834) - /// ] + /// decode_utf16(v).map(|r| r.map_err(|e| e.unpaired_surrogate())).collect::>(), + /// vec![Ok('𝄞'), Ok('m'), Ok('u'), Ok('s'), Err(0xDD1E), Ok('i'), Ok('c'), Err(0xD834)] /// ); /// ``` /// @@ -80,14 +70,10 @@ impl char { /// use std::char::{decode_utf16, REPLACEMENT_CHARACTER}; /// /// // 𝄞music - /// let v = [ - /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834, - /// ]; + /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834]; /// /// assert_eq!( - /// decode_utf16(v) - /// .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)) - /// .collect::(), + /// decode_utf16(v).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect::(), /// "𝄞mus�ic�" /// ); /// ``` diff --git a/library/core/src/clone.rs b/library/core/src/clone.rs index 06dca7e59a2a6..da369ebbfb450 100644 --- a/library/core/src/clone.rs +++ b/library/core/src/clone.rs @@ -24,13 +24,13 @@ //! ``` //! #[derive(Clone)] // we add the Clone trait to Morpheus struct //! struct Morpheus { -//! blue_pill: f32, -//! red_pill: i64, +//! blue_pill: f32, +//! red_pill: i64, //! } //! //! fn main() { -//! let f = Morpheus { blue_pill: 0.0, red_pill: 0 }; -//! let copy = f.clone(); // and now we can clone it! +//! let f = Morpheus { blue_pill: 0.0, red_pill: 0 }; +//! let copy = f.clone(); // and now we can clone it! //! } //! ``` diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index f0fa2e1d2c190..15fc80398c69f 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -264,7 +264,11 @@ pub macro PartialEq($item:item) { /// `Eq`, which has no methods: /// /// ``` -/// enum BookFormat { Paperback, Hardback, Ebook } +/// enum BookFormat { +/// Paperback, +/// Hardback, +/// Ebook, +/// } /// struct Book { /// isbn: i32, /// format: BookFormat, diff --git a/library/core/src/convert/mod.rs b/library/core/src/convert/mod.rs index 33493964bad2e..39e17f7e00103 100644 --- a/library/core/src/convert/mod.rs +++ b/library/core/src/convert/mod.rs @@ -203,7 +203,7 @@ pub const fn identity(x: T) -> T { /// /// ``` /// fn is_hello>(s: T) { -/// assert_eq!("hello", s.as_ref()); +/// assert_eq!("hello", s.as_ref()); /// } /// /// let s = "hello"; @@ -338,7 +338,7 @@ pub trait AsRef { /// // functionality, helps to minimize monomorphization overhead. /// fn doit(data: &mut Vec) { /// let len = data.len(); -/// if len == 0 || data[len-1] != 0 { +/// if len == 0 || data[len - 1] != 0 { /// data.push(0); /// } /// } @@ -351,10 +351,7 @@ pub trait AsRef { /// assert_eq!(v, [6, 7, 8]); /// null_terminate(&mut v); /// assert_eq!(v, [6, 7, 8, 0]); -/// let mut doc = Document { -/// info: String::from("Example"), -/// content: vec![17, 19, 8], -/// }; +/// let mut doc = Document { info: String::from("Example"), content: vec![17, 19, 8] }; /// caesar(&mut doc, 1); /// assert_eq!(doc.content, [18, 20, 9]); /// null_terminate(&mut doc); @@ -431,8 +428,8 @@ pub trait AsMut { /// /// ``` /// fn is_hello>>(s: T) { -/// let bytes = b"hello".to_vec(); -/// assert_eq!(bytes, s.into()); +/// let bytes = b"hello".to_vec(); +/// assert_eq!(bytes, s.into()); /// } /// /// let s = "hello".to_string(); diff --git a/library/core/src/default.rs b/library/core/src/default.rs index a5b4e965552c0..6ccdd9476afdf 100644 --- a/library/core/src/default.rs +++ b/library/core/src/default.rs @@ -83,7 +83,9 @@ /// } /// /// impl Default for Kind { -/// fn default() -> Self { Kind::A } +/// fn default() -> Self { +/// Kind::A +/// } /// } /// ``` /// @@ -127,7 +129,9 @@ pub trait Default: Sized { /// } /// /// impl Default for Kind { - /// fn default() -> Self { Kind::A } + /// fn default() -> Self { + /// Kind::A + /// } /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -163,13 +167,7 @@ pub trait Default: Sized { /// } /// /// fn main() { -/// let options = AppConfig { -/// foo: default(), -/// bar: BarConfig { -/// bar: 10.1, -/// ..default() -/// }, -/// }; +/// let options = AppConfig { foo: default(), bar: BarConfig { bar: 10.1, ..default() } }; /// } /// ``` #[unstable(feature = "default_free_fn", issue = "73014")] diff --git a/library/core/src/error.rs b/library/core/src/error.rs index b24ca037d1afc..816be3cbca8ec 100644 --- a/library/core/src/error.rs +++ b/library/core/src/error.rs @@ -130,8 +130,8 @@ pub trait Error: Debug + Display { /// ```rust /// #![feature(provide_any)] /// #![feature(error_generic_member_access)] - /// use core::fmt; /// use core::any::Demand; + /// use core::fmt; /// /// #[derive(Debug)] /// struct MyBacktrace { diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index 15dd9ea7e8036..975c7dd3f64f2 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -148,7 +148,6 @@ impl FromBytesWithNulError { /// within the slice. /// /// This error is created by the [`CStr::from_bytes_until_nul`] method. -/// #[derive(Clone, PartialEq, Eq, Debug)] #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")] pub struct FromBytesUntilNulError(()); @@ -321,7 +320,6 @@ impl CStr { /// let c_str = CStr::from_bytes_until_nul(&buffer[..]).unwrap(); /// assert_eq!(c_str.to_str().unwrap(), "AAAAAAAA"); /// ``` - /// #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")] #[rustc_const_unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")] pub const fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError> { diff --git a/library/core/src/fmt/builders.rs b/library/core/src/fmt/builders.rs index 7da49b04aaae9..8283fc4d5c12c 100644 --- a/library/core/src/fmt/builders.rs +++ b/library/core/src/fmt/builders.rs @@ -61,10 +61,7 @@ impl fmt::Write for PadAdapter<'_, '_> { /// /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { -/// fmt.debug_struct("Foo") -/// .field("bar", &self.bar) -/// .field("baz", &self.baz) -/// .finish() +/// fmt.debug_struct("Foo").field("bar", &self.bar).field("baz", &self.baz).finish() /// } /// } /// @@ -106,11 +103,11 @@ impl<'a, 'b: 'a> DebugStruct<'a, 'b> { /// impl fmt::Debug for Bar { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { /// fmt.debug_struct("Bar") - /// .field("bar", &self.bar) // We add `bar` field. - /// .field("another", &self.another) // We add `another` field. - /// // We even add a field which doesn't exist (because why not?). - /// .field("not_existing_field", &1) - /// .finish() // We're good to go! + /// .field("bar", &self.bar) // We add `bar` field. + /// .field("another", &self.another) // We add `another` field. + /// // We even add a field which doesn't exist (because why not?). + /// .field("not_existing_field", &1) + /// .finish() // We're good to go! /// } /// } /// @@ -250,17 +247,11 @@ impl<'a, 'b: 'a> DebugStruct<'a, 'b> { /// /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { -/// fmt.debug_tuple("Foo") -/// .field(&self.0) -/// .field(&self.1) -/// .finish() +/// fmt.debug_tuple("Foo").field(&self.0).field(&self.1).finish() /// } /// } /// -/// assert_eq!( -/// format!("{:?}", Foo(10, "Hello World".to_string())), -/// "Foo(10, \"Hello World\")", -/// ); +/// assert_eq!(format!("{:?}", Foo(10, "Hello World".to_string())), "Foo(10, \"Hello World\")",); /// ``` #[must_use = "must eventually call `finish()` on Debug builders"] #[allow(missing_debug_implementations)] @@ -293,16 +284,13 @@ impl<'a, 'b: 'a> DebugTuple<'a, 'b> { /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { /// fmt.debug_tuple("Foo") - /// .field(&self.0) // We add the first field. - /// .field(&self.1) // We add the second field. - /// .finish() // We're good to go! + /// .field(&self.0) // We add the first field. + /// .field(&self.1) // We add the second field. + /// .finish() // We're good to go! /// } /// } /// - /// assert_eq!( - /// format!("{:?}", Foo(10, "Hello World".to_string())), - /// "Foo(10, \"Hello World\")", - /// ); + /// assert_eq!(format!("{:?}", Foo(10, "Hello World".to_string())), "Foo(10, \"Hello World\")",); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn field(&mut self, value: &dyn fmt::Debug) -> &mut Self { @@ -423,10 +411,7 @@ impl<'a, 'b: 'a> DebugInner<'a, 'b> { /// } /// } /// -/// assert_eq!( -/// format!("{:?}", Foo(vec![10, 11])), -/// "{10, 11}", -/// ); +/// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}",); /// ``` #[must_use = "must eventually call `finish()` on Debug builders"] #[allow(missing_debug_implementations)] @@ -453,16 +438,13 @@ impl<'a, 'b: 'a> DebugSet<'a, 'b> { /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { /// fmt.debug_set() - /// .entry(&self.0) // Adds the first "entry". - /// .entry(&self.1) // Adds the second "entry". - /// .finish() + /// .entry(&self.0) // Adds the first "entry". + /// .entry(&self.1) // Adds the second "entry". + /// .finish() /// } /// } /// - /// assert_eq!( - /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])), - /// "{[10, 11], [12, 13]}", - /// ); + /// assert_eq!(format!("{:?}", Foo(vec![10, 11], vec![12, 13])), "{[10, 11], [12, 13]}",); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut Self { @@ -482,16 +464,13 @@ impl<'a, 'b: 'a> DebugSet<'a, 'b> { /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { /// fmt.debug_set() - /// .entries(self.0.iter()) // Adds the first "entry". - /// .entries(self.1.iter()) // Adds the second "entry". - /// .finish() + /// .entries(self.0.iter()) // Adds the first "entry". + /// .entries(self.1.iter()) // Adds the second "entry". + /// .finish() /// } /// } /// - /// assert_eq!( - /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])), - /// "{10, 11, 12, 13}", - /// ); + /// assert_eq!(format!("{:?}", Foo(vec![10, 11], vec![12, 13])), "{10, 11, 12, 13}",); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn entries(&mut self, entries: I) -> &mut Self @@ -516,16 +495,11 @@ impl<'a, 'b: 'a> DebugSet<'a, 'b> { /// /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - /// fmt.debug_set() - /// .entries(self.0.iter()) - /// .finish() // Ends the struct formatting. + /// fmt.debug_set().entries(self.0.iter()).finish() // Ends the struct formatting. /// } /// } /// - /// assert_eq!( - /// format!("{:?}", Foo(vec![10, 11])), - /// "{10, 11}", - /// ); + /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}",); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn finish(&mut self) -> fmt::Result { @@ -553,10 +527,7 @@ impl<'a, 'b: 'a> DebugSet<'a, 'b> { /// } /// } /// -/// assert_eq!( -/// format!("{:?}", Foo(vec![10, 11])), -/// "[10, 11]", -/// ); +/// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]",); /// ``` #[must_use = "must eventually call `finish()` on Debug builders"] #[allow(missing_debug_implementations)] @@ -583,16 +554,13 @@ impl<'a, 'b: 'a> DebugList<'a, 'b> { /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { /// fmt.debug_list() - /// .entry(&self.0) // We add the first "entry". - /// .entry(&self.1) // We add the second "entry". - /// .finish() + /// .entry(&self.0) // We add the first "entry". + /// .entry(&self.1) // We add the second "entry". + /// .finish() /// } /// } /// - /// assert_eq!( - /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])), - /// "[[10, 11], [12, 13]]", - /// ); + /// assert_eq!(format!("{:?}", Foo(vec![10, 11], vec![12, 13])), "[[10, 11], [12, 13]]",); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut Self { @@ -611,17 +579,11 @@ impl<'a, 'b: 'a> DebugList<'a, 'b> { /// /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - /// fmt.debug_list() - /// .entries(self.0.iter()) - /// .entries(self.1.iter()) - /// .finish() + /// fmt.debug_list().entries(self.0.iter()).entries(self.1.iter()).finish() /// } /// } /// - /// assert_eq!( - /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])), - /// "[10, 11, 12, 13]", - /// ); + /// assert_eq!(format!("{:?}", Foo(vec![10, 11], vec![12, 13])), "[10, 11, 12, 13]",); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn entries(&mut self, entries: I) -> &mut Self @@ -646,16 +608,11 @@ impl<'a, 'b: 'a> DebugList<'a, 'b> { /// /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - /// fmt.debug_list() - /// .entries(self.0.iter()) - /// .finish() // Ends the struct formatting. + /// fmt.debug_list().entries(self.0.iter()).finish() // Ends the struct formatting. /// } /// } /// - /// assert_eq!( - /// format!("{:?}", Foo(vec![10, 11])), - /// "[10, 11]", - /// ); + /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]",); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn finish(&mut self) -> fmt::Result { @@ -718,8 +675,8 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { /// fmt.debug_map() - /// .entry(&"whole", &self.0) // We add the "whole" entry. - /// .finish() + /// .entry(&"whole", &self.0) // We add the "whole" entry. + /// .finish() /// } /// } /// @@ -754,8 +711,9 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { /// fmt.debug_map() - /// .key(&"whole").value(&self.0) // We add the "whole" entry. - /// .finish() + /// .key(&"whole") + /// .value(&self.0) // We add the "whole" entry. + /// .finish() /// } /// } /// @@ -818,8 +776,9 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { /// fmt.debug_map() - /// .key(&"whole").value(&self.0) // We add the "whole" entry. - /// .finish() + /// .key(&"whole") + /// .value(&self.0) // We add the "whole" entry. + /// .finish() /// } /// } /// @@ -862,10 +821,10 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { /// fmt.debug_map() - /// // We map our vec so each entries' first field will become - /// // the "key". - /// .entries(self.0.iter().map(|&(ref k, ref v)| (k, v))) - /// .finish() + /// // We map our vec so each entries' first field will become + /// // the "key". + /// .entries(self.0.iter().map(|&(ref k, ref v)| (k, v))) + /// .finish() /// } /// } /// diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index c8d2855056757..726b661a84825 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -55,7 +55,7 @@ pub mod rt { /// struct Triangle { /// a: f32, /// b: f32, -/// c: f32 +/// c: f32, /// } /// /// impl fmt::Display for Triangle { @@ -493,7 +493,8 @@ impl<'a> Arguments<'a> { /// ```rust /// use std::fmt::Arguments; /// - /// fn write_str(_: &str) { /* ... */ } + /// fn write_str(_: &str) { /* ... */ + /// } /// /// fn write_fmt(args: &Arguments) { /// if let Some(s) = args.as_str() { @@ -589,10 +590,7 @@ impl Display for Arguments<'_> { /// /// impl fmt::Debug for Point { /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -/// f.debug_struct("Point") -/// .field("x", &self.x) -/// .field("y", &self.y) -/// .finish() +/// f.debug_struct("Point").field("x", &self.x).field("y", &self.y).finish() /// } /// } /// @@ -639,11 +637,13 @@ impl Display for Arguments<'_> { /// /// let origin = Point { x: 0, y: 0 }; /// -/// assert_eq!(format!("The origin is: {origin:#?}"), -/// "The origin is: Point { +/// assert_eq!( +/// format!("The origin is: {origin:#?}"), +/// "The origin is: Point { /// x: 0, /// y: 0, -/// }"); +/// }" +/// ); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -674,20 +674,20 @@ pub trait Debug { /// /// impl fmt::Debug for Position { /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - /// f.debug_tuple("") - /// .field(&self.longitude) - /// .field(&self.latitude) - /// .finish() + /// f.debug_tuple("").field(&self.longitude).field(&self.latitude).finish() /// } /// } /// /// let position = Position { longitude: 1.987, latitude: 2.983 }; /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)"); /// - /// assert_eq!(format!("{position:#?}"), "( + /// assert_eq!( + /// format!("{position:#?}"), + /// "( /// 1.987, /// 2.983, - /// )"); + /// )" + /// ); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn fmt(&self, f: &mut Formatter<'_>) -> Result; @@ -778,8 +778,7 @@ pub trait Display { /// } /// } /// - /// assert_eq!("(1.987, 2.983)", - /// format!("{}", Position { longitude: 1.987, latitude: 2.983, })); + /// assert_eq!("(1.987, 2.983)", format!("{}", Position { longitude: 1.987, latitude: 2.983 })); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn fmt(&self, f: &mut Formatter<'_>) -> Result; @@ -1092,10 +1091,7 @@ pub trait Pointer { /// /// let l = Length(100); /// -/// assert_eq!( -/// format!("l in scientific notation is: {l:e}"), -/// "l in scientific notation is: 1e2" -/// ); +/// assert_eq!(format!("l in scientific notation is: {l:e}"), "l in scientific notation is: 1e2"); /// /// assert_eq!( /// format!("l in scientific notation is: {l:05e}"), @@ -1143,10 +1139,7 @@ pub trait LowerExp { /// /// let l = Length(100); /// -/// assert_eq!( -/// format!("l in scientific notation is: {l:E}"), -/// "l in scientific notation is: 1E2" -/// ); +/// assert_eq!(format!("l in scientific notation is: {l:E}"), "l in scientific notation is: 1E2"); /// /// assert_eq!( /// format!("l in scientific notation is: {l:05E}"), @@ -1332,13 +1325,13 @@ impl<'a> Formatter<'a> { /// ``` /// use std::fmt; /// - /// struct Foo { nb: i32 } + /// struct Foo { + /// nb: i32, + /// } /// /// impl Foo { /// fn new(nb: i32) -> Foo { - /// Foo { - /// nb, - /// } + /// Foo { nb } /// } /// } /// @@ -1723,9 +1716,9 @@ impl<'a> Formatter<'a> { /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { /// let s = if let Some(s) = formatter.align() { /// match s { - /// Alignment::Left => "left", - /// Alignment::Right => "right", - /// Alignment::Center => "center", + /// Alignment::Left => "left", + /// Alignment::Right => "right", + /// Alignment::Center => "center", /// } /// } else { /// "into the void" @@ -1823,10 +1816,7 @@ impl<'a> Formatter<'a> { /// impl fmt::Display for Foo { /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { /// if formatter.sign_plus() { - /// write!(formatter, - /// "Foo({}{})", - /// if self.0 < 0 { '-' } else { '+' }, - /// self.0.abs()) + /// write!(formatter, "Foo({}{})", if self.0 < 0 { '-' } else { '+' }, self.0.abs()) /// } else { /// write!(formatter, "Foo({})", self.0) /// } @@ -1965,11 +1955,10 @@ impl<'a> Formatter<'a> { /// /// assert_eq!( /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }", - /// format!("{:?}", Foo { - /// bar: 10, - /// baz: "Hello World".to_string(), - /// addr: Ipv4Addr::new(127, 0, 0, 1), - /// }) + /// format!( + /// "{:?}", + /// Foo { bar: 10, baz: "Hello World".to_string(), addr: Ipv4Addr::new(127, 0, 0, 1) } + /// ) /// ); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] @@ -2113,11 +2102,7 @@ impl<'a> Formatter<'a> { /// /// impl fmt::Debug for Foo { /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - /// fmt.debug_tuple("Foo") - /// .field(&self.0) - /// .field(&self.1) - /// .field(&format_args!("_")) - /// .finish() + /// fmt.debug_tuple("Foo").field(&self.0).field(&self.1).field(&format_args!("_")).finish() /// } /// } /// @@ -2288,7 +2273,8 @@ impl<'a> Formatter<'a> { /// /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R> /// where - /// L: 'a + fmt::Debug, R: 'a + fmt::Debug + /// L: 'a + fmt::Debug, + /// R: 'a + fmt::Debug, /// { /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { /// L::fmt(&(self.0).0, fmt)?; @@ -2299,13 +2285,14 @@ impl<'a> Formatter<'a> { /// /// impl<'a, K, V> fmt::Debug for Table<'a, K, V> /// where - /// K: 'a + fmt::Debug, V: 'a + fmt::Debug + /// K: 'a + fmt::Debug, + /// V: 'a + fmt::Debug, /// { /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { /// fmt.debug_set() - /// .entries(self.0.iter().map(Arm)) - /// .entry(&Arm(&(format_args!("_"), &self.1))) - /// .finish() + /// .entries(self.0.iter().map(Arm)) + /// .entry(&Arm(&(format_args!("_"), &self.1))) + /// .finish() /// } /// } /// ``` @@ -2331,9 +2318,9 @@ impl<'a> Formatter<'a> { /// } /// /// assert_eq!( - /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])), + /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])), /// r#"{"A": 10, "B": 11}"# - /// ); + /// ); /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> { diff --git a/library/core/src/fmt/num.rs b/library/core/src/fmt/num.rs index d8365ae9bf920..ee340a432d6b6 100644 --- a/library/core/src/fmt/num.rs +++ b/library/core/src/fmt/num.rs @@ -648,7 +648,6 @@ fn fmt_u128(n: u128, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::R /// T. Granlund and P. Montgomery, “Division by Invariant Integers Using Multiplication” /// in Proc. of the SIGPLAN94 Conference on Programming Language Design and /// Implementation, 1994, pp. 61–72 -/// fn udiv_1e19(n: u128) -> (u128, u64) { const DIV: u64 = 1e19 as u64; const FACTOR: u128 = 156927543384667019095894735580191660403; diff --git a/library/core/src/future/into_future.rs b/library/core/src/future/into_future.rs index 649b433877222..f190cc17ee319 100644 --- a/library/core/src/future/into_future.rs +++ b/library/core/src/future/into_future.rs @@ -31,7 +31,7 @@ use crate::future::Future; /// multiple times before being `.await`ed. /// /// ```rust -/// use std::future::{ready, Ready, IntoFuture}; +/// use std::future::{ready, IntoFuture, Ready}; /// /// /// Eventually multiply two numbers /// pub struct Multiply { @@ -70,10 +70,10 @@ use crate::future::Future; /// // NOTE: Rust does not yet have an `async fn main` function, that functionality /// // currently only exists in the ecosystem. /// async fn run() { -/// let num = Multiply::new(0, 0) // initialize the builder to number: 0, factor: 0 -/// .number(2) // change the number to 2 -/// .factor(2) // change the factor to 2 -/// .await; // convert to future and .await +/// let num = Multiply::new(0, 0) // initialize the builder to number: 0, factor: 0 +/// .number(2) // change the number to 2 +/// .factor(2) // change the factor to 2 +/// .await; // convert to future and .await /// /// assert_eq!(num, 4); /// } diff --git a/library/core/src/future/join.rs b/library/core/src/future/join.rs index 35f0dea062ef9..823bdcb07e9ab 100644 --- a/library/core/src/future/join.rs +++ b/library/core/src/future/join.rs @@ -19,8 +19,12 @@ use crate::task::{Context, Poll}; /// /// use std::future::join; /// -/// async fn one() -> usize { 1 } -/// async fn two() -> usize { 2 } +/// async fn one() -> usize { +/// 1 +/// } +/// async fn two() -> usize { +/// 2 +/// } /// /// # let _ = async { /// let x = join!(one(), two()).await; @@ -35,9 +39,15 @@ use crate::task::{Context, Poll}; /// /// use std::future::join; /// -/// async fn one() -> usize { 1 } -/// async fn two() -> usize { 2 } -/// async fn three() -> usize { 3 } +/// async fn one() -> usize { +/// 1 +/// } +/// async fn two() -> usize { +/// 2 +/// } +/// async fn three() -> usize { +/// 3 +/// } /// /// # let _ = async { /// let x = join!(one(), two(), three()).await; diff --git a/library/core/src/hash/mod.rs b/library/core/src/hash/mod.rs index aa13435e6808d..440f80fcd4a2f 100644 --- a/library/core/src/hash/mod.rs +++ b/library/core/src/hash/mod.rs @@ -22,16 +22,8 @@ //! phone: u64, //! } //! -//! let person1 = Person { -//! id: 5, -//! name: "Janet".to_string(), -//! phone: 555_666_7777, -//! }; -//! let person2 = Person { -//! id: 5, -//! name: "Bob".to_string(), -//! phone: 555_666_7777, -//! }; +//! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 }; +//! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 }; //! //! assert!(calculate_hash(&person1) != calculate_hash(&person2)); //! @@ -63,16 +55,8 @@ //! } //! } //! -//! let person1 = Person { -//! id: 5, -//! name: "Janet".to_string(), -//! phone: 555_666_7777, -//! }; -//! let person2 = Person { -//! id: 5, -//! name: "Bob".to_string(), -//! phone: 555_666_7777, -//! }; +//! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 }; +//! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 }; //! //! assert_eq!(calculate_hash(&person1), calculate_hash(&person2)); //! @@ -688,14 +672,8 @@ pub trait BuildHasher { /// /// // Then later, in a `#[test]` for the type... /// let bh = std::collections::hash_map::RandomState::new(); - /// assert_eq!( - /// bh.hash_one(OrderAmbivalentPair(1, 2)), - /// bh.hash_one(OrderAmbivalentPair(2, 1)) - /// ); - /// assert_eq!( - /// bh.hash_one(OrderAmbivalentPair(10, 2)), - /// bh.hash_one(&OrderAmbivalentPair(2, 10)) - /// ); + /// assert_eq!(bh.hash_one(OrderAmbivalentPair(1, 2)), bh.hash_one(OrderAmbivalentPair(2, 1))); + /// assert_eq!(bh.hash_one(OrderAmbivalentPair(10, 2)), bh.hash_one(&OrderAmbivalentPair(2, 10))); /// ``` #[unstable(feature = "build_hasher_simple_hash_one", issue = "86161")] fn hash_one(&self, x: T) -> u64 @@ -735,7 +713,7 @@ pub trait BuildHasher { /// impl Hasher for MyHasher { /// fn write(&mut self, bytes: &[u8]) { /// // Your hashing algorithm goes here! -/// unimplemented!() +/// unimplemented!() /// } /// /// fn finish(&self) -> u64 { diff --git a/library/core/src/hint.rs b/library/core/src/hint.rs index 3412d3730d011..eac6fdf53216b 100644 --- a/library/core/src/hint.rs +++ b/library/core/src/hint.rs @@ -69,7 +69,6 @@ use crate::intrinsics; /// do_computation(100, &divisors) /// }; /// assert_eq!(result, 12); -/// /// ``` /// /// While using `unreachable_unchecked()` is perfectly sound in the following @@ -85,8 +84,7 @@ use crate::intrinsics; /// // `b.saturating_add(1)` is always positive (not zero), /// // hence `checked_div` will never return `None`. /// // Therefore, the else branch is unreachable. -/// a.checked_div(b.saturating_add(1)) -/// .unwrap_or_else(|| unsafe { unreachable_unchecked() }) +/// a.checked_div(b.saturating_add(1)).unwrap_or_else(|| unsafe { unreachable_unchecked() }) /// } /// /// assert_eq!(div_1(7, 0), 7); diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 1dc79afe83fdb..f7b202c8d2f5b 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -1035,9 +1035,7 @@ extern "rust-intrinsic" { /// // This avoids an integer-to-pointer `transmute`, which can be problematic. /// // Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine. /// let pointer = foo as *const (); - /// let function = unsafe { - /// std::mem::transmute::<*const (), fn() -> i32>(pointer) - /// }; + /// let function = unsafe { std::mem::transmute::<*const (), fn() -> i32>(pointer) }; /// assert_eq!(function(), 0); /// ``` /// @@ -1050,8 +1048,7 @@ extern "rust-intrinsic" { /// std::mem::transmute::, R<'static>>(r) /// } /// - /// unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>) - /// -> &'b mut R<'c> { + /// unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>) -> &'b mut R<'c> { /// std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r) /// } /// ``` @@ -1067,9 +1064,7 @@ extern "rust-intrinsic" { /// ``` /// let raw_bytes = [0x78, 0x56, 0x34, 0x12]; /// - /// let num = unsafe { - /// std::mem::transmute::<[u8; 4], u32>(raw_bytes) - /// }; + /// let num = unsafe { std::mem::transmute::<[u8; 4], u32>(raw_bytes) }; /// /// // use `u32::from_ne_bytes` instead /// let num = u32::from_ne_bytes(raw_bytes); @@ -1084,9 +1079,7 @@ extern "rust-intrinsic" { /// /// ```no_run /// let ptr = &0; - /// let ptr_num_transmute = unsafe { - /// std::mem::transmute::<&i32, usize>(ptr) - /// }; + /// let ptr_num_transmute = unsafe { std::mem::transmute::<&i32, usize>(ptr) }; /// /// // Use an `as` cast instead /// let ptr_num_cast = ptr as *const i32 as usize; @@ -1106,9 +1099,7 @@ extern "rust-intrinsic" { /// /// ``` /// let ptr: *mut i32 = &mut 0; - /// let ref_transmuted = unsafe { - /// std::mem::transmute::<*mut i32, &mut i32>(ptr) - /// }; + /// let ref_transmuted = unsafe { std::mem::transmute::<*mut i32, &mut i32>(ptr) }; /// /// // Use a reborrow instead /// let ref_casted = unsafe { &mut *ptr }; @@ -1118,9 +1109,7 @@ extern "rust-intrinsic" { /// /// ``` /// let ptr = &mut 0; - /// let val_transmuted = unsafe { - /// std::mem::transmute::<&mut i32, &mut u32>(ptr) - /// }; + /// let val_transmuted = unsafe { std::mem::transmute::<&mut i32, &mut u32>(ptr) }; /// /// // Now, put together `as` and reborrowing - note the chaining of `as` /// // `as` is not transitive diff --git a/library/core/src/iter/adapters/map.rs b/library/core/src/iter/adapters/map.rs index 9e25dbe462c91..9608985ec4f23 100644 --- a/library/core/src/iter/adapters/map.rs +++ b/library/core/src/iter/adapters/map.rs @@ -32,8 +32,10 @@ use crate::ops::Try; /// ```rust /// let mut c = 0; /// -/// for pair in ['a', 'b', 'c'].into_iter() -/// .map(|letter| { c += 1; (letter, c) }) { +/// for pair in ['a', 'b', 'c'].into_iter().map(|letter| { +/// c += 1; +/// (letter, c) +/// }) { /// println!("{pair:?}"); /// } /// ``` @@ -49,9 +51,14 @@ use crate::ops::Try; /// ```rust /// let mut c = 0; /// -/// for pair in ['a', 'b', 'c'].into_iter() -/// .map(|letter| { c += 1; (letter, c) }) -/// .rev() { +/// for pair in ['a', 'b', 'c'] +/// .into_iter() +/// .map(|letter| { +/// c += 1; +/// (letter, c) +/// }) +/// .rev() +/// { /// println!("{pair:?}"); /// } /// ``` diff --git a/library/core/src/iter/mod.rs b/library/core/src/iter/mod.rs index ef0f397825b15..ef052cf860e74 100644 --- a/library/core/src/iter/mod.rs +++ b/library/core/src/iter/mod.rs @@ -106,11 +106,7 @@ //! self.count += 1; //! //! // Check to see if we've finished counting or not. -//! if self.count < 6 { -//! Some(self.count) -//! } else { -//! None -//! } +//! if self.count < 6 { Some(self.count) } else { None } //! } //! } //! @@ -181,7 +177,9 @@ //! None => break, //! }; //! let x = next; -//! let () = { println!("{x}"); }; +//! let () = { +//! println!("{x}"); +//! }; //! }, //! }; //! result @@ -233,10 +231,12 @@ //! //! ``` //! let mut values = vec![41]; -//! for x in &mut values { // same as `values.iter_mut()` +//! for x in &mut values { +//! // same as `values.iter_mut()` //! *x += 1; //! } -//! for x in &values { // same as `values.iter()` +//! for x in &values { +//! // same as `values.iter()` //! assert_eq!(*x, 42); //! } //! assert_eq!(values.len(), 1); diff --git a/library/core/src/iter/sources/from_fn.rs b/library/core/src/iter/sources/from_fn.rs index 3cd3830471cfe..7006db04f5064 100644 --- a/library/core/src/iter/sources/from_fn.rs +++ b/library/core/src/iter/sources/from_fn.rs @@ -30,11 +30,7 @@ use crate::fmt; /// count += 1; /// /// // Check to see if we've finished counting or not. -/// if count < 6 { -/// Some(count) -/// } else { -/// None -/// } +/// if count < 6 { Some(count) } else { None } /// }); /// assert_eq!(counter.collect::>(), &[1, 2, 3, 4, 5]); /// ``` diff --git a/library/core/src/iter/sources/once.rs b/library/core/src/iter/sources/once.rs index 6e9ed0d3c5278..423a984b5a9f4 100644 --- a/library/core/src/iter/sources/once.rs +++ b/library/core/src/iter/sources/once.rs @@ -30,8 +30,8 @@ use crate::iter::{FusedIterator, TrustedLen}; /// `.foorc`: /// /// ```no_run -/// use std::iter; /// use std::fs; +/// use std::iter; /// use std::path::PathBuf; /// /// let dirs = fs::read_dir(".foo").unwrap(); diff --git a/library/core/src/iter/sources/once_with.rs b/library/core/src/iter/sources/once_with.rs index d79f85c2559fe..fb0889000507d 100644 --- a/library/core/src/iter/sources/once_with.rs +++ b/library/core/src/iter/sources/once_with.rs @@ -34,8 +34,8 @@ use crate::iter::{FusedIterator, TrustedLen}; /// `.foorc`: /// /// ```no_run -/// use std::iter; /// use std::fs; +/// use std::iter; /// use std::path::PathBuf; /// /// let dirs = fs::read_dir(".foo").unwrap(); diff --git a/library/core/src/iter/sources/repeat_with.rs b/library/core/src/iter/sources/repeat_with.rs index 6f62662d88066..1484e1e6c1b79 100644 --- a/library/core/src/iter/sources/repeat_with.rs +++ b/library/core/src/iter/sources/repeat_with.rs @@ -48,8 +48,12 @@ use crate::iter::{FusedIterator, TrustedLen}; /// /// // From the zeroth to the third power of two: /// let mut curr = 1; -/// let mut pow2 = iter::repeat_with(|| { let tmp = curr; curr *= 2; tmp }) -/// .take(4); +/// let mut pow2 = iter::repeat_with(|| { +/// let tmp = curr; +/// curr *= 2; +/// tmp +/// }) +/// .take(4); /// /// assert_eq!(Some(1), pow2.next()); /// assert_eq!(Some(2), pow2.next()); diff --git a/library/core/src/iter/traits/accum.rs b/library/core/src/iter/traits/accum.rs index 84d83ee39699f..4a9f0261de8de 100644 --- a/library/core/src/iter/traits/accum.rs +++ b/library/core/src/iter/traits/accum.rs @@ -157,10 +157,8 @@ where /// /// ``` /// let v = vec![1, 2]; - /// let res: Result = v.iter().map(|&x: &i32| - /// if x < 0 { Err("Negative element found") } - /// else { Ok(x) } - /// ).sum(); + /// let res: Result = + /// v.iter().map(|&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }).sum(); /// assert_eq!(res, Ok(3)); /// ``` fn sum(iter: I) -> Result diff --git a/library/core/src/iter/traits/collect.rs b/library/core/src/iter/traits/collect.rs index e099700e3e7c8..3e9275873f1d5 100644 --- a/library/core/src/iter/traits/collect.rs +++ b/library/core/src/iter/traits/collect.rs @@ -66,7 +66,7 @@ /// /// // and we'll implement FromIterator /// impl FromIterator for MyCollection { -/// fn from_iter>(iter: I) -> Self { +/// fn from_iter>(iter: I) -> Self { /// let mut c = MyCollection::new(); /// /// for i in iter { @@ -219,10 +219,7 @@ pub trait FromIterator: Sized { /// T: IntoIterator, /// T::Item: std::fmt::Debug, /// { -/// collection -/// .into_iter() -/// .map(|item| format!("{item:?}")) -/// .collect() +/// collection.into_iter().map(|item| format!("{item:?}")).collect() /// } /// ``` #[rustc_diagnostic_item = "IntoIterator"] @@ -317,12 +314,10 @@ impl const IntoIterator for I { /// /// // since MyCollection has a list of i32s, we implement Extend for i32 /// impl Extend for MyCollection { -/// /// // This is a bit simpler with the concrete type signature: we can call /// // extend on anything which can be turned into an Iterator which gives /// // us i32s. Because we need i32s to put into MyCollection. -/// fn extend>(&mut self, iter: T) { -/// +/// fn extend>(&mut self, iter: T) { /// // The implementation is very straightforward: loop through the /// // iterator, and add() each element to ourselves. /// for elem in iter { diff --git a/library/core/src/iter/traits/double_ended.rs b/library/core/src/iter/traits/double_ended.rs index bdf94c792c27c..945fcafeacf19 100644 --- a/library/core/src/iter/traits/double_ended.rs +++ b/library/core/src/iter/traits/double_ended.rs @@ -81,11 +81,17 @@ pub trait DoubleEndedIterator: Iterator { /// assert_eq!(uniq_by_fst_comp().next_back(), Some((2, 'b'))); /// /// assert_eq!( - /// uniq_by_fst_comp().fold(vec![], |mut v, x| {v.push(x); v}), + /// uniq_by_fst_comp().fold(vec![], |mut v, x| { + /// v.push(x); + /// v + /// }), /// vec![(1, 'a'), (2, 'a')] /// ); /// assert_eq!( - /// uniq_by_fst_comp().rfold(vec![], |mut v, x| {v.push(x); v}), + /// uniq_by_fst_comp().rfold(vec![], |mut v, x| { + /// v.push(x); + /// v + /// }), /// vec![(2, 'b'), (1, 'c')] /// ); /// ``` @@ -195,9 +201,8 @@ pub trait DoubleEndedIterator: Iterator { /// /// ``` /// let a = ["1", "2", "3"]; - /// let sum = a.iter() - /// .map(|&s| s.parse::()) - /// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y))); + /// let sum = + /// a.iter().map(|&s| s.parse::()).try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y))); /// assert_eq!(sum, Ok(6)); /// ``` /// @@ -206,10 +211,8 @@ pub trait DoubleEndedIterator: Iterator { /// ``` /// let a = ["1", "rust", "3"]; /// let mut it = a.iter(); - /// let sum = it - /// .by_ref() - /// .map(|&s| s.parse::()) - /// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y))); + /// let sum = + /// it.by_ref().map(|&s| s.parse::()).try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y))); /// assert!(sum.is_err()); /// /// // Because it short-circuited, the remaining elements are still @@ -265,8 +268,7 @@ pub trait DoubleEndedIterator: Iterator { /// let a = [1, 2, 3]; /// /// // the sum of all of the elements of a - /// let sum = a.iter() - /// .rfold(0, |acc, &x| acc + x); + /// let sum = a.iter().rfold(0, |acc, &x| acc + x); /// /// assert_eq!(sum, 6); /// ``` @@ -280,9 +282,7 @@ pub trait DoubleEndedIterator: Iterator { /// /// let zero = "0".to_string(); /// - /// let result = numbers.iter().rfold(zero, |acc, &x| { - /// format!("({x} + {acc})") - /// }); + /// let result = numbers.iter().rfold(zero, |acc, &x| format!("({x} + {acc})")); /// /// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))"); /// ``` diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 83c7e8977e9f3..7ab3169b883dc 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -117,8 +117,8 @@ pub trait Iterator { /// /// let mut iter = "lorem".chars(); /// - /// assert_eq!(iter.next_chunk().unwrap(), ['l', 'o']); // N is inferred as 2 - /// assert_eq!(iter.next_chunk().unwrap(), ['r', 'e', 'm']); // N is inferred as 3 + /// assert_eq!(iter.next_chunk().unwrap(), ['l', 'o']); // N is inferred as 2 + /// assert_eq!(iter.next_chunk().unwrap(), ['r', 'e', 'm']); // N is inferred as 3 /// assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(), &[]); // N is explicitly 4 /// ``` /// @@ -582,10 +582,8 @@ pub trait Iterator { /// let a = [1, 2, 3]; /// let b = [2, 3, 4]; /// - /// let mut zipped = zip( - /// a.into_iter().map(|x| x * 2).skip(1), - /// b.into_iter().map(|x| x * 2).skip(1), - /// ); + /// let mut zipped = + /// zip(a.into_iter().map(|x| x * 2).skip(1), b.into_iter().map(|x| x * 2).skip(1)); /// /// assert_eq!(zipped.next(), Some((4, 6))); /// assert_eq!(zipped.next(), Some((6, 8))); @@ -598,11 +596,7 @@ pub trait Iterator { /// # let a = [1, 2, 3]; /// # let b = [2, 3, 4]; /// # - /// let mut zipped = a - /// .into_iter() - /// .map(|x| x * 2) - /// .skip(1) - /// .zip(b.into_iter().map(|x| x * 2).skip(1)); + /// let mut zipped = a.into_iter().map(|x| x * 2).skip(1).zip(b.into_iter().map(|x| x * 2).skip(1)); /// # /// # assert_eq!(zipped.next(), Some((4, 6))); /// # assert_eq!(zipped.next(), Some((6, 8))); @@ -636,12 +630,12 @@ pub trait Iterator { /// #![feature(iter_intersperse)] /// /// let mut a = [0, 1, 2].iter().intersperse(&100); - /// assert_eq!(a.next(), Some(&0)); // The first element from `a`. + /// assert_eq!(a.next(), Some(&0)); // The first element from `a`. /// assert_eq!(a.next(), Some(&100)); // The separator. - /// assert_eq!(a.next(), Some(&1)); // The next element from `a`. + /// assert_eq!(a.next(), Some(&1)); // The next element from `a`. /// assert_eq!(a.next(), Some(&100)); // The separator. - /// assert_eq!(a.next(), Some(&2)); // The last element from `a`. - /// assert_eq!(a.next(), None); // The iterator is finished. + /// assert_eq!(a.next(), Some(&2)); // The last element from `a`. + /// assert_eq!(a.next(), None); // The iterator is finished. /// ``` /// /// `intersperse` can be very useful to join an iterator's items using a common element: @@ -688,12 +682,12 @@ pub trait Iterator { /// let v = [NotClone(0), NotClone(1), NotClone(2)]; /// let mut it = v.into_iter().intersperse_with(|| NotClone(99)); /// - /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`. + /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`. /// assert_eq!(it.next(), Some(NotClone(99))); // The separator. - /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`. + /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`. /// assert_eq!(it.next(), Some(NotClone(99))); // The separator. - /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from `v`. - /// assert_eq!(it.next(), None); // The iterator is finished. + /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from `v`. + /// assert_eq!(it.next(), None); // The iterator is finished. /// ``` /// /// `intersperse_with` can be used in situations where the separator needs @@ -800,10 +794,9 @@ pub trait Iterator { /// use std::sync::mpsc::channel; /// /// let (tx, rx) = channel(); - /// (0..5).map(|x| x * 2 + 1) - /// .for_each(move |x| tx.send(x).unwrap()); + /// (0..5).map(|x| x * 2 + 1).for_each(move |x| tx.send(x).unwrap()); /// - /// let v: Vec<_> = rx.iter().collect(); + /// let v: Vec<_> = rx.iter().collect(); /// assert_eq!(v, vec![1, 3, 5, 7, 9]); /// ``` /// @@ -811,10 +804,11 @@ pub trait Iterator { /// might be preferable to keep a functional style with longer iterators: /// /// ``` - /// (0..5).flat_map(|x| x * 100 .. x * 110) - /// .enumerate() - /// .filter(|&(i, x)| (i + x) % 3 == 0) - /// .for_each(|(i, x)| println!("{i}:{x}")); + /// (0..5) + /// .flat_map(|x| x * 100..x * 110) + /// .enumerate() + /// .filter(|&(i, x)| (i + x) % 3 == 0) + /// .for_each(|(i, x)| println!("{i}:{x}")); /// ``` #[inline] #[stable(feature = "iterator_for_each", since = "1.21.0")] @@ -1185,10 +1179,7 @@ pub trait Iterator { /// let a = [1, 2, 3, 4]; /// let mut iter = a.iter(); /// - /// let result: Vec = iter.by_ref() - /// .take_while(|n| **n != 3) - /// .cloned() - /// .collect(); + /// let result: Vec = iter.by_ref().take_while(|n| **n != 3).cloned().collect(); /// /// assert_eq!(result, &[1, 2]); /// @@ -1237,10 +1228,8 @@ pub trait Iterator { /// ``` /// let a = [-1i32, 4, 0, 1]; /// - /// let mut iter = a.iter() - /// .map(|x| 16i32.checked_div(*x)) - /// .take_while(|x| x.is_some()) - /// .map(|x| x.unwrap()); + /// let mut iter = + /// a.iter().map(|x| 16i32.checked_div(*x)).take_while(|x| x.is_some()).map(|x| x.unwrap()); /// /// assert_eq!(iter.next(), Some(-16)); /// assert_eq!(iter.next(), Some(4)); @@ -1268,9 +1257,7 @@ pub trait Iterator { /// let a = [1, 2, -3, 4]; /// let mut iter = a.iter(); /// - /// let result: Vec = iter.by_ref() - /// .map_while(|n| u32::try_from(*n).ok()) - /// .collect(); + /// let result: Vec = iter.by_ref().map_while(|n| u32::try_from(*n).ok()).collect(); /// /// assert_eq!(result, &[1, 2]); /// @@ -1450,9 +1437,7 @@ pub trait Iterator { /// let words = ["alpha", "beta", "gamma"]; /// /// // chars() returns an iterator - /// let merged: String = words.iter() - /// .flat_map(|s| s.chars()) - /// .collect(); + /// let merged: String = words.iter().flat_map(|s| s.chars()).collect(); /// assert_eq!(merged, "alphabetagamma"); /// ``` #[inline] @@ -1488,10 +1473,7 @@ pub trait Iterator { /// let words = ["alpha", "beta", "gamma"]; /// /// // chars() returns an iterator - /// let merged: String = words.iter() - /// .map(|s| s.chars()) - /// .flatten() - /// .collect(); + /// let merged: String = words.iter().map(|s| s.chars()).flatten().collect(); /// assert_eq!(merged, "alphabetagamma"); /// ``` /// @@ -1502,9 +1484,7 @@ pub trait Iterator { /// let words = ["alpha", "beta", "gamma"]; /// /// // chars() returns an iterator - /// let merged: String = words.iter() - /// .flat_map(|s| s.chars()) - /// .collect(); + /// let merged: String = words.iter().flat_map(|s| s.chars()).collect(); /// assert_eq!(merged, "alphabetagamma"); /// ``` /// @@ -1568,11 +1548,7 @@ pub trait Iterator { /// self.state = self.state + 1; /// /// // if it's even, Some(i32), else None - /// if val % 2 == 0 { - /// Some(val) - /// } else { - /// None - /// } + /// if val % 2 == 0 { Some(val) } else { None } /// } /// } /// @@ -1623,15 +1599,13 @@ pub trait Iterator { /// let a = [1, 4, 2, 3]; /// /// // this iterator sequence is complex. - /// let sum = a.iter() - /// .cloned() - /// .filter(|x| x % 2 == 0) - /// .fold(0, |sum, i| sum + i); + /// let sum = a.iter().cloned().filter(|x| x % 2 == 0).fold(0, |sum, i| sum + i); /// /// println!("{sum}"); /// /// // let's add some inspect() calls to investigate what's happening - /// let sum = a.iter() + /// let sum = a + /// .iter() /// .cloned() /// .inspect(|x| println!("about to filter: {x}")) /// .filter(|x| x % 2 == 0) @@ -1746,9 +1720,7 @@ pub trait Iterator { /// ``` /// let a = [1, 2, 3]; /// - /// let doubled: Vec = a.iter() - /// .map(|&x| x * 2) - /// .collect(); + /// let doubled: Vec = a.iter().map(|&x| x * 2).collect(); /// /// assert_eq!(vec![2, 4, 6], doubled); /// ``` @@ -1796,10 +1768,7 @@ pub trait Iterator { /// ``` /// let chars = ['g', 'd', 'k', 'k', 'n']; /// - /// let hello: String = chars.iter() - /// .map(|&x| x as u8) - /// .map(|x| (x + 1) as char) - /// .collect(); + /// let hello: String = chars.iter().map(|&x| x as u8).map(|x| (x + 1) as char).collect(); /// /// assert_eq!("hello", hello); /// ``` @@ -1937,7 +1906,7 @@ pub trait Iterator { /// #![feature(iter_collect_into)] /// /// let a = [1, 2, 3]; - /// let mut vec: Vec:: = vec![0, 1]; + /// let mut vec: Vec = vec![0, 1]; /// /// a.iter().map(|&x| x * 2).collect_into(&mut vec); /// a.iter().map(|&x| x * 10).collect_into(&mut vec); @@ -1951,7 +1920,7 @@ pub trait Iterator { /// #![feature(iter_collect_into)] /// /// let a = [1, 2, 3]; - /// let mut vec: Vec:: = Vec::with_capacity(6); + /// let mut vec: Vec = Vec::with_capacity(6); /// /// a.iter().map(|&x| x * 2).collect_into(&mut vec); /// a.iter().map(|&x| x * 10).collect_into(&mut vec); @@ -1966,7 +1935,7 @@ pub trait Iterator { /// #![feature(iter_collect_into)] /// /// let a = [1, 2, 3]; - /// let mut vec: Vec:: = Vec::with_capacity(6); + /// let mut vec: Vec = Vec::with_capacity(6); /// /// let count = a.iter().collect_into(&mut vec).iter().count(); /// @@ -2006,9 +1975,7 @@ pub trait Iterator { /// ``` /// let a = [1, 2, 3]; /// - /// let (even, odd): (Vec<_>, Vec<_>) = a - /// .into_iter() - /// .partition(|n| n % 2 == 0); + /// let (even, odd): (Vec<_>, Vec<_>) = a.into_iter().partition(|n| n % 2 == 0); /// /// assert_eq!(even, vec![2]); /// assert_eq!(odd, vec![1, 3]); @@ -2276,7 +2243,7 @@ pub trait Iterator { /// /// let r = (2..100).try_for_each(|x| { /// if 323 % x == 0 { - /// return ControlFlow::Break(x) + /// return ControlFlow::Break(x); /// } /// /// ControlFlow::Continue(()) @@ -2371,9 +2338,7 @@ pub trait Iterator { /// /// let zero = "0".to_string(); /// - /// let result = numbers.iter().fold(zero, |acc, &x| { - /// format!("({acc} + {x})") - /// }); + /// let result = numbers.iter().fold(zero, |acc, &x| format!("({acc} + {x})")); /// /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)"); /// ``` @@ -2744,7 +2709,7 @@ pub trait Iterator { /// let a = ["1", "2", "lol", "NaN", "5"]; /// /// let is_my_num = |s: &str, search: i32| -> Result { - /// Ok(s.parse::()? == search) + /// Ok(s.parse::()? == search) /// }; /// /// let result = a.iter().try_find(|&&s| is_my_num(s, 2)); @@ -2847,7 +2812,6 @@ pub trait Iterator { /// /// // The returned index depends on iterator state /// assert_eq!(iter.position(|&x| x == 4), Some(0)); - /// /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -2937,13 +2901,7 @@ pub trait Iterator { /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being /// incomparable. You can work around this by using [`Iterator::reduce`]: /// ``` - /// assert_eq!( - /// [2.4, f32::NAN, 1.3] - /// .into_iter() - /// .reduce(f32::max) - /// .unwrap(), - /// 2.4 - /// ); + /// assert_eq!([2.4, f32::NAN, 1.3].into_iter().reduce(f32::max).unwrap(), 2.4); /// ``` /// /// # Examples @@ -2975,13 +2933,7 @@ pub trait Iterator { /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being /// incomparable. You can work around this by using [`Iterator::reduce`]: /// ``` - /// assert_eq!( - /// [2.4, f32::NAN, 1.3] - /// .into_iter() - /// .reduce(f32::min) - /// .unwrap(), - /// 1.3 - /// ); + /// assert_eq!([2.4, f32::NAN, 1.3].into_iter().reduce(f32::min).unwrap(), 1.3); /// ``` /// /// # Examples @@ -3514,10 +3466,7 @@ pub trait Iterator { /// let xs = [1.0, 2.0, 3.0, 4.0]; /// let ys = [1.0, 4.0, 9.0, 16.0]; /// - /// assert_eq!( - /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)), - /// Some(Ordering::Less) - /// ); + /// assert_eq!(xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)), Some(Ordering::Less)); /// assert_eq!( /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)), /// Some(Ordering::Equal) diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 659409557c910..bec254475eec3 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -16,7 +16,6 @@ //! # How to use the core library //! //! Please note that all of these details are currently not considered stable. -//! // FIXME: Fill me in with more detail when the interface settles //! This library is built on the assumption of a few existing symbols: //! diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index 2850d84acc327..943869c19f964 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -199,14 +199,17 @@ pub macro assert_matches { /// // expression given. /// debug_assert!(true); /// -/// fn some_expensive_computation() -> bool { true } // a very simple function +/// fn some_expensive_computation() -> bool { +/// true +/// } // a very simple function /// debug_assert!(some_expensive_computation()); /// /// // assert with a custom message /// let x = true; /// debug_assert!(x, "x wasn't true!"); /// -/// let a = 3; let b = 27; +/// let a = 3; +/// let b = 27; /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[macro_export] @@ -372,12 +375,12 @@ macro_rules! matches { /// # Examples /// /// ``` -/// use std::io; /// use std::fs::File; +/// use std::io; /// use std::io::prelude::*; /// /// enum MyError { -/// FileWriteError +/// FileWriteError, /// } /// /// impl From for MyError { @@ -489,7 +492,7 @@ macro_rules! r#try { /// /// impl fmt::Write for Example { /// fn write_str(&mut self, _s: &str) -> core::fmt::Result { -/// unimplemented!(); +/// unimplemented!(); /// } /// } /// ``` @@ -505,11 +508,11 @@ macro_rules! r#try { /// /// impl Write for Example { /// fn write_str(&mut self, _s: &str) -> core::fmt::Result { -/// unimplemented!(); +/// unimplemented!(); /// } /// } /// -/// let mut m = Example{}; +/// let mut m = Example {}; /// write!(&mut m, "Hello World").expect("Not written"); /// ``` #[macro_export] @@ -534,7 +537,7 @@ macro_rules! write { /// # Examples /// /// ``` -/// use std::io::{Write, Result}; +/// use std::io::{Result, Write}; /// /// fn main() -> Result<()> { /// let mut w = Vec::new(); @@ -592,9 +595,9 @@ macro_rules! writeln { /// fn foo(x: Option) { /// match x { /// Some(n) if n >= 0 => println!("Some(Non-negative)"), -/// Some(n) if n < 0 => println!("Some(Negative)"), -/// Some(_) => unreachable!(), // compile error if commented out -/// None => println!("None") +/// Some(n) if n < 0 => println!("Some(Negative)"), +/// Some(_) => unreachable!(), // compile error if commented out +/// None => println!("None"), /// } /// } /// ``` @@ -603,10 +606,15 @@ macro_rules! writeln { /// /// ``` /// # #[allow(dead_code)] -/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3 +/// fn divide_by_three(x: u32) -> u32 { +/// // one of the poorest implementations of x/3 /// for i in 0.. { -/// if 3*i < i { panic!("u32 overflow"); } -/// if x < 3*i { return i-1; } +/// if 3 * i < i { +/// panic!("u32 overflow"); +/// } +/// if x < 3 * i { +/// return i - 1; +/// } /// } /// unreachable!("The loop should always return"); /// } @@ -994,7 +1002,9 @@ pub(crate) mod builtin { /// #![feature(concat_idents)] /// /// # fn main() { - /// fn foobar() -> u32 { 23 } + /// fn foobar() -> u32 { + /// 23 + /// } /// /// let f = concat_idents!(foo, bar); /// println!("{}", f()); @@ -1307,11 +1317,7 @@ pub(crate) mod builtin { /// # Examples /// /// ``` - /// let my_directory = if cfg!(windows) { - /// "windows-specific-directory" - /// } else { - /// "unix-directory" - /// }; + /// let my_directory = if cfg!(windows) { "windows-specific-directory" } else { "unix-directory" }; /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_builtin_macro] @@ -1405,7 +1411,9 @@ pub(crate) mod builtin { /// // expression given. /// assert!(true); /// - /// fn some_computation() -> bool { true } // a very simple function + /// fn some_computation() -> bool { + /// true + /// } // a very simple function /// /// assert!(some_computation()); /// @@ -1413,7 +1421,8 @@ pub(crate) mod builtin { /// let x = true; /// assert!(x, "x wasn't true!"); /// - /// let a = 3; let b = 27; + /// let a = 3; + /// let b = 27; /// assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index ae4ebf4444295..60c92d4344e86 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -74,16 +74,16 @@ unsafe impl Send for &T {} /// /// ``` /// # #![allow(unused_variables)] -/// trait Foo { } -/// trait Bar: Sized { } +/// trait Foo {} +/// trait Bar: Sized {} /// /// struct Impl; -/// impl Foo for Impl { } -/// impl Bar for Impl { } +/// impl Foo for Impl {} +/// impl Bar for Impl {} /// -/// let x: &dyn Foo = &Impl; // OK +/// let x: &dyn Foo = &Impl; // OK /// // let y: &dyn Bar = &Impl; // error: the trait `Bar` cannot -/// // be made into an object +/// // be made into an object /// ``` /// /// [trait object]: ../../book/ch17-02-trait-objects.html @@ -182,7 +182,7 @@ pub trait StructuralPartialEq { /// #[derive(PartialEq, Eq)] /// struct Wrap(X); /// -/// fn higher_order(_: &()) { } +/// fn higher_order(_: &()) {} /// /// const CFN: Wrap = Wrap(higher_order); /// @@ -264,7 +264,7 @@ pub trait StructuralEq { /// ``` /// struct MyStruct; /// -/// impl Copy for MyStruct { } +/// impl Copy for MyStruct {} /// /// impl Clone for MyStruct { /// fn clone(&self) -> MyStruct { @@ -301,8 +301,8 @@ pub trait StructuralEq { /// # #[allow(dead_code)] /// #[derive(Copy, Clone)] /// struct Point { -/// x: i32, -/// y: i32, +/// x: i32, +/// y: i32, /// } /// ``` /// @@ -555,11 +555,7 @@ impl !Sync for *mut T {} /// # } /// fn borrow_vec(vec: &Vec) -> Slice<'_, T> { /// let ptr = vec.as_ptr(); -/// Slice { -/// start: ptr, -/// end: unsafe { ptr.add(vec.len()) }, -/// phantom: PhantomData, -/// } +/// Slice { start: ptr, end: unsafe { ptr.add(vec.len()) }, phantom: PhantomData } /// } /// ``` /// @@ -588,17 +584,14 @@ impl !Sync for *mut T {} /// use std::mem; /// /// struct ExternalResource { -/// resource_handle: *mut (), -/// resource_type: PhantomData, +/// resource_handle: *mut (), +/// resource_type: PhantomData, /// } /// /// impl ExternalResource { /// fn new() -> Self { /// let size_of_res = mem::size_of::(); -/// Self { -/// resource_handle: foreign_lib::new(size_of_res), -/// resource_type: PhantomData, -/// } +/// Self { resource_handle: foreign_lib::new(size_of_res), resource_type: PhantomData } /// } /// /// fn do_stuff(&self, param: ParamType) { diff --git a/library/core/src/mem/manually_drop.rs b/library/core/src/mem/manually_drop.rs index 3d719afe49e4a..ac284b3c98a77 100644 --- a/library/core/src/mem/manually_drop.rs +++ b/library/core/src/mem/manually_drop.rs @@ -103,7 +103,6 @@ impl ManuallyDrop { /// This function semantically moves out the contained value without preventing further usage, /// leaving the state of this container unchanged. /// It is your responsibility to ensure that this `ManuallyDrop` is not used again. - /// #[must_use = "if you don't need the value, you can use `ManuallyDrop::drop` instead"] #[stable(feature = "manually_drop_take", since = "1.42.0")] #[inline] diff --git a/library/core/src/mem/maybe_uninit.rs b/library/core/src/mem/maybe_uninit.rs index 7757c95de9d2a..c17ced88e8ba5 100644 --- a/library/core/src/mem/maybe_uninit.rs +++ b/library/core/src/mem/maybe_uninit.rs @@ -105,7 +105,9 @@ use crate::slice; /// } /// /// let mut v = MaybeUninit::uninit(); -/// unsafe { make_vec(v.as_mut_ptr()); } +/// unsafe { +/// make_vec(v.as_mut_ptr()); +/// } /// // Now we know `v` is initialized! This also makes sure the vector gets /// // properly dropped. /// let v = unsafe { v.assume_init() }; @@ -123,9 +125,8 @@ use crate::slice; /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is /// // safe because the type we are claiming to have initialized here is a /// // bunch of `MaybeUninit`s, which do not require initialization. -/// let mut data: [MaybeUninit>; 1000] = unsafe { -/// MaybeUninit::uninit().assume_init() -/// }; +/// let mut data: [MaybeUninit>; 1000] = +/// unsafe { MaybeUninit::uninit().assume_init() }; /// /// // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop, /// // we have a memory leak, but there is no memory safety issue. @@ -161,7 +162,9 @@ use crate::slice; /// /// // For each item in the array, drop if we allocated it. /// for elem in &mut data[0..data_len] { -/// unsafe { elem.assume_init_drop(); } +/// unsafe { +/// elem.assume_init_drop(); +/// } /// } /// ``` /// @@ -186,23 +189,21 @@ use crate::slice; /// // Initializing the `name` field /// // Using `write` instead of assignment via `=` to not call `drop` on the /// // old, uninitialized value. -/// unsafe { addr_of_mut!((*ptr).name).write("Bob".to_string()); } +/// unsafe { +/// addr_of_mut!((*ptr).name).write("Bob".to_string()); +/// } /// /// // Initializing the `list` field /// // If there is a panic here, then the `String` in the `name` field leaks. -/// unsafe { addr_of_mut!((*ptr).list).write(vec![0, 1, 2]); } +/// unsafe { +/// addr_of_mut!((*ptr).list).write(vec![0, 1, 2]); +/// } /// /// // All the fields are initialized, so we call `assume_init` to get an initialized Foo. /// unsafe { uninit.assume_init() } /// }; /// -/// assert_eq!( -/// foo, -/// Foo { -/// name: "Bob".to_string(), -/// list: vec![0, 1, 2] -/// } -/// ); +/// assert_eq!(foo, Foo { name: "Bob".to_string(), list: vec![0, 1, 2] }); /// ``` /// [`std::ptr::addr_of_mut`]: crate::ptr::addr_of_mut /// [ub]: ../../reference/behavior-considered-undefined.html @@ -212,7 +213,7 @@ use crate::slice; /// `MaybeUninit` is guaranteed to have the same size, alignment, and ABI as `T`: /// /// ```rust -/// use std::mem::{MaybeUninit, size_of, align_of}; +/// use std::mem::{align_of, size_of, MaybeUninit}; /// assert_eq!(size_of::>(), size_of::()); /// assert_eq!(align_of::>(), align_of::()); /// ``` @@ -380,7 +381,10 @@ impl MaybeUninit { /// ```rust,no_run /// use std::mem::MaybeUninit; /// - /// enum NotZero { One = 1, Two = 2 } + /// enum NotZero { + /// One = 1, + /// Two = 2, + /// } /// /// let x = MaybeUninit::<(u8, NotZero)>::zeroed(); /// let x = unsafe { x.assume_init() }; @@ -460,15 +464,15 @@ impl MaybeUninit { /// With `write`, we can avoid the need to write through a raw pointer: /// /// ```rust - /// use core::pin::Pin; /// use core::mem::MaybeUninit; + /// use core::pin::Pin; /// /// struct PinArena { /// memory: Box<[MaybeUninit]>, /// len: usize, /// } /// - /// impl PinArena { + /// impl PinArena { /// pub fn capacity(&self) -> usize { /// self.memory.len() /// } @@ -776,8 +780,8 @@ impl MaybeUninit { /// // Initialize the `MaybeUninit` using `Cell::set`: /// unsafe { /// b.assume_init_ref().set(true); - /// // ^^^^^^^^^^^^^^^ - /// // Reference to an uninitialized `Cell`: UB! + /// // ^^^^^^^^^^^^^^^ + /// // Reference to an uninitialized `Cell`: UB! /// } /// ``` #[stable(feature = "maybe_uninit_ref", since = "1.55.0")] @@ -823,7 +827,9 @@ impl MaybeUninit { /// let mut buf = MaybeUninit::<[u8; 1024]>::uninit(); /// /// // Initialize `buf`: - /// unsafe { initialize_buffer(buf.as_mut_ptr()); } + /// unsafe { + /// initialize_buffer(buf.as_mut_ptr()); + /// } /// // Now we know that `buf` has been initialized, so we could `.assume_init()` it. /// // However, using `.assume_init()` may trigger a `memcpy` of the 1024 bytes. /// // To assert our buffer has been initialized without copying it, we upgrade @@ -835,10 +841,7 @@ impl MaybeUninit { /// /// // Now we can use `buf` as a normal slice: /// buf.sort_unstable(); - /// assert!( - /// buf.windows(2).all(|pair| pair[0] <= pair[1]), - /// "buffer is sorted", - /// ); + /// assert!(buf.windows(2).all(|pair| pair[0] <= pair[1]), "buffer is sorted",); /// ``` /// /// ### *Incorrect* usages of this method: @@ -863,13 +866,12 @@ impl MaybeUninit { /// ```rust,no_run /// use std::{io, mem::MaybeUninit}; /// - /// fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]> - /// { + /// fn read_chunk(reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]> { /// let mut buffer = MaybeUninit::<[u8; 64]>::uninit(); /// reader.read_exact(unsafe { buffer.assume_init_mut() })?; - /// // ^^^^^^^^^^^^^^^^^^^^^^^^ - /// // (mutable) reference to uninitialized memory! - /// // This is undefined behavior. + /// // ^^^^^^^^^^^^^^^^^^^^^^^^ + /// // (mutable) reference to uninitialized memory! + /// // This is undefined behavior. /// Ok(unsafe { buffer.assume_init() }) /// } /// ``` @@ -887,13 +889,13 @@ impl MaybeUninit { /// let foo: Foo = unsafe { /// let mut foo = MaybeUninit::::uninit(); /// ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337); - /// // ^^^^^^^^^^^^^^^^^^^^^ - /// // (mutable) reference to uninitialized memory! - /// // This is undefined behavior. + /// // ^^^^^^^^^^^^^^^^^^^^^ + /// // (mutable) reference to uninitialized memory! + /// // This is undefined behavior. /// ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42); - /// // ^^^^^^^^^^^^^^^^^^^^^ - /// // (mutable) reference to uninitialized memory! - /// // This is undefined behavior. + /// // ^^^^^^^^^^^^^^^^^^^^^ + /// // (mutable) reference to uninitialized memory! + /// // This is undefined behavior. /// foo.assume_init() /// }; /// ``` @@ -929,9 +931,7 @@ impl MaybeUninit { /// array[2].write(2); /// /// // SAFETY: Now safe as we initialised all elements - /// let array = unsafe { - /// MaybeUninit::array_assume_init(array) - /// }; + /// let array = unsafe { MaybeUninit::array_assume_init(array) }; /// /// assert_eq!(array, [0, 1, 2]); /// ``` @@ -1089,8 +1089,20 @@ impl MaybeUninit { /// #![feature(maybe_uninit_write_slice)] /// use std::mem::MaybeUninit; /// - /// let mut dst = [MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit()]; - /// let src = ["wibbly".to_string(), "wobbly".to_string(), "timey".to_string(), "wimey".to_string(), "stuff".to_string()]; + /// let mut dst = [ + /// MaybeUninit::uninit(), + /// MaybeUninit::uninit(), + /// MaybeUninit::uninit(), + /// MaybeUninit::uninit(), + /// MaybeUninit::uninit(), + /// ]; + /// let src = [ + /// "wibbly".to_string(), + /// "wobbly".to_string(), + /// "timey".to_string(), + /// "wimey".to_string(), + /// "stuff".to_string(), + /// ]; /// /// let init = MaybeUninit::write_slice_cloned(&mut dst, &src); /// diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index 2e1a667097c01..ede1364ce24e7 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -72,8 +72,8 @@ pub use crate::intrinsics::transmute; /// the space taken by the variable but never close the underlying system resource: /// /// ```no_run -/// use std::mem; /// use std::fs::File; +/// use std::mem; /// /// let file = File::open("foo.txt").unwrap(); /// mem::forget(file); @@ -95,7 +95,7 @@ pub use crate::intrinsics::transmute; /// // Build a `String` using the contents of `v` /// let s = unsafe { String::from_raw_parts(v.as_mut_ptr(), v.len(), v.capacity()) }; /// // leak `v` because its memory is now managed by `s` -/// mem::forget(v); // ERROR - v is invalid and must not be passed to a function +/// mem::forget(v); // ERROR - v is invalid and must not be passed to a function /// assert_eq!(s, "Az"); /// // `s` is implicitly dropped and its memory deallocated. /// ``` @@ -247,7 +247,6 @@ pub fn forget_unsized(t: T) { /// assert_eq!(12, mem::size_of::<[i32; 3]>()); /// assert_eq!(0, mem::size_of::<[i32; 0]>()); /// -/// /// // Pointer size equality /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>()); /// assert_eq!(mem::size_of::<&i32>(), mem::size_of::>()); @@ -264,7 +263,7 @@ pub fn forget_unsized(t: T) { /// struct FieldStruct { /// first: u8, /// second: u16, -/// third: u8 +/// third: u8, /// } /// /// // The size of the first field is 1, so add 1 to the size. Size is 1. @@ -288,7 +287,7 @@ pub fn forget_unsized(t: T) { /// struct FieldStructOptimized { /// first: u8, /// third: u8, -/// second: u16 +/// second: u16, /// } /// /// assert_eq!(4, mem::size_of::()); @@ -297,7 +296,7 @@ pub fn forget_unsized(t: T) { /// #[repr(C)] /// union ExampleUnion { /// smaller: u8, -/// larger: u16 +/// larger: u16, /// } /// /// assert_eq!(2, mem::size_of::()); @@ -931,7 +930,7 @@ pub const fn replace(dest: &mut T, src: T) -> T { /// This function is not magic; it is literally defined as /// /// ``` -/// pub fn drop(_x: T) { } +/// pub fn drop(_x: T) {} /// ``` /// /// Because `_x` is moved into the function, it is automatically dropped before @@ -990,7 +989,9 @@ pub fn drop(_x: T) {} /// /// This function is not magic; it is literally defined as /// ``` -/// pub fn copy(x: &T) -> T { *x } +/// pub fn copy(x: &T) -> T { +/// *x +/// } /// ``` /// /// It is useful when you want to pass a function pointer to a combinator, rather than defining a new closure. @@ -1131,7 +1132,11 @@ impl fmt::Debug for Discriminant { /// ``` /// use std::mem; /// -/// enum Foo { A(&'static str), B(i32), C(i32) } +/// enum Foo { +/// A(&'static str), +/// B(i32), +/// C(i32), +/// } /// /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz"))); /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2))); @@ -1164,7 +1169,11 @@ pub const fn discriminant(v: &T) -> Discriminant { /// use std::mem; /// /// enum Void {} -/// enum Foo { A(&'static str), B(i32), C(i32) } +/// enum Foo { +/// A(&'static str), +/// B(i32), +/// C(i32), +/// } /// /// assert_eq!(mem::variant_count::(), 0); /// assert_eq!(mem::variant_count::(), 3); diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs index 2c6a0ba64f266..a58c72349c133 100644 --- a/library/core/src/num/f32.rs +++ b/library/core/src/num/f32.rs @@ -988,7 +988,6 @@ impl f32 { /// ``` /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting! /// assert_eq!((12.5f32).to_bits(), 0x41480000); - /// /// ``` #[must_use = "this returns the result of the operation, \ without modifying the original"] diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs index fd3c18ce29bd2..4171763d819d2 100644 --- a/library/core/src/num/f64.rs +++ b/library/core/src/num/f64.rs @@ -999,7 +999,6 @@ impl f64 { /// ``` /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting! /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000); - /// /// ``` #[must_use = "this returns the result of the operation, \ without modifying the original"] diff --git a/library/core/src/num/flt2dec/decoder.rs b/library/core/src/num/flt2dec/decoder.rs index 5763860540aa4..cd70516025e95 100644 --- a/library/core/src/num/flt2dec/decoder.rs +++ b/library/core/src/num/flt2dec/decoder.rs @@ -59,7 +59,7 @@ impl DecodableFloat for f64 { /// Returns a sign (true when negative) and `FullDecoded` value /// from given floating point number. -pub fn decode(v: T) -> (/*negative?*/ bool, FullDecoded) { +pub fn decode(v: T) -> (/* negative? */ bool, FullDecoded) { let (mant, exp, sign) = v.integer_decode(); let even = (mant & 1) == 0; let decoded = match v.classify() { diff --git a/library/core/src/num/flt2dec/strategy/dragon.rs b/library/core/src/num/flt2dec/strategy/dragon.rs index 8ced5971ec2f9..1719b07c83c89 100644 --- a/library/core/src/num/flt2dec/strategy/dragon.rs +++ b/library/core/src/num/flt2dec/strategy/dragon.rs @@ -101,7 +101,7 @@ fn div_rem_upto_16<'a>( pub fn format_shortest<'a>( d: &Decoded, buf: &'a mut [MaybeUninit], -) -> (/*digits*/ &'a [u8], /*exp*/ i16) { +) -> (/* digits */ &'a [u8], /* exp */ i16) { // the number `v` to format is known to be: // - equal to `mant * 2^exp`; // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and @@ -262,7 +262,7 @@ pub fn format_exact<'a>( d: &Decoded, buf: &'a mut [MaybeUninit], limit: i16, -) -> (/*digits*/ &'a [u8], /*exp*/ i16) { +) -> (/* digits */ &'a [u8], /* exp */ i16) { assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); diff --git a/library/core/src/num/flt2dec/strategy/grisu.rs b/library/core/src/num/flt2dec/strategy/grisu.rs index ed3e0edaff2a2..9ee9ca9fc580f 100644 --- a/library/core/src/num/flt2dec/strategy/grisu.rs +++ b/library/core/src/num/flt2dec/strategy/grisu.rs @@ -165,7 +165,7 @@ pub fn max_pow10_no_more_than(x: u32) -> (u8, u32) { pub fn format_shortest_opt<'a>( d: &Decoded, buf: &'a mut [MaybeUninit], -) -> Option<(/*digits*/ &'a [u8], /*exp*/ i16)> { +) -> Option<(/* digits */ &'a [u8], /* exp */ i16)> { assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); @@ -454,7 +454,7 @@ pub fn format_shortest_opt<'a>( pub fn format_shortest<'a>( d: &Decoded, buf: &'a mut [MaybeUninit], -) -> (/*digits*/ &'a [u8], /*exp*/ i16) { +) -> (/* digits */ &'a [u8], /* exp */ i16) { use crate::num::flt2dec::strategy::dragon::format_shortest as fallback; // SAFETY: The borrow checker is not smart enough to let us use `buf` // in the second branch, so we launder the lifetime here. But we only re-use @@ -472,7 +472,7 @@ pub fn format_exact_opt<'a>( d: &Decoded, buf: &'a mut [MaybeUninit], limit: i16, -) -> Option<(/*digits*/ &'a [u8], /*exp*/ i16)> { +) -> Option<(/* digits */ &'a [u8], /* exp */ i16)> { assert!(d.mant > 0); assert!(d.mant < (1 << 61)); // we need at least three bits of additional precision assert!(!buf.is_empty()); @@ -748,7 +748,7 @@ pub fn format_exact<'a>( d: &Decoded, buf: &'a mut [MaybeUninit], limit: i16, -) -> (/*digits*/ &'a [u8], /*exp*/ i16) { +) -> (/* digits */ &'a [u8], /* exp */ i16) { use crate::num::flt2dec::strategy::dragon::format_exact as fallback; // SAFETY: The borrow checker is not smart enough to let us use `buf` // in the second branch, so we launder the lifetime here. But we only re-use diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index 311c5fa5b6834..d9f7a33a7eabd 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -858,7 +858,6 @@ impl u8 { /// # Examples /// /// ``` - /// /// assert_eq!("0", b'0'.escape_ascii().to_string()); /// assert_eq!("\\t", b'\t'.escape_ascii().to_string()); /// assert_eq!("\\r", b'\r'.escape_ascii().to_string()); diff --git a/library/core/src/ops/arith.rs b/library/core/src/ops/arith.rs index 75c52d3ecfc8b..75edf2c2c053d 100644 --- a/library/core/src/ops/arith.rs +++ b/library/core/src/ops/arith.rs @@ -23,15 +23,11 @@ /// type Output = Self; /// /// fn add(self, other: Self) -> Self { -/// Self { -/// x: self.x + other.x, -/// y: self.y + other.y, -/// } +/// Self { x: self.x + other.x, y: self.y + other.y } /// } /// } /// -/// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, -/// Point { x: 3, y: 3 }); +/// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, Point { x: 3, y: 3 }); /// ``` /// /// ## Implementing `Add` with generics @@ -53,15 +49,11 @@ /// type Output = Self; /// /// fn add(self, other: Self) -> Self::Output { -/// Self { -/// x: self.x + other.x, -/// y: self.y + other.y, -/// } +/// Self { x: self.x + other.x, y: self.y + other.y } /// } /// } /// -/// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, -/// Point { x: 3, y: 3 }); +/// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, Point { x: 3, y: 3 }); /// ``` #[lang = "add"] #[stable(feature = "rust1", since = "1.0.0")] @@ -134,15 +126,11 @@ add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// type Output = Self; /// /// fn sub(self, other: Self) -> Self::Output { -/// Self { -/// x: self.x - other.x, -/// y: self.y - other.y, -/// } +/// Self { x: self.x - other.x, y: self.y - other.y } /// } /// } /// -/// assert_eq!(Point { x: 3, y: 3 } - Point { x: 2, y: 3 }, -/// Point { x: 1, y: 0 }); +/// assert_eq!(Point { x: 3, y: 3 } - Point { x: 2, y: 3 }, Point { x: 1, y: 0 }); /// ``` /// /// ## Implementing `Sub` with generics @@ -164,15 +152,11 @@ add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// type Output = Self; /// /// fn sub(self, other: Self) -> Self::Output { -/// Point { -/// x: self.x - other.x, -/// y: self.y - other.y, -/// } +/// Point { x: self.x - other.x, y: self.y - other.y } /// } /// } /// -/// assert_eq!(Point { x: 2, y: 3 } - Point { x: 1, y: 0 }, -/// Point { x: 1, y: 3 }); +/// assert_eq!(Point { x: 2, y: 3 } - Point { x: 1, y: 0 }, Point { x: 1, y: 3 }); /// ``` #[lang = "sub"] #[stable(feature = "rust1", since = "1.0.0")] @@ -247,10 +231,7 @@ sub_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// // Reduce to lowest terms by dividing by the greatest common /// // divisor. /// let gcd = gcd(numerator, denominator); -/// Self { -/// numerator: numerator / gcd, -/// denominator: denominator / gcd, -/// } +/// Self { numerator: numerator / gcd, denominator: denominator / gcd } /// } /// } /// @@ -279,8 +260,7 @@ sub_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// } /// /// assert_eq!(Rational::new(1, 2), Rational::new(2, 4)); -/// assert_eq!(Rational::new(2, 3) * Rational::new(3, 4), -/// Rational::new(1, 2)); +/// assert_eq!(Rational::new(2, 3) * Rational::new(3, 4), Rational::new(1, 2)); /// ``` /// /// ## Multiplying vectors by scalars as in linear algebra @@ -288,10 +268,14 @@ sub_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// ``` /// use std::ops::Mul; /// -/// struct Scalar { value: usize } +/// struct Scalar { +/// value: usize, +/// } /// /// #[derive(Debug, PartialEq)] -/// struct Vector { value: Vec } +/// struct Vector { +/// value: Vec, +/// } /// /// impl Mul for Vector { /// type Output = Self; @@ -377,10 +361,7 @@ mul_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// // Reduce to lowest terms by dividing by the greatest common /// // divisor. /// let gcd = gcd(numerator, denominator); -/// Self { -/// numerator: numerator / gcd, -/// denominator: denominator / gcd, -/// } +/// Self { numerator: numerator / gcd, denominator: denominator / gcd } /// } /// } /// @@ -413,8 +394,7 @@ mul_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// } /// /// assert_eq!(Rational::new(1, 2), Rational::new(2, 4)); -/// assert_eq!(Rational::new(1, 2) / Rational::new(3, 4), -/// Rational::new(2, 3)); +/// assert_eq!(Rational::new(1, 2) / Rational::new(3, 4), Rational::new(2, 3)); /// ``` /// /// ## Dividing vectors by scalars as in linear algebra @@ -422,10 +402,14 @@ mul_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// ``` /// use std::ops::Div; /// -/// struct Scalar { value: f32 } +/// struct Scalar { +/// value: f32, +/// } /// /// #[derive(Debug, PartialEq)] -/// struct Vector { value: Vec } +/// struct Vector { +/// value: Vec, +/// } /// /// impl Div for Vector { /// type Output = Self; @@ -533,14 +517,13 @@ div_impl_float! { f32 f64 } /// let len = self.slice.len(); /// let rem = len % modulus; /// let start = len - rem; -/// Self {slice: &self.slice[start..]} +/// Self { slice: &self.slice[start..] } /// } /// } /// /// // If we were to divide &[0, 1, 2, 3, 4, 5, 6, 7] into slices of size 3, /// // the remainder would be &[6, 7]. -/// assert_eq!(SplitSlice { slice: &[0, 1, 2, 3, 4, 5, 6, 7] } % 3, -/// SplitSlice { slice: &[6, 7] }); +/// assert_eq!(SplitSlice { slice: &[0, 1, 2, 3, 4, 5, 6, 7] } % 3, SplitSlice { slice: &[6, 7] }); /// ``` #[lang = "rem"] #[stable(feature = "rust1", since = "1.0.0")] @@ -719,10 +702,7 @@ neg_impl! { isize i8 i16 i32 i64 i128 f32 f64 } /// /// impl AddAssign for Point { /// fn add_assign(&mut self, other: Self) { -/// *self = Self { -/// x: self.x + other.x, -/// y: self.y + other.y, -/// }; +/// *self = Self { x: self.x + other.x, y: self.y + other.y }; /// } /// } /// @@ -787,16 +767,13 @@ add_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// /// impl SubAssign for Point { /// fn sub_assign(&mut self, other: Self) { -/// *self = Self { -/// x: self.x - other.x, -/// y: self.y - other.y, -/// }; +/// *self = Self { x: self.x - other.x, y: self.y - other.y }; /// } /// } /// /// let mut point = Point { x: 3, y: 3 }; /// point -= Point { x: 2, y: 3 }; -/// assert_eq!(point, Point {x: 1, y: 0}); +/// assert_eq!(point, Point { x: 1, y: 0 }); /// ``` #[lang = "sub_assign"] #[stable(feature = "op_assign_traits", since = "1.8.0")] @@ -845,7 +822,9 @@ sub_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// use std::ops::MulAssign; /// /// #[derive(Debug, PartialEq)] -/// struct Frequency { hertz: f64 } +/// struct Frequency { +/// hertz: f64, +/// } /// /// impl MulAssign for Frequency { /// fn mul_assign(&mut self, rhs: f64) { @@ -904,7 +883,9 @@ mul_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// use std::ops::DivAssign; /// /// #[derive(Debug, PartialEq)] -/// struct Frequency { hertz: f64 } +/// struct Frequency { +/// hertz: f64, +/// } /// /// impl DivAssign for Frequency { /// fn div_assign(&mut self, rhs: f64) { @@ -961,7 +942,9 @@ div_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// ``` /// use std::ops::RemAssign; /// -/// struct CookieJar { cookies: u32 } +/// struct CookieJar { +/// cookies: u32, +/// } /// /// impl RemAssign for CookieJar { /// fn rem_assign(&mut self, piles: u32) { diff --git a/library/core/src/ops/bit.rs b/library/core/src/ops/bit.rs index 327009801d1bd..98ebe34ec9cd3 100644 --- a/library/core/src/ops/bit.rs +++ b/library/core/src/ops/bit.rs @@ -20,7 +20,7 @@ /// fn not(self) -> Self::Output { /// match self { /// Answer::Yes => Answer::No, -/// Answer::No => Answer::Yes +/// Answer::No => Answer::Yes, /// } /// } /// } @@ -123,12 +123,7 @@ impl const Not for ! { /// fn bitand(self, Self(rhs): Self) -> Self::Output { /// let Self(lhs) = self; /// assert_eq!(lhs.len(), rhs.len()); -/// Self( -/// lhs.iter() -/// .zip(rhs.iter()) -/// .map(|(x, y)| *x & *y) -/// .collect() -/// ) +/// Self(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x & *y).collect()) /// } /// } /// @@ -225,12 +220,7 @@ bitand_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } /// fn bitor(self, Self(rhs): Self) -> Self::Output { /// let Self(lhs) = self; /// assert_eq!(lhs.len(), rhs.len()); -/// Self( -/// lhs.iter() -/// .zip(rhs.iter()) -/// .map(|(x, y)| *x | *y) -/// .collect() -/// ) +/// Self(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x | *y).collect()) /// } /// } /// @@ -327,12 +317,7 @@ bitor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } /// fn bitxor(self, Self(rhs): Self) -> Self::Output { /// let Self(lhs) = self; /// assert_eq!(lhs.len(), rhs.len()); -/// Self( -/// lhs.iter() -/// .zip(rhs.iter()) -/// .map(|(x, y)| *x ^ *y) -/// .collect() -/// ) +/// Self(lhs.iter().zip(rhs.iter()).map(|(x, y)| *x ^ *y).collect()) /// } /// } /// @@ -439,8 +424,10 @@ bitxor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } /// } /// } /// -/// assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } << 2, -/// SpinVector { vec: vec![2, 3, 4, 0, 1] }); +/// assert_eq!( +/// SpinVector { vec: vec![0, 1, 2, 3, 4] } << 2, +/// SpinVector { vec: vec![2, 3, 4, 0, 1] } +/// ); /// ``` #[lang = "shl"] #[doc(alias = "<<")] @@ -559,8 +546,10 @@ shl_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 isize i128 } /// } /// } /// -/// assert_eq!(SpinVector { vec: vec![0, 1, 2, 3, 4] } >> 2, -/// SpinVector { vec: vec![3, 4, 0, 1, 2] }); +/// assert_eq!( +/// SpinVector { vec: vec![0, 1, 2, 3, 4] } >> 2, +/// SpinVector { vec: vec![3, 4, 0, 1, 2] } +/// ); /// ``` #[lang = "shr"] #[doc(alias = ">>")] @@ -676,13 +665,7 @@ shr_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize } /// // `rhs` is the "right-hand side" of the expression `a &= b`. /// fn bitand_assign(&mut self, rhs: Self) { /// assert_eq!(self.0.len(), rhs.0.len()); -/// *self = Self( -/// self.0 -/// .iter() -/// .zip(rhs.0.iter()) -/// .map(|(x, y)| *x & *y) -/// .collect() -/// ); +/// *self = Self(self.0.iter().zip(rhs.0.iter()).map(|(x, y)| *x & *y).collect()); /// } /// } /// @@ -835,7 +818,7 @@ bitor_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } /// /// let mut personality = Personality { has_soul: false, likes_knitting: true }; /// personality ^= Personality { has_soul: true, likes_knitting: true }; -/// assert_eq!(personality, Personality { has_soul: true, likes_knitting: false}); +/// assert_eq!(personality, Personality { has_soul: true, likes_knitting: false }); /// ``` #[lang = "bitxor_assign"] #[doc(alias = "^=")] diff --git a/library/core/src/ops/control_flow.rs b/library/core/src/ops/control_flow.rs index cd183540cd5e9..2fa323e92dc81 100644 --- a/library/core/src/ops/control_flow.rs +++ b/library/core/src/ops/control_flow.rs @@ -19,7 +19,7 @@ use crate::{convert, ops}; /// /// let r = (2..100).try_for_each(|x| { /// if 403 % x == 0 { -/// return ControlFlow::Break(x) +/// return ControlFlow::Break(x); /// } /// /// ControlFlow::Continue(()) @@ -38,7 +38,10 @@ use crate::{convert, ops}; /// } /// /// impl TreeNode { -/// pub fn traverse_inorder(&self, f: &mut impl FnMut(&T) -> ControlFlow) -> ControlFlow { +/// pub fn traverse_inorder( +/// &self, +/// f: &mut impl FnMut(&T) -> ControlFlow, +/// ) -> ControlFlow { /// if let Some(left) = &self.left { /// left.traverse_inorder(f)?; /// } @@ -60,7 +63,7 @@ use crate::{convert, ops}; /// value: -1, /// left: TreeNode::leaf(5), /// right: TreeNode::leaf(2), -/// })) +/// })), /// }; /// let mut sum = 0; /// @@ -273,8 +276,7 @@ impl ControlFlow { /// let mut partial_sum = 0; /// let last_used = (1..10).chain(20..25).try_for_each(|x| { /// partial_sum += x; - /// if partial_sum > 100 { ControlFlow::Break(x) } - /// else { ControlFlow::CONTINUE } + /// if partial_sum > 100 { ControlFlow::Break(x) } else { ControlFlow::CONTINUE } /// }); /// assert_eq!(last_used.break_value(), Some(22)); /// ``` @@ -294,8 +296,12 @@ impl ControlFlow<(), C> { /// /// let mut partial_sum = 0; /// (1..10).chain(20..25).try_for_each(|x| { - /// if partial_sum > 100 { ControlFlow::BREAK } - /// else { partial_sum += x; ControlFlow::CONTINUE } + /// if partial_sum > 100 { + /// ControlFlow::BREAK + /// } else { + /// partial_sum += x; + /// ControlFlow::CONTINUE + /// } /// }); /// assert_eq!(partial_sum, 108); /// ``` diff --git a/library/core/src/ops/deref.rs b/library/core/src/ops/deref.rs index 4f4c99c4ad97c..61431ca776519 100644 --- a/library/core/src/ops/deref.rs +++ b/library/core/src/ops/deref.rs @@ -42,7 +42,7 @@ /// use std::ops::Deref; /// /// struct DerefExample { -/// value: T +/// value: T, /// } /// /// impl Deref for DerefExample { @@ -146,7 +146,7 @@ impl const Deref for &mut T { /// use std::ops::{Deref, DerefMut}; /// /// struct DerefMutExample { -/// value: T +/// value: T, /// } /// /// impl Deref for DerefMutExample { diff --git a/library/core/src/ops/function.rs b/library/core/src/ops/function.rs index 2e0a752c815d9..0f9f7598d16ca 100644 --- a/library/core/src/ops/function.rs +++ b/library/core/src/ops/function.rs @@ -44,7 +44,9 @@ /// /// ``` /// fn call_with_one(func: F) -> usize -/// where F: Fn(usize) -> usize { +/// where +/// F: Fn(usize) -> usize, +/// { /// func(1) /// } /// @@ -125,7 +127,8 @@ pub trait Fn: FnMut { /// /// ``` /// fn do_twice(mut func: F) -/// where F: FnMut() +/// where +/// F: FnMut(), /// { /// func(); /// func(); @@ -201,7 +204,8 @@ pub trait FnMut: FnOnce { /// /// ``` /// fn consume_with_relish(func: F) -/// where F: FnOnce() -> String +/// where +/// F: FnOnce() -> String, /// { /// // `func` consumes its captured variables, so it cannot be run more /// // than once. diff --git a/library/core/src/ops/index.rs b/library/core/src/ops/index.rs index dd4e3ac1c2fe5..d25c1ccaab541 100644 --- a/library/core/src/ops/index.rs +++ b/library/core/src/ops/index.rs @@ -40,7 +40,7 @@ /// } /// } /// -/// let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12}; +/// let nucleotide_count = NucleotideCount { a: 14, c: 9, g: 10, t: 12 }; /// assert_eq!(nucleotide_count[Nucleotide::A], 14); /// assert_eq!(nucleotide_count[Nucleotide::C], 9); /// assert_eq!(nucleotide_count[Nucleotide::G], 10); @@ -125,10 +125,7 @@ pub trait Index { /// } /// } /// -/// let mut balance = Balance { -/// right: Weight::Kilogram(2.5), -/// left: Weight::Pound(1.5), -/// }; +/// let mut balance = Balance { right: Weight::Kilogram(2.5), left: Weight::Pound(1.5) }; /// /// // In this case, `balance[Side::Right]` is sugar for /// // `*balance.index(Side::Right)`, since we are only *reading* diff --git a/library/core/src/ops/mod.rs b/library/core/src/ops/mod.rs index a5e5b13b33674..865bcf7f8f672 100644 --- a/library/core/src/ops/mod.rs +++ b/library/core/src/ops/mod.rs @@ -52,7 +52,7 @@ //! type Output = Self; //! //! fn add(self, other: Self) -> Self { -//! Self {x: self.x + other.x, y: self.y + other.y} +//! Self { x: self.x + other.x, y: self.y + other.y } //! } //! } //! @@ -60,12 +60,12 @@ //! type Output = Self; //! //! fn sub(self, other: Self) -> Self { -//! Self {x: self.x - other.x, y: self.y - other.y} +//! Self { x: self.x - other.x, y: self.y - other.y } //! } //! } //! -//! assert_eq!(Point {x: 3, y: 3}, Point {x: 1, y: 0} + Point {x: 2, y: 3}); -//! assert_eq!(Point {x: -1, y: -3}, Point {x: 1, y: 0} - Point {x: 2, y: 3}); +//! assert_eq!(Point { x: 3, y: 3 }, Point { x: 1, y: 0 } + Point { x: 2, y: 3 }); +//! assert_eq!(Point { x: -1, y: -3 }, Point { x: 1, y: 0 } - Point { x: 2, y: 3 }); //! ``` //! //! See the documentation for each trait for an example implementation. @@ -82,7 +82,8 @@ //! //! ```rust //! fn call_with_one(func: F) -> usize -//! where F: Fn(usize) -> usize +//! where +//! F: Fn(usize) -> usize, //! { //! func(1) //! } @@ -95,7 +96,8 @@ //! //! ```rust //! fn do_twice(mut func: F) -//! where F: FnMut() +//! where +//! F: FnMut(), //! { //! func(); //! func(); @@ -114,7 +116,8 @@ //! //! ```rust //! fn consume_with_relish(func: F) -//! where F: FnOnce() -> String +//! where +//! F: FnOnce() -> String, //! { //! // `func` consumes its captured variables, so it cannot be run more //! // than once diff --git a/library/core/src/ops/range.rs b/library/core/src/ops/range.rs index d29ae35614c1c..e89a83868395a 100644 --- a/library/core/src/ops/range.rs +++ b/library/core/src/ops/range.rs @@ -27,12 +27,12 @@ use crate::hash::Hash; /// /// ``` /// let arr = [0, 1, 2, 3, 4]; -/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]); // This is the `RangeFull` -/// assert_eq!(arr[ .. 3], [0, 1, 2 ]); -/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]); -/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]); -/// assert_eq!(arr[1.. 3], [ 1, 2 ]); -/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]); +/// assert_eq!(arr[..], [0, 1, 2, 3, 4]); // This is the `RangeFull` +/// assert_eq!(arr[..3], [0, 1, 2]); +/// assert_eq!(arr[..=3], [0, 1, 2, 3]); +/// assert_eq!(arr[1..], [1, 2, 3, 4]); +/// assert_eq!(arr[1..3], [1, 2]); +/// assert_eq!(arr[1..=3], [1, 2, 3]); /// ``` /// /// [slicing index]: crate::slice::SliceIndex @@ -66,12 +66,12 @@ impl fmt::Debug for RangeFull { /// /// ``` /// let arr = [0, 1, 2, 3, 4]; -/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]); -/// assert_eq!(arr[ .. 3], [0, 1, 2 ]); -/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]); -/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]); -/// assert_eq!(arr[1.. 3], [ 1, 2 ]); // This is a `Range` -/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]); +/// assert_eq!(arr[..], [0, 1, 2, 3, 4]); +/// assert_eq!(arr[..3], [0, 1, 2]); +/// assert_eq!(arr[..=3], [0, 1, 2, 3]); +/// assert_eq!(arr[1..], [1, 2, 3, 4]); +/// assert_eq!(arr[1..3], [1, 2]); // This is a `Range` +/// assert_eq!(arr[1..=3], [1, 2, 3]); /// ``` #[lang = "Range"] #[doc(alias = "..")] @@ -103,14 +103,14 @@ impl> Range { /// /// ``` /// assert!(!(3..5).contains(&2)); - /// assert!( (3..5).contains(&3)); - /// assert!( (3..5).contains(&4)); + /// assert!((3..5).contains(&3)); + /// assert!((3..5).contains(&4)); /// assert!(!(3..5).contains(&5)); /// /// assert!(!(3..3).contains(&3)); /// assert!(!(3..2).contains(&3)); /// - /// assert!( (0.0..1.0).contains(&0.5)); + /// assert!((0.0..1.0).contains(&0.5)); /// assert!(!(0.0..1.0).contains(&f32::NAN)); /// assert!(!(0.0..f32::NAN).contains(&0.5)); /// assert!(!(f32::NAN..1.0).contains(&0.5)); @@ -130,16 +130,16 @@ impl> Range { /// /// ``` /// assert!(!(3..5).is_empty()); - /// assert!( (3..3).is_empty()); - /// assert!( (3..2).is_empty()); + /// assert!((3..3).is_empty()); + /// assert!((3..2).is_empty()); /// ``` /// /// The range is empty if either side is incomparable: /// /// ``` /// assert!(!(3.0..5.0).is_empty()); - /// assert!( (3.0..f32::NAN).is_empty()); - /// assert!( (f32::NAN..5.0).is_empty()); + /// assert!((3.0..f32::NAN).is_empty()); + /// assert!((f32::NAN..5.0).is_empty()); /// ``` #[stable(feature = "range_is_empty", since = "1.47.0")] pub fn is_empty(&self) -> bool { @@ -173,12 +173,12 @@ impl> Range { /// /// ``` /// let arr = [0, 1, 2, 3, 4]; -/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]); -/// assert_eq!(arr[ .. 3], [0, 1, 2 ]); -/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]); -/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]); // This is a `RangeFrom` -/// assert_eq!(arr[1.. 3], [ 1, 2 ]); -/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]); +/// assert_eq!(arr[..], [0, 1, 2, 3, 4]); +/// assert_eq!(arr[..3], [0, 1, 2]); +/// assert_eq!(arr[..=3], [0, 1, 2, 3]); +/// assert_eq!(arr[1..], [1, 2, 3, 4]); // This is a `RangeFrom` +/// assert_eq!(arr[1..3], [1, 2]); +/// assert_eq!(arr[1..=3], [1, 2, 3]); /// ``` #[lang = "RangeFrom"] #[doc(alias = "..")] @@ -206,10 +206,10 @@ impl> RangeFrom { /// /// ``` /// assert!(!(3..).contains(&2)); - /// assert!( (3..).contains(&3)); - /// assert!( (3..).contains(&1_000_000_000)); + /// assert!((3..).contains(&3)); + /// assert!((3..).contains(&1_000_000_000)); /// - /// assert!( (0.0..).contains(&0.5)); + /// assert!((0.0..).contains(&0.5)); /// assert!(!(0.0..).contains(&f32::NAN)); /// assert!(!(f32::NAN..).contains(&0.5)); /// ``` @@ -252,12 +252,12 @@ impl> RangeFrom { /// /// ``` /// let arr = [0, 1, 2, 3, 4]; -/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]); -/// assert_eq!(arr[ .. 3], [0, 1, 2 ]); // This is a `RangeTo` -/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]); -/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]); -/// assert_eq!(arr[1.. 3], [ 1, 2 ]); -/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]); +/// assert_eq!(arr[..], [0, 1, 2, 3, 4]); +/// assert_eq!(arr[..3], [0, 1, 2]); // This is a `RangeTo` +/// assert_eq!(arr[..=3], [0, 1, 2, 3]); +/// assert_eq!(arr[1..], [1, 2, 3, 4]); +/// assert_eq!(arr[1..3], [1, 2]); +/// assert_eq!(arr[1..=3], [1, 2, 3]); /// ``` /// /// [slicing index]: crate::slice::SliceIndex @@ -286,11 +286,11 @@ impl> RangeTo { /// # Examples /// /// ``` - /// assert!( (..5).contains(&-1_000_000_000)); - /// assert!( (..5).contains(&4)); + /// assert!((..5).contains(&-1_000_000_000)); + /// assert!((..5).contains(&4)); /// assert!(!(..5).contains(&5)); /// - /// assert!( (..1.0).contains(&0.5)); + /// assert!((..1.0).contains(&0.5)); /// assert!(!(..1.0).contains(&f32::NAN)); /// assert!(!(..f32::NAN).contains(&0.5)); /// ``` @@ -327,12 +327,12 @@ impl> RangeTo { /// /// ``` /// let arr = [0, 1, 2, 3, 4]; -/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]); -/// assert_eq!(arr[ .. 3], [0, 1, 2 ]); -/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]); -/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]); -/// assert_eq!(arr[1.. 3], [ 1, 2 ]); -/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]); // This is a `RangeInclusive` +/// assert_eq!(arr[..], [0, 1, 2, 3, 4]); +/// assert_eq!(arr[..3], [0, 1, 2]); +/// assert_eq!(arr[..=3], [0, 1, 2, 3]); +/// assert_eq!(arr[1..], [1, 2, 3, 4]); +/// assert_eq!(arr[1..3], [1, 2]); +/// assert_eq!(arr[1..=3], [1, 2, 3]); // This is a `RangeInclusive` /// ``` #[lang = "RangeInclusive"] #[doc(alias = "..=")] @@ -476,15 +476,15 @@ impl> RangeInclusive { /// /// ``` /// assert!(!(3..=5).contains(&2)); - /// assert!( (3..=5).contains(&3)); - /// assert!( (3..=5).contains(&4)); - /// assert!( (3..=5).contains(&5)); + /// assert!((3..=5).contains(&3)); + /// assert!((3..=5).contains(&4)); + /// assert!((3..=5).contains(&5)); /// assert!(!(3..=5).contains(&6)); /// - /// assert!( (3..=3).contains(&3)); + /// assert!((3..=3).contains(&3)); /// assert!(!(3..=2).contains(&3)); /// - /// assert!( (0.0..=1.0).contains(&1.0)); + /// assert!((0.0..=1.0).contains(&1.0)); /// assert!(!(0.0..=1.0).contains(&f32::NAN)); /// assert!(!(0.0..=f32::NAN).contains(&0.0)); /// assert!(!(f32::NAN..=1.0).contains(&1.0)); @@ -515,15 +515,15 @@ impl> RangeInclusive { /// ``` /// assert!(!(3..=5).is_empty()); /// assert!(!(3..=3).is_empty()); - /// assert!( (3..=2).is_empty()); + /// assert!((3..=2).is_empty()); /// ``` /// /// The range is empty if either side is incomparable: /// /// ``` /// assert!(!(3.0..=5.0).is_empty()); - /// assert!( (3.0..=f32::NAN).is_empty()); - /// assert!( (f32::NAN..=5.0).is_empty()); + /// assert!((3.0..=f32::NAN).is_empty()); + /// assert!((f32::NAN..=5.0).is_empty()); /// ``` /// /// This method returns `true` after iteration has finished: @@ -551,7 +551,7 @@ impl> RangeInclusive { /// The `..=end` syntax is a `RangeToInclusive`: /// /// ``` -/// assert_eq!((..=5), std::ops::RangeToInclusive{ end: 5 }); +/// assert_eq!((..=5), std::ops::RangeToInclusive { end: 5 }); /// ``` /// /// It does not have an [`IntoIterator`] implementation, so you can't use it in a @@ -570,12 +570,12 @@ impl> RangeInclusive { /// /// ``` /// let arr = [0, 1, 2, 3, 4]; -/// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]); -/// assert_eq!(arr[ .. 3], [0, 1, 2 ]); -/// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]); // This is a `RangeToInclusive` -/// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]); -/// assert_eq!(arr[1.. 3], [ 1, 2 ]); -/// assert_eq!(arr[1..=3], [ 1, 2, 3 ]); +/// assert_eq!(arr[..], [0, 1, 2, 3, 4]); +/// assert_eq!(arr[..3], [0, 1, 2]); +/// assert_eq!(arr[..=3], [0, 1, 2, 3]); // This is a `RangeToInclusive` +/// assert_eq!(arr[1..], [1, 2, 3, 4]); +/// assert_eq!(arr[1..3], [1, 2]); +/// assert_eq!(arr[1..=3], [1, 2, 3]); /// ``` /// /// [slicing index]: crate::slice::SliceIndex @@ -604,11 +604,11 @@ impl> RangeToInclusive { /// # Examples /// /// ``` - /// assert!( (..=5).contains(&-1_000_000_000)); - /// assert!( (..=5).contains(&5)); + /// assert!((..=5).contains(&-1_000_000_000)); + /// assert!((..=5).contains(&5)); /// assert!(!(..=5).contains(&6)); /// - /// assert!( (..=1.0).contains(&1.0)); + /// assert!((..=1.0).contains(&1.0)); /// assert!(!(..=1.0).contains(&f32::NAN)); /// assert!(!(..=f32::NAN).contains(&0.5)); /// ``` diff --git a/library/core/src/ops/unsize.rs b/library/core/src/ops/unsize.rs index a920b9165c18e..7c31b917fe767 100644 --- a/library/core/src/ops/unsize.rs +++ b/library/core/src/ops/unsize.rs @@ -107,10 +107,7 @@ impl, U: ?Sized> CoerceUnsized<*const U> for *const T {} /// # #![feature(dispatch_from_dyn, unsize)] /// # use std::{ops::DispatchFromDyn, marker::Unsize}; /// # struct Rc(std::rc::Rc); -/// impl DispatchFromDyn> for Rc -/// where -/// T: Unsize, -/// {} +/// impl DispatchFromDyn> for Rc where T: Unsize {} /// ``` #[unstable(feature = "dispatch_from_dyn", issue = "none")] #[lang = "dispatch_from_dyn"] diff --git a/library/core/src/option.rs b/library/core/src/option.rs index a81dbc6924fb7..5dad4fe500d64 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -21,11 +21,7 @@ //! //! ``` //! fn divide(numerator: f64, denominator: f64) -> Option { -//! if denominator == 0.0 { -//! None -//! } else { -//! Some(numerator / denominator) -//! } +//! if denominator == 0.0 { None } else { Some(numerator / denominator) } //! } //! //! // The return value of the function is an option @@ -36,13 +32,11 @@ //! // The division was valid //! Some(x) => println!("Result: {x}"), //! // The division was invalid -//! None => println!("Cannot divide by 0"), +//! None => println!("Cannot divide by 0"), //! } //! ``` -//! // // FIXME: Show how `Option` is used in practice, with lots of methods -// //! # Options and pointers ("nullable" pointers) //! //! Rust's pointer types must always point to a valid location; there are @@ -467,7 +461,10 @@ //! Initialize a result to [`None`] before a loop: //! //! ``` -//! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) } +//! enum Kingdom { +//! Plant(u32, &'static str), +//! Animal(u32, &'static str), +//! } //! //! // A list of data to search through. //! let all_the_big_things = [ @@ -490,7 +487,7 @@ //! size_of_biggest_animal = size; //! name_of_biggest_animal = Some(name); //! } -//! Kingdom::Animal(..) | Kingdom::Plant(..) => () +//! Kingdom::Animal(..) | Kingdom::Plant(..) => (), //! } //! } //! @@ -641,7 +638,7 @@ impl Option { /// let mut x = Some(2); /// match x.as_mut() { /// Some(v) => *v = 42, - /// None => {}, + /// None => {} /// } /// assert_eq!(x, Some(42)); /// ``` @@ -719,8 +716,7 @@ impl Option { /// /// ```should_panic /// # let slice: &[u8] = &[]; - /// let item = slice.get(0) - /// .expect("slice should not be empty"); + /// let item = slice.get(0).expect("slice should not be empty"); /// ``` /// /// **Hint**: If you're having trouble remembering how to phrase expect @@ -1119,10 +1115,13 @@ impl Option { /// /// ``` /// let mut x: Option = Some("hey".to_owned()); - /// assert_eq!(x.as_deref_mut().map(|x| { - /// x.make_ascii_uppercase(); - /// x - /// }), Some("HEY".to_owned().as_mut_str())); + /// assert_eq!( + /// x.as_deref_mut().map(|x| { + /// x.make_ascii_uppercase(); + /// x + /// }), + /// Some("HEY".to_owned().as_mut_str()) + /// ); /// ``` #[stable(feature = "option_deref", since = "1.40.0")] #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] @@ -1166,7 +1165,7 @@ impl Option { /// let mut x = Some(4); /// match x.iter_mut().next() { /// Some(v) => *v = 42, - /// None => {}, + /// None => {} /// } /// assert_eq!(x, Some(42)); /// @@ -1353,8 +1352,12 @@ impl Option { /// # Examples /// /// ``` - /// fn nobody() -> Option<&'static str> { None } - /// fn vikings() -> Option<&'static str> { Some("vikings") } + /// fn nobody() -> Option<&'static str> { + /// None + /// } + /// fn vikings() -> Option<&'static str> { + /// Some("vikings") + /// } /// /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians")); /// assert_eq!(None.or_else(vikings), Some("vikings")); @@ -2225,10 +2228,7 @@ impl> FromIterator> for Option { /// ``` /// let items = vec![0_u16, 1, 2]; /// - /// let res: Option> = items - /// .iter() - /// .map(|x| x.checked_add(1)) - /// .collect(); + /// let res: Option> = items.iter().map(|x| x.checked_add(1)).collect(); /// /// assert_eq!(res, Some(vec![1, 2, 3])); /// ``` @@ -2241,10 +2241,7 @@ impl> FromIterator> for Option { /// ``` /// let items = vec![2_u16, 1, 0]; /// - /// let res: Option> = items - /// .iter() - /// .map(|x| x.checked_sub(1)) - /// .collect(); + /// let res: Option> = items.iter().map(|x| x.checked_sub(1)).collect(); /// /// assert_eq!(res, None); /// ``` @@ -2262,7 +2259,10 @@ impl> FromIterator> for Option { /// /// let res: Option> = items /// .iter() - /// .map(|x| { shared += x; x.checked_sub(2) }) + /// .map(|x| { + /// shared += x; + /// x.checked_sub(2) + /// }) /// .collect(); /// /// assert_eq!(res, None); diff --git a/library/core/src/panic/panic_info.rs b/library/core/src/panic/panic_info.rs index 1923155ebc15f..4b03723aa41aa 100644 --- a/library/core/src/panic/panic_info.rs +++ b/library/core/src/panic/panic_info.rs @@ -111,10 +111,7 @@ impl<'a> PanicInfo<'a> { /// /// panic::set_hook(Box::new(|panic_info| { /// if let Some(location) = panic_info.location() { - /// println!("panic occurred in file '{}' at line {}", - /// location.file(), - /// location.line(), - /// ); + /// println!("panic occurred in file '{}' at line {}", location.file(), location.line(),); /// } else { /// println!("panic occurred but can't get location information..."); /// } diff --git a/library/core/src/pin.rs b/library/core/src/pin.rs index ccef35b45325a..4e875134c0244 100644 --- a/library/core/src/pin.rs +++ b/library/core/src/pin.rs @@ -71,8 +71,8 @@ //! Feel free to [skip to where the theoretical discussion continues](#drop-guarantee). //! //! ```rust -//! use std::pin::Pin; //! use std::marker::PhantomPinned; +//! use std::pin::Pin; //! use std::ptr::NonNull; //! //! // This is a self-referential struct because the slice field points to the data field. @@ -187,7 +187,7 @@ //! fn drop(&mut self) { //! // `new_unchecked` is okay because we know this value is never used //! // again after being dropped. -//! inner_drop(unsafe { Pin::new_unchecked(self)}); +//! inner_drop(unsafe { Pin::new_unchecked(self) }); //! fn inner_drop(this: Pin<&mut Type>) { //! // Actual drop code goes here. //! } @@ -1003,12 +1003,12 @@ impl DispatchFromDyn> for Pin

where P: DispatchFromDyn {} /// }; /// /// fn generator_fn() -> impl Generator /* not Unpin */ { -/// // Allow generator to be self-referential (not `Unpin`) -/// // vvvvvv so that locals can cross yield points. +/// // Allow generator to be self-referential (not `Unpin`) +/// // vvvvvv so that locals can cross yield points. /// static || { /// let foo = String::from("foo"); /// let foo_ref = &foo; // ------+ -/// yield 0; // | <- crosses yield point! +/// yield 0; // | <- crosses yield point! /// println!("{foo_ref}"); // <--+ /// yield foo.len(); /// } @@ -1017,16 +1017,16 @@ impl DispatchFromDyn> for Pin

where P: DispatchFromDyn {} /// fn main() { /// let mut generator = pin!(generator_fn()); /// match generator.as_mut().resume(()) { -/// GeneratorState::Yielded(0) => {}, +/// GeneratorState::Yielded(0) => {} /// _ => unreachable!(), /// } /// match generator.as_mut().resume(()) { -/// GeneratorState::Yielded(3) => {}, +/// GeneratorState::Yielded(3) => {} /// _ => unreachable!(), /// } /// match generator.resume(()) { /// GeneratorState::Yielded(_) => unreachable!(), -/// GeneratorState::Complete(()) => {}, +/// GeneratorState::Complete(()) => {} /// } /// } /// ``` @@ -1089,11 +1089,16 @@ pub macro pin($value:expr $(,)?) { // review such a hypothetical macro (that any user-code could define): // // ```rust - // macro_rules! pin {( $value:expr ) => ( - // match &mut { $value } { at_value => unsafe { // Do not wrap `$value` in an `unsafe` block. - // $crate::pin::Pin::<&mut _>::new_unchecked(at_value) - // }} - // )} + // macro_rules! pin { + // ( $value:expr ) => { + // match &mut { $value } { + // at_value => unsafe { + // // Do not wrap `$value` in an `unsafe` block. + // $crate::pin::Pin::<&mut _>::new_unchecked(at_value) + // }, + // } + // }; + // } // ``` // // Safety: diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index 331714a993c60..ea7b739aefcb4 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -78,9 +78,7 @@ mod prim_bool {} /// ``` /// #![feature(never_type)] /// # fn foo() -> u32 { -/// let x: ! = { -/// return 123 -/// }; +/// let x: ! = { return 123 }; /// # } /// ``` /// @@ -215,11 +213,7 @@ mod prim_bool {} /// use std::ops::Add; /// /// fn foo() -> impl Add { -/// if true { -/// unimplemented!() -/// } else { -/// 0 -/// } +/// if true { unimplemented!() } else { 0 } /// } /// ``` /// @@ -266,11 +260,9 @@ mod prim_bool {} /// Since `!` has no values, it has no default value either. It's true that we could write an /// `impl` for this which simply panics, but the same is true for any type (we could `impl /// Default` for (eg.) [`File`] by just making [`default()`] panic.) -/// #[doc = concat!("[`File`]: ", include_str!("../primitive_docs/fs_file.md"))] /// [`Debug`]: fmt::Debug /// [`default()`]: Default::default -/// #[unstable(feature = "never_type", issue = "35121")] mod prim_never {} @@ -322,8 +314,8 @@ mod prim_never {} /// ``` /// let c: char = 'a'; /// match c { -/// '\0' ..= '\u{D7FF}' => false, -/// '\u{E000}' ..= '\u{10FFFF}' => true, +/// '\0'..='\u{D7FF}' => false, +/// '\u{E000}'..='\u{10FFFF}' => true, /// }; /// ``` /// @@ -354,7 +346,6 @@ mod prim_never {} /// // five elements times one byte per element /// assert_eq!(5, s.len() * std::mem::size_of::()); /// ``` -/// #[doc = concat!("[`String`]: ", include_str!("../primitive_docs/string_string.md"))] /// /// As always, remember that a human intuition for 'character' might not map to @@ -428,14 +419,11 @@ mod prim_char {} /// 1i64; /// } /// -/// let is_i64 = { -/// returns_i64() -/// }; +/// let is_i64 = { returns_i64() }; /// let is_unit = { /// returns_i64(); /// }; /// ``` -/// #[stable(feature = "rust1", since = "1.0.0")] mod prim_unit {} @@ -649,7 +637,7 @@ mod prim_pointer {} /// ``` /// let array: [i32; 3] = [0; 3]; /// -/// for x in &array { } +/// for x in &array {} /// ``` /// /// You can use `::try_from(slice)` or `slice.try_into()` to get an array from @@ -664,7 +652,8 @@ mod prim_pointer {} /// You can use a [slice pattern] to move elements out of an array: /// /// ``` -/// fn move_away(_: String) { /* Do interesting things. */ } +/// fn move_away(_: String) { /* Do interesting things. */ +/// } /// /// let [john, roa] = ["John".to_string(), "Roa".to_string()]; /// move_away(john); @@ -979,7 +968,6 @@ mod prim_str {} /// sequentially until the first non-equal set is found. /// /// For more about tuples, see [the book](../book/ch03-02-data-types.html#the-tuple-type). -/// // Hardcoded anchor in src/librustdoc/html/format.rs // linked to as `#trait-implementations-1` /// # Trait implementations @@ -1050,7 +1038,6 @@ mod prim_str {} /// assert_eq!(x, 4); /// assert_eq!(y, 5); /// ``` -/// #[stable(feature = "rust1", since = "1.0.0")] mod prim_tuple {} @@ -1486,7 +1473,7 @@ mod prim_ref {} /// You cast function pointers directly to integers: /// /// ```rust -/// let fnptr: fn(i32) -> i32 = |x| x+2; +/// let fnptr: fn(i32) -> i32 = |x| x + 2; /// let fnptr_addr = fnptr as usize; /// ``` /// diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 565c38d222a2c..a29d31f14b7e3 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -982,9 +982,7 @@ const unsafe fn swap_nonoverlapping_simple_untyped(x: *mut T, y: *mut T, coun /// /// // `mem::replace` would have the same effect without requiring the unsafe /// // block. -/// let b = unsafe { -/// ptr::replace(&mut rust[0], 'r') -/// }; +/// let b = unsafe { ptr::replace(&mut rust[0], 'r') }; /// /// assert_eq!(b, 'b'); /// assert_eq!(rust, &['r', 'u', 's', 't']); @@ -1186,10 +1184,7 @@ pub const unsafe fn read(src: *const T) -> T { /// unaligned: u32, /// } /// -/// let packed = Packed { -/// _padding: 0x00, -/// unaligned: 0x01020304, -/// }; +/// let packed = Packed { _padding: 0x00, unaligned: 0x01020304 }; /// /// // Take the address of a 32-bit integer which is not aligned. /// // In contrast to `&packed.unaligned as *const _`, this has no undefined behavior. @@ -2051,7 +2046,7 @@ pub macro addr_of($place:expr) { /// **Creating a pointer to uninitialized data:** /// /// ```rust -/// use std::{ptr, mem::MaybeUninit}; +/// use std::{mem::MaybeUninit, ptr}; /// /// struct Demo { /// field: bool, @@ -2061,7 +2056,9 @@ pub macro addr_of($place:expr) { /// // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`, /// // and thus be Undefined Behavior! /// let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) }; -/// unsafe { f1_ptr.write(true); } +/// unsafe { +/// f1_ptr.write(true); +/// } /// let init = unsafe { uninit.assume_init() }; /// ``` #[stable(feature = "raw_ref_macros", since = "1.51.0")] diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index c18264d13ebac..cdba4beb95d97 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -323,7 +323,9 @@ impl NonNull { /// let x_value = unsafe { *ptr.as_ptr() }; /// assert_eq!(x_value, 0); /// - /// unsafe { *ptr.as_ptr() += 2; } + /// unsafe { + /// *ptr.as_ptr() += 2; + /// } /// let x_value = unsafe { *ptr.as_ptr() }; /// assert_eq!(x_value, 2); /// ``` @@ -646,7 +648,7 @@ impl NonNull<[T]> { /// ```rust /// #![feature(allocator_api, ptr_as_uninit)] /// - /// use std::alloc::{Allocator, Layout, Global}; + /// use std::alloc::{Allocator, Global, Layout}; /// use std::mem::MaybeUninit; /// use std::ptr::NonNull; /// diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 3f33c5fd6ca36..03efa5925a50e 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -8,8 +8,8 @@ //! ``` //! # #[allow(dead_code)] //! enum Result { -//! Ok(T), -//! Err(E), +//! Ok(T), +//! Err(E), //! } //! ``` //! @@ -22,7 +22,10 @@ //! //! ``` //! #[derive(Debug)] -//! enum Version { Version1, Version2 } +//! enum Version { +//! Version1, +//! Version2, +//! } //! //! fn parse_version(header: &[u8]) -> Result { //! match header.get(0) { @@ -155,8 +158,8 @@ //! ``` //! # #![allow(dead_code)] //! use std::fs::File; -//! use std::io::prelude::*; //! use std::io; +//! use std::io::prelude::*; //! //! struct Info { //! name: String, @@ -167,17 +170,17 @@ //! fn write_info(info: &Info) -> io::Result<()> { //! // Early return on error //! let mut file = match File::create("my_best_friends.txt") { -//! Err(e) => return Err(e), -//! Ok(f) => f, +//! Err(e) => return Err(e), +//! Ok(f) => f, //! }; //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) { -//! return Err(e) +//! return Err(e); //! } //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) { -//! return Err(e) +//! return Err(e); //! } //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) { -//! return Err(e) +//! return Err(e); //! } //! Ok(()) //! } @@ -188,8 +191,8 @@ //! ``` //! # #![allow(dead_code)] //! use std::fs::File; -//! use std::io::prelude::*; //! use std::io; +//! use std::io::prelude::*; //! //! struct Info { //! name: String, @@ -295,7 +298,6 @@ //! mapping [`Ok(v)`] to [`Some(v)`] and [`Err(e)`] to [`None`] //! * [`transpose`] transposes a [`Result`] of an [`Option`] into an //! [`Option`] of a [`Result`] -//! // Do NOT add link reference definitions for `err` or `ok`, because they // will generate numerous incorrect URLs for `Err` and `Ok` elsewhere, due // to case folding. @@ -437,14 +439,14 @@ //! let mut results = vec![]; //! let mut errs = vec![]; //! let nums: Vec<_> = ["17", "not a number", "99", "-27", "768"] -//! .into_iter() -//! .map(u8::from_str) -//! // Save clones of the raw `Result` values to inspect -//! .inspect(|x| results.push(x.clone())) -//! // Challenge: explain how this captures only the `Err` values -//! .inspect(|x| errs.extend(x.clone().err())) -//! .flatten() -//! .collect(); +//! .into_iter() +//! .map(u8::from_str) +//! // Save clones of the raw `Result` values to inspect +//! .inspect(|x| results.push(x.clone())) +//! // Challenge: explain how this captures only the `Err` values +//! .inspect(|x| errs.extend(x.clone().err())) +//! .flatten() +//! .collect(); //! assert_eq!(errs.len(), 3); //! assert_eq!(nums, [17, 99]); //! println!("results {results:?}"); @@ -818,10 +820,10 @@ impl Result { /// ``` /// let k = 21; /// - /// let x : Result<_, &str> = Ok("foo"); + /// let x: Result<_, &str> = Ok("foo"); /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); /// - /// let x : Result<&str, _> = Err("bar"); + /// let x: Result<&str, _> = Err("bar"); /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); /// ``` #[inline] @@ -845,7 +847,9 @@ impl Result { /// Basic usage: /// /// ``` - /// fn stringify(x: u32) -> String { format!("error code: {x}") } + /// fn stringify(x: u32) -> String { + /// format!("error code: {x}") + /// } /// /// let x: Result = Ok(2); /// assert_eq!(x.map_err(stringify), Ok(2)); @@ -895,8 +899,7 @@ impl Result { /// use std::{fs, io}; /// /// fn read() -> io::Result { - /// fs::read_to_string("address.txt") - /// .inspect_err(|e| eprintln!("failed to read file: {e}")) + /// fs::read_to_string("address.txt").inspect_err(|e| eprintln!("failed to read file: {e}")) /// } /// ``` #[inline] @@ -944,12 +947,24 @@ impl Result { /// let mut s = "HELLO".to_string(); /// let mut x: Result = Ok("hello".to_string()); /// let y: Result<&mut str, &mut u32> = Ok(&mut s); - /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); + /// assert_eq!( + /// x.as_deref_mut().map(|x| { + /// x.make_ascii_uppercase(); + /// x + /// }), + /// y + /// ); /// /// let mut i = 42; /// let mut x: Result = Err(42); /// let y: Result<&mut str, &mut u32> = Err(&mut i); - /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); + /// assert_eq!( + /// x.as_deref_mut().map(|x| { + /// x.make_ascii_uppercase(); + /// x + /// }), + /// y + /// ); /// ``` #[stable(feature = "inner_deref", since = "1.47.0")] pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> @@ -996,7 +1011,7 @@ impl Result { /// let mut x: Result = Ok(7); /// match x.iter_mut().next() { /// Some(v) => *v = 40, - /// None => {}, + /// None => {} /// } /// assert_eq!(x, Ok(40)); /// @@ -1430,8 +1445,12 @@ impl Result { /// Basic usage: /// /// ``` - /// fn sq(x: u32) -> Result { Ok(x * x) } - /// fn err(x: u32) -> Result { Err(x) } + /// fn sq(x: u32) -> Result { + /// Ok(x * x) + /// } + /// fn err(x: u32) -> Result { + /// Err(x) + /// } /// /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); @@ -1491,7 +1510,9 @@ impl Result { /// Basic usage: /// /// ``` - /// fn count(x: &str) -> usize { x.len() } + /// fn count(x: &str) -> usize { + /// x.len() + /// } /// /// assert_eq!(Ok(2).unwrap_or_else(count), 2); /// assert_eq!(Err("foo").unwrap_or_else(count), 3); @@ -1523,7 +1544,9 @@ impl Result { /// /// ```no_run /// let x: Result = Err("emergency failure"); - /// unsafe { x.unwrap_unchecked(); } // Undefined behavior! + /// unsafe { + /// x.unwrap_unchecked(); + /// } // Undefined behavior! /// ``` #[inline] #[track_caller] @@ -2037,9 +2060,8 @@ impl> FromIterator> for Result { /// /// ``` /// let v = vec![1, 2]; - /// let res: Result, &'static str> = v.iter().map(|x: &u32| - /// x.checked_add(1).ok_or("Overflow!") - /// ).collect(); + /// let res: Result, &'static str> = + /// v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!")).collect(); /// assert_eq!(res, Ok(vec![2, 3])); /// ``` /// @@ -2048,9 +2070,8 @@ impl> FromIterator> for Result { /// /// ``` /// let v = vec![1, 2, 0]; - /// let res: Result, &'static str> = v.iter().map(|x: &u32| - /// x.checked_sub(1).ok_or("Underflow!") - /// ).collect(); + /// let res: Result, &'static str> = + /// v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!")).collect(); /// assert_eq!(res, Err("Underflow!")); /// ``` /// @@ -2060,10 +2081,13 @@ impl> FromIterator> for Result { /// ``` /// let v = vec![3, 2, 1, 10]; /// let mut shared = 0; - /// let res: Result, &'static str> = v.iter().map(|x: &u32| { - /// shared += x; - /// x.checked_sub(2).ok_or("Underflow!") - /// }).collect(); + /// let res: Result, &'static str> = v + /// .iter() + /// .map(|x: &u32| { + /// shared += x; + /// x.checked_sub(2).ok_or("Underflow!") + /// }) + /// .collect(); /// assert_eq!(res, Err("Underflow!")); /// assert_eq!(shared, 6); /// ``` diff --git a/library/core/src/slice/ascii.rs b/library/core/src/slice/ascii.rs index 5e5399acc1b0f..b7ca05aa1ee67 100644 --- a/library/core/src/slice/ascii.rs +++ b/library/core/src/slice/ascii.rs @@ -67,7 +67,6 @@ impl [u8] { /// # Examples /// /// ``` - /// /// let s = b"0\t\r\n'\"\\\x9d"; /// let escaped = s.escape_ascii().to_string(); /// assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d"); diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index 8a8962828e980..90686eaf14400 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -410,10 +410,10 @@ impl<'a, T: 'a, P: FnMut(&T) -> bool> Split<'a, T, P> { /// /// ``` /// #![feature(split_as_slice)] - /// let slice = [1,2,3,4,5]; + /// let slice = [1, 2, 3, 4, 5]; /// let mut split = slice.split(|v| v % 2 == 0); /// assert!(split.next().is_some()); - /// assert_eq!(split.as_slice(), &[3,4,5]); + /// assert_eq!(split.as_slice(), &[3, 4, 5]); /// ``` #[unstable(feature = "split_as_slice", issue = "96137")] pub fn as_slice(&self) -> &'a [T] { diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 4f1bb17344b29..af0226a82665e 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -1528,9 +1528,9 @@ impl [T] { /// let v = [1, 2, 3, 4, 5, 6]; /// /// { - /// let (left, right) = v.split_at(0); - /// assert_eq!(left, []); - /// assert_eq!(right, [1, 2, 3, 4, 5, 6]); + /// let (left, right) = v.split_at(0); + /// assert_eq!(left, []); + /// assert_eq!(right, [1, 2, 3, 4, 5, 6]); /// } /// /// { @@ -1615,9 +1615,9 @@ impl [T] { /// let v = [1, 2, 3, 4, 5, 6]; /// /// unsafe { - /// let (left, right) = v.split_at_unchecked(0); - /// assert_eq!(left, []); - /// assert_eq!(right, [1, 2, 3, 4, 5, 6]); + /// let (left, right) = v.split_at_unchecked(0); + /// assert_eq!(left, []); + /// assert_eq!(right, [1, 2, 3, 4, 5, 6]); /// } /// /// unsafe { @@ -1720,9 +1720,9 @@ impl [T] { /// let v = &[1, 2, 3, 4, 5, 6][..]; /// /// { - /// let (left, right) = v.split_array_ref::<0>(); - /// assert_eq!(left, &[]); - /// assert_eq!(right, [1, 2, 3, 4, 5, 6]); + /// let (left, right) = v.split_array_ref::<0>(); + /// assert_eq!(left, &[]); + /// assert_eq!(right, [1, 2, 3, 4, 5, 6]); /// } /// /// { @@ -1799,9 +1799,9 @@ impl [T] { /// let v = &[1, 2, 3, 4, 5, 6][..]; /// /// { - /// let (left, right) = v.rsplit_array_ref::<0>(); - /// assert_eq!(left, [1, 2, 3, 4, 5, 6]); - /// assert_eq!(right, &[]); + /// let (left, right) = v.rsplit_array_ref::<0>(); + /// assert_eq!(left, [1, 2, 3, 4, 5, 6]); + /// assert_eq!(right, &[]); /// } /// /// { @@ -1977,7 +1977,7 @@ impl [T] { /// let mut v = [10, 40, 30, 20, 60, 50]; /// /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) { - /// let terminator_idx = group.len()-1; + /// let terminator_idx = group.len() - 1; /// group[terminator_idx] = 1; /// } /// assert_eq!(v, [10, 40, 1, 20, 1, 1]); @@ -2043,7 +2043,6 @@ impl [T] { /// } /// assert_eq!(v, [3, 400, 300, 2, 600, 1]); /// ``` - /// #[stable(feature = "slice_rsplit", since = "1.27.0")] #[inline] pub fn rsplit_mut(&mut self, pred: F) -> RSplitMut<'_, T, F> @@ -2274,9 +2273,8 @@ impl [T] { /// assert_eq!(v.strip_prefix(&[50]), None); /// assert_eq!(v.strip_prefix(&[10, 50]), None); /// - /// let prefix : &str = "he"; - /// assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), - /// Some(b"llo".as_ref())); + /// let prefix: &str = "he"; + /// assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); /// ``` #[must_use = "returns the subslice without modifying the original"] #[stable(feature = "slice_strip", since = "1.51.0")] @@ -2357,11 +2355,14 @@ impl [T] { /// ``` /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; /// - /// assert_eq!(s.binary_search(&13), Ok(9)); - /// assert_eq!(s.binary_search(&4), Err(7)); + /// assert_eq!(s.binary_search(&13), Ok(9)); + /// assert_eq!(s.binary_search(&4), Err(7)); /// assert_eq!(s.binary_search(&100), Err(13)); /// let r = s.binary_search(&1); - /// assert!(match r { Ok(1..=4) => true, _ => false, }); + /// assert!(match r { + /// Ok(1..=4) => true, + /// _ => false, + /// }); /// ``` /// /// If you want to find that whole *range* of matching items, rather than @@ -2445,7 +2446,10 @@ impl [T] { /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13)); /// let seek = 1; /// let r = s.binary_search_by(|probe| probe.cmp(&seek)); - /// assert!(match r { Ok(1..=4) => true, _ => false, }); + /// assert!(match r { + /// Ok(1..=4) => true, + /// _ => false, + /// }); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] @@ -2521,15 +2525,30 @@ impl [T] { /// fourth could match any position in `[1, 4]`. /// /// ``` - /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1), - /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13), - /// (1, 21), (2, 34), (4, 55)]; - /// - /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9)); - /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7)); + /// let s = [ + /// (0, 0), + /// (2, 1), + /// (4, 1), + /// (5, 1), + /// (3, 1), + /// (1, 2), + /// (2, 3), + /// (4, 5), + /// (5, 8), + /// (3, 13), + /// (1, 21), + /// (2, 34), + /// (4, 55), + /// ]; + /// + /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9)); + /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7)); /// assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13)); /// let r = s.binary_search_by_key(&1, |&(a, b)| b); - /// assert!(match r { Ok(1..=4) => true, _ => false, }); + /// assert!(match r { + /// Ok(1..=4) => true, + /// _ => false, + /// }); /// ``` // Lint rustdoc::broken_intra_doc_links is allowed as `slice::sort_by_key` is // in crate `alloc`, and as such doesn't exists yet when building `core`: #74481. @@ -2707,10 +2726,12 @@ impl [T] { /// /// // We are only guaranteed the slice will be one of the following, based on the way we sort /// // about the specified index. - /// assert!(v == [-3, -5, 1, 2, 4] || - /// v == [-5, -3, 1, 2, 4] || - /// v == [-3, -5, 1, 4, 2] || - /// v == [-5, -3, 1, 4, 2]); + /// assert!( + /// v == [-3, -5, 1, 2, 4] + /// || v == [-5, -3, 1, 2, 4] + /// || v == [-3, -5, 1, 4, 2] + /// || v == [-5, -3, 1, 4, 2] + /// ); /// ``` #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")] #[inline] @@ -2755,10 +2776,12 @@ impl [T] { /// /// // We are only guaranteed the slice will be one of the following, based on the way we sort /// // about the specified index. - /// assert!(v == [2, 4, 1, -5, -3] || - /// v == [2, 4, 1, -3, -5] || - /// v == [4, 2, 1, -5, -3] || - /// v == [4, 2, 1, -3, -5]); + /// assert!( + /// v == [2, 4, 1, -5, -3] + /// || v == [2, 4, 1, -3, -5] + /// || v == [4, 2, 1, -5, -3] + /// || v == [4, 2, 1, -3, -5] + /// ); /// ``` #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")] #[inline] @@ -2807,10 +2830,12 @@ impl [T] { /// /// // We are only guaranteed the slice will be one of the following, based on the way we sort /// // about the specified index. - /// assert!(v == [1, 2, -3, 4, -5] || - /// v == [1, 2, -3, -5, 4] || - /// v == [2, 1, -3, 4, -5] || - /// v == [2, 1, -3, -5, 4]); + /// assert!( + /// v == [1, 2, -3, 4, -5] + /// || v == [1, 2, -3, -5, 4] + /// || v == [2, 1, -3, 4, -5] + /// || v == [2, 1, -3, -5, 4] + /// ); /// ``` #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")] #[inline] @@ -4101,10 +4126,7 @@ impl [[T; N]] { /// /// assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]); /// - /// assert_eq!( - /// [[1, 2, 3], [4, 5, 6]].flatten(), - /// [[1, 2], [3, 4], [5, 6]].flatten(), - /// ); + /// assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), [[1, 2], [3, 4], [5, 6]].flatten(),); /// /// let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []]; /// assert!(slice_of_empty_arrays.flatten().is_empty()); diff --git a/library/core/src/str/converts.rs b/library/core/src/str/converts.rs index b0c55ca4f5139..896e2a4b31af9 100644 --- a/library/core/src/str/converts.rs +++ b/library/core/src/str/converts.rs @@ -157,9 +157,7 @@ pub const fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> { /// // some bytes, in a vector /// let sparkle_heart = vec![240, 159, 146, 150]; /// -/// let sparkle_heart = unsafe { -/// str::from_utf8_unchecked(&sparkle_heart) -/// }; +/// let sparkle_heart = unsafe { str::from_utf8_unchecked(&sparkle_heart) }; /// /// assert_eq!("💖", sparkle_heart); /// ``` diff --git a/library/core/src/str/error.rs b/library/core/src/str/error.rs index a11b5add42ebf..ad630660c6e30 100644 --- a/library/core/src/str/error.rs +++ b/library/core/src/str/error.rs @@ -18,24 +18,25 @@ use crate::fmt; /// similar to `String::from_utf8_lossy` without allocating heap memory: /// /// ``` -/// fn from_utf8_lossy(mut input: &[u8], mut push: F) where F: FnMut(&str) { +/// fn from_utf8_lossy(mut input: &[u8], mut push: F) +/// where +/// F: FnMut(&str), +/// { /// loop { /// match std::str::from_utf8(input) { /// Ok(valid) => { /// push(valid); -/// break +/// break; /// } /// Err(error) => { /// let (valid, after_valid) = input.split_at(error.valid_up_to()); -/// unsafe { -/// push(std::str::from_utf8_unchecked(valid)) -/// } +/// unsafe { push(std::str::from_utf8_unchecked(valid)) } /// push("\u{FFFD}"); /// /// if let Some(invalid_sequence_length) = error.error_len() { /// input = &after_valid[invalid_sequence_length..] /// } else { -/// break +/// break; /// } /// } /// } diff --git a/library/core/src/str/lossy.rs b/library/core/src/str/lossy.rs index 59f873d1268ce..c6c5b6c3f145f 100644 --- a/library/core/src/str/lossy.rs +++ b/library/core/src/str/lossy.rs @@ -127,7 +127,10 @@ impl fmt::Debug for Debug<'_> { /// /// use std::str::Utf8Chunks; /// -/// fn from_utf8_lossy(input: &[u8], mut push: F) where F: FnMut(&str) { +/// fn from_utf8_lossy(input: &[u8], mut push: F) +/// where +/// F: FnMut(&str), +/// { /// for chunk in Utf8Chunks::new(input) { /// push(chunk.valid()); /// diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index fbc0fc397a5df..d0ed99f9ce91c 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -1348,8 +1348,8 @@ impl str { /// # Examples /// /// ``` - /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb." - /// .split_inclusive('\n').collect(); + /// let v: Vec<&str> = + /// "Mary had a little lamb\nlittle lamb\nlittle lamb.".split_inclusive('\n').collect(); /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]); /// ``` /// @@ -1358,8 +1358,8 @@ impl str { /// That substring will be the last item returned by the iterator. /// /// ``` - /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n" - /// .split_inclusive('\n').collect(); + /// let v: Vec<&str> = + /// "Mary had a little lamb\nlittle lamb\nlittle lamb.\n".split_inclusive('\n').collect(); /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]); /// ``` #[stable(feature = "split_inclusive", since = "1.51.0")] diff --git a/library/core/src/str/traits.rs b/library/core/src/str/traits.rs index d3ed811b1575b..78296473a76bf 100644 --- a/library/core/src/str/traits.rs +++ b/library/core/src/str/traits.rs @@ -148,9 +148,9 @@ unsafe impl const SliceIndex for ops::RangeFull { /// /// ``` /// let s = "Löwe 老虎 Léopard"; -/// assert_eq!(&s[0 .. 1], "L"); +/// assert_eq!(&s[0..1], "L"); /// -/// assert_eq!(&s[1 .. 9], "öwe 老"); +/// assert_eq!(&s[1..9], "öwe 老"); /// /// // these will panic: /// // byte 2 lies within `ö`: @@ -511,7 +511,7 @@ unsafe impl const SliceIndex for ops::RangeToInclusive { /// #[derive(Debug, PartialEq)] /// struct Point { /// x: i32, -/// y: i32 +/// y: i32, /// } /// /// #[derive(Debug, PartialEq, Eq)] diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index edc68d6fae51b..751c16d07d429 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -84,15 +84,15 @@ //! A simple spinlock: //! //! ``` -//! use std::sync::Arc; //! use std::sync::atomic::{AtomicUsize, Ordering}; +//! use std::sync::Arc; //! use std::{hint, thread}; //! //! fn main() { //! let spinlock = Arc::new(AtomicUsize::new(1)); //! //! let spinlock_clone = Arc::clone(&spinlock); -//! let thread = thread::spawn(move|| { +//! let thread = thread::spawn(move || { //! spinlock_clone.store(0, Ordering::SeqCst); //! }); //! @@ -597,17 +597,16 @@ impl AtomicBool { /// /// let some_bool = AtomicBool::new(true); /// - /// assert_eq!(some_bool.compare_exchange(true, - /// false, - /// Ordering::Acquire, - /// Ordering::Relaxed), - /// Ok(true)); + /// assert_eq!( + /// some_bool.compare_exchange(true, false, Ordering::Acquire, Ordering::Relaxed), + /// Ok(true) + /// ); /// assert_eq!(some_bool.load(Ordering::Relaxed), false); /// - /// assert_eq!(some_bool.compare_exchange(true, true, - /// Ordering::SeqCst, - /// Ordering::Acquire), - /// Err(false)); + /// assert_eq!( + /// some_bool.compare_exchange(true, true, Ordering::SeqCst, Ordering::Acquire), + /// Err(false) + /// ); /// assert_eq!(some_bool.load(Ordering::Relaxed), false); /// ``` #[inline] @@ -1083,8 +1082,7 @@ impl AtomicPtr { /// /// let view: &mut [*mut String] = AtomicPtr::get_mut_slice(&mut some_ptrs); /// assert_eq!(view, [null_mut::(); 10]); - /// view - /// .iter_mut() + /// view.iter_mut() /// .enumerate() /// .for_each(|(i, ptr)| *ptr = Box::into_raw(Box::new(format!("iteration#{i}")))); /// @@ -1337,8 +1335,7 @@ impl AtomicPtr { /// /// let other_ptr = &mut 10; /// - /// let value = some_ptr.compare_exchange(ptr, other_ptr, - /// Ordering::SeqCst, Ordering::Relaxed); + /// let value = some_ptr.compare_exchange(ptr, other_ptr, Ordering::SeqCst, Ordering::Relaxed); /// ``` #[inline] #[stable(feature = "extended_compare_and_swap", since = "1.10.0")] @@ -1449,11 +1446,7 @@ impl AtomicPtr { /// let new: *mut _ = &mut 10; /// assert_eq!(some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr)); /// let result = some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| { - /// if x == ptr { - /// Some(new) - /// } else { - /// None - /// } + /// if x == ptr { Some(new) } else { None } /// }); /// assert_eq!(result, Ok(ptr)); /// assert_eq!(some_ptr.load(Ordering::SeqCst), new); @@ -1553,10 +1546,7 @@ impl AtomicPtr { /// let array = [1i32, 2i32]; /// let atom = AtomicPtr::new(array.as_ptr().wrapping_add(1) as *mut _); /// - /// assert!(core::ptr::eq( - /// atom.fetch_ptr_sub(1, Ordering::Relaxed), - /// &array[1], - /// )); + /// assert!(core::ptr::eq(atom.fetch_ptr_sub(1, Ordering::Relaxed), &array[1],)); /// assert!(core::ptr::eq(atom.load(Ordering::Relaxed), &array[0])); /// ``` #[inline] @@ -1726,8 +1716,7 @@ impl AtomicPtr { /// let atom = AtomicPtr::::new(pointer.map_addr(|a| a | 1)); /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 1); /// // Untag, and extract the previously tagged pointer. - /// let untagged = atom.fetch_and(!1, Ordering::Relaxed) - /// .map_addr(|a| a & !1); + /// let untagged = atom.fetch_and(!1, Ordering::Relaxed).map_addr(|a| a & !1); /// assert_eq!(untagged, pointer); /// ``` #[inline] @@ -3287,8 +3276,8 @@ unsafe fn atomic_umin(dst: *mut T, val: T, order: Ordering) -> T { /// # Examples /// /// ``` -/// use std::sync::atomic::AtomicBool; /// use std::sync::atomic::fence; +/// use std::sync::atomic::AtomicBool; /// use std::sync::atomic::Ordering; /// /// // A mutual exclusion primitive based on spinlock. @@ -3298,9 +3287,7 @@ unsafe fn atomic_umin(dst: *mut T, val: T, order: Ordering) -> T { /// /// impl Mutex { /// pub fn new() -> Mutex { -/// Mutex { -/// flag: AtomicBool::new(false), -/// } +/// Mutex { flag: AtomicBool::new(false) } /// } /// /// pub fn lock(&self) { @@ -3380,9 +3367,9 @@ pub fn fence(order: Ordering) { /// Using a `compiler_fence` remedies this situation. /// /// ``` -/// use std::sync::atomic::{AtomicBool, AtomicUsize}; -/// use std::sync::atomic::Ordering; /// use std::sync::atomic::compiler_fence; +/// use std::sync::atomic::Ordering; +/// use std::sync::atomic::{AtomicBool, AtomicUsize}; /// /// static IMPORTANT_VARIABLE: AtomicUsize = AtomicUsize::new(0); /// static IS_READY: AtomicBool = AtomicBool::new(false); diff --git a/library/core/src/sync/exclusive.rs b/library/core/src/sync/exclusive.rs index c65c275000ce8..5ca07def76e70 100644 --- a/library/core/src/sync/exclusive.rs +++ b/library/core/src/sync/exclusive.rs @@ -50,7 +50,7 @@ use core::task::{Context, Poll}; /// async fn other() {} /// fn assert_sync(t: T) {} /// struct State { -/// future: Exclusive +/// future: Exclusive, /// } /// /// assert_sync(State { @@ -59,7 +59,7 @@ use core::task::{Context, Poll}; /// let cell_ref = &cell; /// other().await; /// let value = cell_ref.get(); -/// }) +/// }), /// }); /// ``` /// diff --git a/library/core/src/task/poll.rs b/library/core/src/task/poll.rs index 41f0a25dbc3e0..9fb86c86e5059 100644 --- a/library/core/src/task/poll.rs +++ b/library/core/src/task/poll.rs @@ -105,9 +105,9 @@ impl Poll { /// ```rust /// #![feature(poll_ready)] /// - /// use std::task::{Context, Poll}; /// use std::future::{self, Future}; /// use std::pin::Pin; + /// use std::task::{Context, Poll}; /// /// pub fn do_poll(cx: &mut Context<'_>) -> Poll<()> { /// let mut fut = future::ready(42); diff --git a/library/core/src/task/ready.rs b/library/core/src/task/ready.rs index b1daf545fbe7b..e62ce5fe8ec20 100644 --- a/library/core/src/task/ready.rs +++ b/library/core/src/task/ready.rs @@ -13,9 +13,9 @@ use core::task::Poll; /// # Examples /// /// ``` -/// use std::task::{ready, Context, Poll}; /// use std::future::{self, Future}; /// use std::pin::Pin; +/// use std::task::{ready, Context, Poll}; /// /// pub fn do_poll(cx: &mut Context<'_>) -> Poll<()> { /// let mut fut = future::ready(42); diff --git a/library/core/src/unit.rs b/library/core/src/unit.rs index 6656dd5c40beb..d67e4e425a89f 100644 --- a/library/core/src/unit.rs +++ b/library/core/src/unit.rs @@ -8,9 +8,7 @@ use crate::iter::FromIterator; /// ``` /// use std::io::*; /// let data = vec![1, 2, 3, 4, 5]; -/// let res: Result<()> = data.iter() -/// .map(|x| writeln!(stdout(), "{x}")) -/// .collect(); +/// let res: Result<()> = data.iter().map(|x| writeln!(stdout(), "{x}")).collect(); /// assert!(res.is_ok()); /// ``` #[stable(feature = "unit_from_iter", since = "1.23.0")] diff --git a/library/std/src/alloc.rs b/library/std/src/alloc.rs index 61c1ff578b2ca..7859ab585316e 100644 --- a/library/std/src/alloc.rs +++ b/library/std/src/alloc.rs @@ -14,7 +14,7 @@ //! to route all default allocation requests to a custom object. //! //! ```rust -//! use std::alloc::{GlobalAlloc, System, Layout}; +//! use std::alloc::{GlobalAlloc, Layout, System}; //! //! struct MyAllocator; //! @@ -92,7 +92,7 @@ pub use alloc_crate::alloc::*; /// keeping track of the number of all bytes allocated: /// /// ```rust -/// use std::alloc::{System, GlobalAlloc, Layout}; +/// use std::alloc::{GlobalAlloc, Layout, System}; /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; /// /// struct Counter; @@ -305,10 +305,10 @@ static HOOK: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut()); /// ``` /// #![feature(alloc_error_hook)] /// -/// use std::alloc::{Layout, set_alloc_error_hook}; +/// use std::alloc::{set_alloc_error_hook, Layout}; /// /// fn custom_alloc_error_hook(layout: Layout) { -/// panic!("memory allocation of {} bytes failed", layout.size()); +/// panic!("memory allocation of {} bytes failed", layout.size()); /// } /// /// set_alloc_error_hook(custom_alloc_error_hook); diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index 708edc5de4751..38258447cda0b 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -79,29 +79,18 @@ use crate::sys; /// let mut book_reviews = HashMap::new(); /// /// // Review some books. -/// book_reviews.insert( -/// "Adventures of Huckleberry Finn".to_string(), -/// "My favorite book.".to_string(), -/// ); -/// book_reviews.insert( -/// "Grimms' Fairy Tales".to_string(), -/// "Masterpiece.".to_string(), -/// ); -/// book_reviews.insert( -/// "Pride and Prejudice".to_string(), -/// "Very enjoyable.".to_string(), -/// ); -/// book_reviews.insert( -/// "The Adventures of Sherlock Holmes".to_string(), -/// "Eye lyked it alot.".to_string(), -/// ); +/// book_reviews +/// .insert("Adventures of Huckleberry Finn".to_string(), "My favorite book.".to_string()); +/// book_reviews.insert("Grimms' Fairy Tales".to_string(), "Masterpiece.".to_string()); +/// book_reviews.insert("Pride and Prejudice".to_string(), "Very enjoyable.".to_string()); +/// book_reviews +/// .insert("The Adventures of Sherlock Holmes".to_string(), "Eye lyked it alot.".to_string()); /// /// // Check for a specific one. /// // When collections store owned values (String), they can still be /// // queried using references (&str). /// if !book_reviews.contains_key("Les Misérables") { -/// println!("We've got {} reviews, but Les Misérables ain't one.", -/// book_reviews.len()); +/// println!("We've got {} reviews, but Les Misérables ain't one.", book_reviews.len()); /// } /// /// // oops, this review has a lot of spelling mistakes, let's delete it. @@ -112,7 +101,7 @@ use crate::sys; /// for &book in &to_find { /// match book_reviews.get(book) { /// Some(review) => println!("{book}: {review}"), -/// None => println!("{book} is unreviewed.") +/// None => println!("{book} is unreviewed."), /// } /// } /// @@ -130,12 +119,8 @@ use crate::sys; /// ``` /// use std::collections::HashMap; /// -/// let solar_distance = HashMap::from([ -/// ("Mercury", 0.4), -/// ("Venus", 0.7), -/// ("Earth", 1.0), -/// ("Mars", 1.5), -/// ]); +/// let solar_distance = +/// HashMap::from([("Mercury", 0.4), ("Venus", 0.7), ("Earth", 1.0), ("Mars", 1.5)]); /// ``` /// /// `HashMap` implements an [`Entry` API](#method.entry), which allows @@ -271,8 +256,8 @@ impl HashMap { /// # Examples /// /// ``` - /// use std::collections::HashMap; /// use std::collections::hash_map::RandomState; + /// use std::collections::HashMap; /// /// let s = RandomState::new(); /// let mut map = HashMap::with_hasher(s); @@ -303,8 +288,8 @@ impl HashMap { /// # Examples /// /// ``` - /// use std::collections::HashMap; /// use std::collections::hash_map::RandomState; + /// use std::collections::HashMap; /// /// let s = RandomState::new(); /// let mut map = HashMap::with_capacity_and_hasher(10, s); @@ -342,11 +327,7 @@ impl HashMap { /// ``` /// use std::collections::HashMap; /// - /// let map = HashMap::from([ - /// ("a", 1), - /// ("b", 2), - /// ("c", 3), - /// ]); + /// let map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]); /// /// for key in map.keys() { /// println!("{key}"); @@ -371,11 +352,7 @@ impl HashMap { /// ``` /// use std::collections::HashMap; /// - /// let map = HashMap::from([ - /// ("a", 1), - /// ("b", 2), - /// ("c", 3), - /// ]); + /// let map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]); /// /// let mut vec: Vec<&str> = map.into_keys().collect(); /// // The `IntoKeys` iterator produces keys in arbitrary order, so the @@ -403,11 +380,7 @@ impl HashMap { /// ``` /// use std::collections::HashMap; /// - /// let map = HashMap::from([ - /// ("a", 1), - /// ("b", 2), - /// ("c", 3), - /// ]); + /// let map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]); /// /// for val in map.values() { /// println!("{val}"); @@ -431,11 +404,7 @@ impl HashMap { /// ``` /// use std::collections::HashMap; /// - /// let mut map = HashMap::from([ - /// ("a", 1), - /// ("b", 2), - /// ("c", 3), - /// ]); + /// let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]); /// /// for val in map.values_mut() { /// *val = *val + 10; @@ -464,11 +433,7 @@ impl HashMap { /// ``` /// use std::collections::HashMap; /// - /// let map = HashMap::from([ - /// ("a", 1), - /// ("b", 2), - /// ("c", 3), - /// ]); + /// let map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]); /// /// let mut vec: Vec = map.into_values().collect(); /// // The `IntoValues` iterator produces values in arbitrary order, so @@ -496,11 +461,7 @@ impl HashMap { /// ``` /// use std::collections::HashMap; /// - /// let map = HashMap::from([ - /// ("a", 1), - /// ("b", 2), - /// ("c", 3), - /// ]); + /// let map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]); /// /// for (key, val) in map.iter() { /// println!("key: {key} val: {val}"); @@ -526,11 +487,7 @@ impl HashMap { /// ``` /// use std::collections::HashMap; /// - /// let mut map = HashMap::from([ - /// ("a", 1), - /// ("b", 2), - /// ("c", 3), - /// ]); + /// let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]); /// /// // Update all values /// for (_, val) in map.iter_mut() { @@ -672,7 +629,7 @@ impl HashMap { /// ``` /// use std::collections::HashMap; /// - /// let mut map: HashMap = (0..8).map(|x| (x, x*10)).collect(); + /// let mut map: HashMap = (0..8).map(|x| (x, x * 10)).collect(); /// map.retain(|&k, _| k % 2 == 0); /// assert_eq!(map.len(), 4); /// ``` @@ -715,8 +672,8 @@ impl HashMap { /// # Examples /// /// ``` - /// use std::collections::HashMap; /// use std::collections::hash_map::RandomState; + /// use std::collections::HashMap; /// /// let hasher = RandomState::new(); /// let map: HashMap = HashMap::with_hasher(hasher); @@ -925,30 +882,15 @@ where /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); /// libraries.insert("Library of Congress".to_string(), 1800); /// - /// let got = libraries.get_many_mut([ - /// "Athenæum", - /// "Library of Congress", - /// ]); - /// assert_eq!( - /// got, - /// Some([ - /// &mut 1807, - /// &mut 1800, - /// ]), - /// ); + /// let got = libraries.get_many_mut(["Athenæum", "Library of Congress"]); + /// assert_eq!(got, Some([&mut 1807, &mut 1800,]),); /// /// // Missing keys result in None - /// let got = libraries.get_many_mut([ - /// "Athenæum", - /// "New York Public Library", - /// ]); + /// let got = libraries.get_many_mut(["Athenæum", "New York Public Library"]); /// assert_eq!(got, None); /// /// // Duplicate keys result in None - /// let got = libraries.get_many_mut([ - /// "Athenæum", - /// "Athenæum", - /// ]); + /// let got = libraries.get_many_mut(["Athenæum", "Athenæum"]); /// assert_eq!(got, None); /// ``` #[inline] @@ -988,23 +930,11 @@ where /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); /// libraries.insert("Library of Congress".to_string(), 1800); /// - /// let got = libraries.get_many_mut([ - /// "Athenæum", - /// "Library of Congress", - /// ]); - /// assert_eq!( - /// got, - /// Some([ - /// &mut 1807, - /// &mut 1800, - /// ]), - /// ); + /// let got = libraries.get_many_mut(["Athenæum", "Library of Congress"]); + /// assert_eq!(got, Some([&mut 1807, &mut 1800,]),); /// /// // Missing keys result in None - /// let got = libraries.get_many_mut([ - /// "Athenæum", - /// "New York Public Library", - /// ]); + /// let got = libraries.get_many_mut(["Athenæum", "New York Public Library"]); /// assert_eq!(got, None); /// ``` #[inline] @@ -1384,9 +1314,7 @@ where /// ``` /// use std::collections::HashMap; /// -/// let map = HashMap::from([ -/// ("a", 1), -/// ]); +/// let map = HashMap::from([("a", 1)]); /// let iter = map.iter(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -1422,9 +1350,7 @@ impl fmt::Debug for Iter<'_, K, V> { /// ``` /// use std::collections::HashMap; /// -/// let mut map = HashMap::from([ -/// ("a", 1), -/// ]); +/// let mut map = HashMap::from([("a", 1)]); /// let iter = map.iter_mut(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -1453,9 +1379,7 @@ impl<'a, K, V> IterMut<'a, K, V> { /// ``` /// use std::collections::HashMap; /// -/// let map = HashMap::from([ -/// ("a", 1), -/// ]); +/// let map = HashMap::from([("a", 1)]); /// let iter = map.into_iter(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -1483,9 +1407,7 @@ impl IntoIter { /// ``` /// use std::collections::HashMap; /// -/// let map = HashMap::from([ -/// ("a", 1), -/// ]); +/// let map = HashMap::from([("a", 1)]); /// let iter_keys = map.keys(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -1521,9 +1443,7 @@ impl fmt::Debug for Keys<'_, K, V> { /// ``` /// use std::collections::HashMap; /// -/// let map = HashMap::from([ -/// ("a", 1), -/// ]); +/// let map = HashMap::from([("a", 1)]); /// let iter_values = map.values(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -1559,9 +1479,7 @@ impl fmt::Debug for Values<'_, K, V> { /// ``` /// use std::collections::HashMap; /// -/// let mut map = HashMap::from([ -/// ("a", 1), -/// ]); +/// let mut map = HashMap::from([("a", 1)]); /// let iter = map.drain(); /// ``` #[stable(feature = "drain", since = "1.6.0")] @@ -1590,9 +1508,7 @@ impl<'a, K, V> Drain<'a, K, V> { /// /// use std::collections::HashMap; /// -/// let mut map = HashMap::from([ -/// ("a", 1), -/// ]); +/// let mut map = HashMap::from([("a", 1)]); /// let iter = map.drain_filter(|_k, v| *v % 2 == 0); /// ``` #[unstable(feature = "hash_drain_filter", issue = "59618")] @@ -1615,9 +1531,7 @@ where /// ``` /// use std::collections::HashMap; /// -/// let mut map = HashMap::from([ -/// ("a", 1), -/// ]); +/// let mut map = HashMap::from([("a", 1)]); /// let iter_values = map.values_mut(); /// ``` #[stable(feature = "map_values_mut", since = "1.10.0")] @@ -1637,9 +1551,7 @@ pub struct ValuesMut<'a, K: 'a, V: 'a> { /// ``` /// use std::collections::HashMap; /// -/// let map = HashMap::from([ -/// ("a", 1), -/// ]); +/// let map = HashMap::from([("a", 1)]); /// let iter_keys = map.into_keys(); /// ``` #[stable(feature = "map_into_keys_values", since = "1.54.0")] @@ -1659,9 +1571,7 @@ pub struct IntoKeys { /// ``` /// use std::collections::HashMap; /// -/// let map = HashMap::from([ -/// ("a", 1), -/// ]); +/// let map = HashMap::from([("a", 1)]); /// let iter_keys = map.into_values(); /// ``` #[stable(feature = "map_into_keys_values", since = "1.54.0")] @@ -1831,9 +1741,7 @@ impl<'a, K, V, S> RawEntryMut<'a, K, V, S> { /// /// let mut map: HashMap<&str, String> = HashMap::new(); /// - /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| { - /// ("poneyland", "hoho".to_string()) - /// }); + /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| ("poneyland", "hoho".to_string())); /// /// assert_eq!(map["poneyland"], "hoho".to_string()); /// ``` @@ -1866,15 +1774,12 @@ impl<'a, K, V, S> RawEntryMut<'a, K, V, S> { /// let mut map: HashMap<&str, u32> = HashMap::new(); /// /// map.raw_entry_mut() - /// .from_key("poneyland") - /// .and_modify(|_k, v| { *v += 1 }) - /// .or_insert("poneyland", 42); + /// .from_key("poneyland") + /// .and_modify(|_k, v| *v += 1) + /// .or_insert("poneyland", 42); /// assert_eq!(map["poneyland"], 42); /// - /// map.raw_entry_mut() - /// .from_key("poneyland") - /// .and_modify(|_k, v| { *v += 1 }) - /// .or_insert("poneyland", 0); + /// map.raw_entry_mut().from_key("poneyland").and_modify(|_k, v| *v += 1).or_insert("poneyland", 0); /// assert_eq!(map["poneyland"], 43); /// ``` #[inline] @@ -2206,11 +2111,7 @@ impl IntoIterator for HashMap { /// ``` /// use std::collections::HashMap; /// - /// let map = HashMap::from([ - /// ("a", 1), - /// ("b", 2), - /// ("c", 3), - /// ]); + /// let map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]); /// /// // Not possible with .iter() /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); @@ -2619,14 +2520,10 @@ impl<'a, K, V> Entry<'a, K, V> { /// /// let mut map: HashMap<&str, u32> = HashMap::new(); /// - /// map.entry("poneyland") - /// .and_modify(|e| { *e += 1 }) - /// .or_insert(42); + /// map.entry("poneyland").and_modify(|e| *e += 1).or_insert(42); /// assert_eq!(map["poneyland"], 42); /// - /// map.entry("poneyland") - /// .and_modify(|e| { *e += 1 }) - /// .or_insert(42); + /// map.entry("poneyland").and_modify(|e| *e += 1).or_insert(42); /// assert_eq!(map["poneyland"], 43); /// ``` #[inline] @@ -2719,8 +2616,8 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// # Examples /// /// ``` - /// use std::collections::HashMap; /// use std::collections::hash_map::Entry; + /// use std::collections::HashMap; /// /// let mut map: HashMap<&str, u32> = HashMap::new(); /// map.entry("poneyland").or_insert(12); @@ -2743,8 +2640,8 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// # Examples /// /// ``` - /// use std::collections::HashMap; /// use std::collections::hash_map::Entry; + /// use std::collections::HashMap; /// /// let mut map: HashMap<&str, u32> = HashMap::new(); /// map.entry("poneyland").or_insert(12); @@ -2769,8 +2666,8 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// # Examples /// /// ``` - /// use std::collections::HashMap; /// use std::collections::hash_map::Entry; + /// use std::collections::HashMap; /// /// let mut map: HashMap<&str, u32> = HashMap::new(); /// map.entry("poneyland").or_insert(12); @@ -2802,8 +2699,8 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// # Examples /// /// ``` - /// use std::collections::HashMap; /// use std::collections::hash_map::Entry; + /// use std::collections::HashMap; /// /// let mut map: HashMap<&str, u32> = HashMap::new(); /// map.entry("poneyland").or_insert(12); @@ -2826,8 +2723,8 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// # Examples /// /// ``` - /// use std::collections::HashMap; /// use std::collections::hash_map::Entry; + /// use std::collections::HashMap; /// /// let mut map: HashMap<&str, u32> = HashMap::new(); /// map.entry("poneyland").or_insert(12); @@ -2849,8 +2746,8 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// # Examples /// /// ``` - /// use std::collections::HashMap; /// use std::collections::hash_map::Entry; + /// use std::collections::HashMap; /// /// let mut map: HashMap<&str, u32> = HashMap::new(); /// map.entry("poneyland").or_insert(12); @@ -2886,7 +2783,6 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// // Also replace the key with a handle to our other key. /// let (old_key, old_value): (Rc, u32) = entry.replace_entry(16); /// } - /// /// ``` #[inline] #[unstable(feature = "map_entry_replace", issue = "44286")] @@ -2910,7 +2806,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// /// reclaim_memory(&mut map, &known_strings); /// - /// fn reclaim_memory(map: &mut HashMap, u32>, known_strings: &[Rc] ) { + /// fn reclaim_memory(map: &mut HashMap, u32>, known_strings: &[Rc]) { /// for s in known_strings { /// if let Entry::Occupied(entry) = map.entry(Rc::clone(s)) { /// // Replaces the entry's key with our version of it in `known_strings`. @@ -2949,8 +2845,8 @@ impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { /// # Examples /// /// ``` - /// use std::collections::HashMap; /// use std::collections::hash_map::Entry; + /// use std::collections::HashMap; /// /// let mut map: HashMap<&str, u32> = HashMap::new(); /// @@ -2970,8 +2866,8 @@ impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { /// # Examples /// /// ``` - /// use std::collections::HashMap; /// use std::collections::hash_map::Entry; + /// use std::collections::HashMap; /// /// let mut map: HashMap<&str, u32> = HashMap::new(); /// @@ -2993,8 +2889,8 @@ impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { /// /// ``` /// #![feature(entry_insert)] - /// use std::collections::HashMap; /// use std::collections::hash_map::Entry; + /// use std::collections::HashMap; /// /// let mut map: HashMap<&str, u32> = HashMap::new(); /// @@ -3080,8 +2976,8 @@ where /// # Examples /// /// ``` -/// use std::collections::HashMap; /// use std::collections::hash_map::RandomState; +/// use std::collections::HashMap; /// /// let s = RandomState::new(); /// let mut map = HashMap::with_hasher(s); diff --git a/library/std/src/collections/hash/set.rs b/library/std/src/collections/hash/set.rs index cee884145c711..167e3bcb30a69 100644 --- a/library/std/src/collections/hash/set.rs +++ b/library/std/src/collections/hash/set.rs @@ -58,8 +58,7 @@ use super::map::{map_try_reserve_error, RandomState}; /// /// // Check for a specific one. /// if !books.contains("The Winds of Winter") { -/// println!("We have {} books, but The Winds of Winter ain't one.", -/// books.len()); +/// println!("We have {} books, but The Winds of Winter ain't one.", books.len()); /// } /// /// // Remove a book. @@ -367,8 +366,8 @@ impl HashSet { /// # Examples /// /// ``` - /// use std::collections::HashSet; /// use std::collections::hash_map::RandomState; + /// use std::collections::HashSet; /// /// let s = RandomState::new(); /// let mut set = HashSet::with_hasher(s); @@ -399,8 +398,8 @@ impl HashSet { /// # Examples /// /// ``` - /// use std::collections::HashSet; /// use std::collections::hash_map::RandomState; + /// use std::collections::HashSet; /// /// let s = RandomState::new(); /// let mut set = HashSet::with_capacity_and_hasher(10, s); @@ -417,8 +416,8 @@ impl HashSet { /// # Examples /// /// ``` - /// use std::collections::HashSet; /// use std::collections::hash_map::RandomState; + /// use std::collections::HashSet; /// /// let hasher = RandomState::new(); /// let set: HashSet = HashSet::with_hasher(hasher); @@ -741,8 +740,8 @@ where /// /// use std::collections::HashSet; /// - /// let mut set: HashSet = ["cat", "dog", "horse"] - /// .iter().map(|&pet| pet.to_owned()).collect(); + /// let mut set: HashSet = + /// ["cat", "dog", "horse"].iter().map(|&pet| pet.to_owned()).collect(); /// /// assert_eq!(set.len(), 3); /// for &pet in &["cat", "dog", "fish"] { @@ -773,8 +772,8 @@ where /// /// use std::collections::HashSet; /// - /// let mut set: HashSet = ["cat", "dog", "horse"] - /// .iter().map(|&pet| pet.to_owned()).collect(); + /// let mut set: HashSet = + /// ["cat", "dog", "horse"].iter().map(|&pet| pet.to_owned()).collect(); /// /// assert_eq!(set.len(), 3); /// for &pet in &["cat", "dog", "fish"] { diff --git a/library/std/src/collections/mod.rs b/library/std/src/collections/mod.rs index ae2baba09e683..645747b0c16ea 100644 --- a/library/std/src/collections/mod.rs +++ b/library/std/src/collections/mod.rs @@ -199,7 +199,7 @@ //! ``` //! let vec = vec![1, 2, 3, 4]; //! for x in vec.iter() { -//! println!("vec contained {x:?}"); +//! println!("vec contained {x:?}"); //! } //! ``` //! @@ -209,7 +209,7 @@ //! ``` //! let mut vec = vec![1, 2, 3, 4]; //! for x in vec.iter_mut() { -//! *x += 1; +//! *x += 1; //! } //! ``` //! @@ -246,7 +246,7 @@ //! ``` //! let vec = vec![1, 2, 3, 4]; //! for x in vec.iter().rev() { -//! println!("vec contained {x:?}"); +//! println!("vec contained {x:?}"); //! } //! ``` //! @@ -320,7 +320,9 @@ //! use std::collections::btree_map::BTreeMap; //! //! // A client of the bar. They have a blood alcohol level. -//! struct Person { blood_alcohol: f32 } +//! struct Person { +//! blood_alcohol: f32, +//! } //! //! // All the orders made to the bar, by client ID. //! let orders = vec![1, 2, 1, 2, 3, 4, 1, 2, 2, 3, 4, 1, 1, 1]; @@ -365,22 +367,30 @@ //! //! // we will compare `Foo`s by their `a` value only. //! impl PartialEq for Foo { -//! fn eq(&self, other: &Self) -> bool { self.a == other.a } +//! fn eq(&self, other: &Self) -> bool { +//! self.a == other.a +//! } //! } //! //! impl Eq for Foo {} //! //! // we will hash `Foo`s by their `a` value only. //! impl Hash for Foo { -//! fn hash(&self, h: &mut H) { self.a.hash(h); } +//! fn hash(&self, h: &mut H) { +//! self.a.hash(h); +//! } //! } //! //! impl PartialOrd for Foo { -//! fn partial_cmp(&self, other: &Self) -> Option { self.a.partial_cmp(&other.a) } +//! fn partial_cmp(&self, other: &Self) -> Option { +//! self.a.partial_cmp(&other.a) +//! } //! } //! //! impl Ord for Foo { -//! fn cmp(&self, other: &Self) -> Ordering { self.a.cmp(&other.a) } +//! fn cmp(&self, other: &Self) -> Ordering { +//! self.a.cmp(&other.a) +//! } //! } //! //! let mut map = BTreeMap::new(); diff --git a/library/std/src/env.rs b/library/std/src/env.rs index 6eb7cbea6269d..cd6cee5dc6930 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -260,7 +260,7 @@ fn _var(key: &OsStr) -> Result { /// let key = "HOME"; /// match env::var_os(key) { /// Some(val) => println!("{key}: {val:?}"), -/// None => println!("{key} is not defined in the environment.") +/// None => println!("{key} is not defined in the environment."), /// } /// ``` #[must_use] @@ -428,7 +428,7 @@ pub struct SplitPaths<'a> { /// println!("'{}'", path.display()); /// } /// } -/// None => println!("{key} is not defined in the environment.") +/// None => println!("{key} is not defined in the environment."), /// } /// ``` #[stable(feature = "env", since = "1.0.0")] @@ -676,8 +676,7 @@ pub fn temp_dir() -> PathBuf { /// use std::env; /// /// match env::current_exe() { -/// Ok(exe_path) => println!("Path of this executable is: {}", -/// exe_path.display()), +/// Ok(exe_path) => println!("Path of this executable is: {}", exe_path.display()), /// Err(e) => println!("failed to get current exe path: {e}"), /// }; /// ``` diff --git a/library/std/src/error.rs b/library/std/src/error.rs index 05f8fd8de327f..b22260f9fb2db 100644 --- a/library/std/src/error.rs +++ b/library/std/src/error.rs @@ -210,9 +210,7 @@ mod private { /// # } /// /// fn main() -> Result<(), Report> { -/// get_super_error() -/// .map_err(Report::from) -/// .map_err(|r| r.pretty(true).show_backtrace(true))?; +/// get_super_error().map_err(Report::from).map_err(|r| r.pretty(true).show_backtrace(true))?; /// Ok(()) /// } /// ``` @@ -375,8 +373,8 @@ impl Report { /// # use std::error::Error; /// # use std::fmt; /// use std::any::Demand; - /// use std::error::Report; /// use std::backtrace::Backtrace; + /// use std::error::Report; /// /// # #[derive(Debug)] /// # struct SuperError { diff --git a/library/std/src/ffi/os_str.rs b/library/std/src/ffi/os_str.rs index 80ed34157e6dc..657be9c177ea5 100644 --- a/library/std/src/ffi/os_str.rs +++ b/library/std/src/ffi/os_str.rs @@ -147,7 +147,7 @@ impl OsString { /// # Examples /// /// ``` - /// use std::ffi::{OsString, OsStr}; + /// use std::ffi::{OsStr, OsString}; /// /// let os_string = OsString::from("foo"); /// let os_str = OsStr::new("foo"); @@ -303,8 +303,8 @@ impl OsString { /// # Examples /// /// ``` - /// use std::ffi::{OsStr, OsString}; /// use std::collections::TryReserveError; + /// use std::ffi::{OsStr, OsString}; /// /// fn process_data(data: &str) -> Result { /// let mut s = OsString::new(); @@ -374,8 +374,8 @@ impl OsString { /// # Examples /// /// ``` - /// use std::ffi::{OsStr, OsString}; /// use std::collections::TryReserveError; + /// use std::ffi::{OsStr, OsString}; /// /// fn process_data(data: &str) -> Result { /// let mut s = OsString::new(); @@ -454,7 +454,7 @@ impl OsString { /// # Examples /// /// ``` - /// use std::ffi::{OsString, OsStr}; + /// use std::ffi::{OsStr, OsString}; /// /// let s = OsString::from("hello"); /// @@ -723,7 +723,8 @@ impl OsStr { /// // sequences simply through collecting user command line arguments, for /// // example. /// - /// #[cfg(unix)] { + /// #[cfg(unix)] + /// { /// use std::ffi::OsStr; /// use std::os::unix::ffi::OsStrExt; /// @@ -735,7 +736,8 @@ impl OsStr { /// /// assert_eq!(os_str.to_string_lossy(), "fo�o"); /// } - /// #[cfg(windows)] { + /// #[cfg(windows)] + /// { /// use std::ffi::OsString; /// use std::os::windows::prelude::*; /// diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index 188ff00e1f8dd..6e0c7e5091ecd 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -64,8 +64,8 @@ use crate::time::SystemTime; /// /// ```no_run /// use std::fs::File; -/// use std::io::BufReader; /// use std::io::prelude::*; +/// use std::io::BufReader; /// /// fn main() -> std::io::Result<()> { /// let file = File::open("foo.txt")?; @@ -174,11 +174,7 @@ pub struct DirEntry(fs_imp::DirEntry); /// ```no_run /// use std::fs::OpenOptions; /// -/// let file = OpenOptions::new() -/// .read(true) -/// .write(true) -/// .create(true) -/// .open("foo.txt"); +/// let file = OpenOptions::new().read(true).write(true).create(true).open("foo.txt"); /// ``` #[derive(Clone, Debug)] #[stable(feature = "rust1", since = "1.0.0")] @@ -275,9 +271,9 @@ pub fn read>(path: P) -> io::Result> { /// # Examples /// /// ```no_run +/// use std::error::Error; /// use std::fs; /// use std::net::SocketAddr; -/// use std::error::Error; /// /// fn main() -> Result<(), Box> { /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?; @@ -574,8 +570,8 @@ impl File { /// /// ```no_run /// use std::fs::File; - /// use std::io::SeekFrom; /// use std::io::prelude::*; + /// use std::io::SeekFrom; /// /// fn main() -> std::io::Result<()> { /// let mut file = File::open("foo.txt")?; @@ -659,9 +655,7 @@ impl File { /// /// let src = fs::metadata("src")?; /// let dest = File::options().write(true).open("dest")?; - /// let times = FileTimes::new() - /// .set_accessed(src.accessed()?) - /// .set_modified(src.modified()?); + /// let times = FileTimes::new().set_accessed(src.accessed()?).set_modified(src.modified()?); /// dest.set_times(times)?; /// Ok(()) /// } @@ -999,9 +993,7 @@ impl OpenOptions { /// ```no_run /// use std::fs::OpenOptions; /// - /// let file = OpenOptions::new().write(true) - /// .create_new(true) - /// .open("foo.txt"); + /// let file = OpenOptions::new().write(true).create_new(true).open("foo.txt"); /// ``` #[stable(feature = "expand_open_options2", since = "1.9.0")] pub fn create_new(&mut self, create_new: bool) -> &mut Self { @@ -1149,7 +1141,6 @@ impl Metadata { /// Returns `true` if this metadata is for a symbolic link. /// /// # Examples - /// #[cfg_attr(unix, doc = "```no_run")] #[cfg_attr(not(unix), doc = "```ignore")] /// use std::fs; @@ -1952,7 +1943,7 @@ pub fn rename, Q: AsRef>(from: P, to: Q) -> io::Result<()> /// use std::fs; /// /// fn main() -> std::io::Result<()> { -/// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt +/// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt /// Ok(()) /// } /// ``` @@ -2308,8 +2299,8 @@ pub fn remove_dir_all>(path: P) -> io::Result<()> { /// # Examples /// /// ``` -/// use std::io; /// use std::fs::{self, DirEntry}; +/// use std::io; /// use std::path::Path; /// /// // one possible implementation of walking a directory only visiting files @@ -2436,9 +2427,7 @@ impl DirBuilder { /// use std::fs::{self, DirBuilder}; /// /// let path = "/tmp/foo/bar/baz"; - /// DirBuilder::new() - /// .recursive(true) - /// .create(path).unwrap(); + /// DirBuilder::new().recursive(true).create(path).unwrap(); /// /// assert!(fs::metadata(path).unwrap().is_dir()); /// ``` @@ -2504,7 +2493,10 @@ impl AsInnerMut for DirBuilder { /// #![feature(fs_try_exists)] /// use std::fs; /// -/// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt")); +/// assert!( +/// !fs::try_exists("does_not_exist.txt") +/// .expect("Can't check existence of file does_not_exist.txt") +/// ); /// assert!(fs::try_exists("/root/secret_file.txt").is_err()); /// ``` /// diff --git a/library/std/src/io/buffered/bufreader.rs b/library/std/src/io/buffered/bufreader.rs index 4f339a18a480e..6da989e80bbe1 100644 --- a/library/std/src/io/buffered/bufreader.rs +++ b/library/std/src/io/buffered/bufreader.rs @@ -24,7 +24,6 @@ use buffer::Buffer; /// stream can cause data loss. Reading from the underlying reader after /// unwrapping the `BufReader` with [`BufReader::into_inner`] can also cause /// data loss. -/// // HACK(#78696): can't use `crate` for associated items /// [`TcpStream::read`]: super::super::super::net::TcpStream::read /// [`TcpStream`]: crate::net::TcpStream @@ -32,9 +31,9 @@ use buffer::Buffer; /// # Examples /// /// ```no_run +/// use std::fs::File; /// use std::io::prelude::*; /// use std::io::BufReader; -/// use std::fs::File; /// /// fn main() -> std::io::Result<()> { /// let f = File::open("log.txt")?; @@ -59,8 +58,8 @@ impl BufReader { /// # Examples /// /// ```no_run - /// use std::io::BufReader; /// use std::fs::File; + /// use std::io::BufReader; /// /// fn main() -> std::io::Result<()> { /// let f = File::open("log.txt")?; @@ -80,8 +79,8 @@ impl BufReader { /// Creating a buffer with ten bytes of capacity: /// /// ```no_run - /// use std::io::BufReader; /// use std::fs::File; + /// use std::io::BufReader; /// /// fn main() -> std::io::Result<()> { /// let f = File::open("log.txt")?; @@ -103,8 +102,8 @@ impl BufReader { /// # Examples /// /// ```no_run - /// use std::io::BufReader; /// use std::fs::File; + /// use std::io::BufReader; /// /// fn main() -> std::io::Result<()> { /// let f1 = File::open("log.txt")?; @@ -126,8 +125,8 @@ impl BufReader { /// # Examples /// /// ```no_run - /// use std::io::BufReader; /// use std::fs::File; + /// use std::io::BufReader; /// /// fn main() -> std::io::Result<()> { /// let f1 = File::open("log.txt")?; @@ -151,8 +150,8 @@ impl BufReader { /// # Examples /// /// ```no_run - /// use std::io::{BufReader, BufRead}; /// use std::fs::File; + /// use std::io::{BufRead, BufReader}; /// /// fn main() -> std::io::Result<()> { /// let f = File::open("log.txt")?; @@ -175,8 +174,8 @@ impl BufReader { /// # Examples /// /// ```no_run - /// use std::io::{BufReader, BufRead}; /// use std::fs::File; + /// use std::io::{BufRead, BufReader}; /// /// fn main() -> std::io::Result<()> { /// let f = File::open("log.txt")?; @@ -201,8 +200,8 @@ impl BufReader { /// # Examples /// /// ```no_run - /// use std::io::BufReader; /// use std::fs::File; + /// use std::io::BufReader; /// /// fn main() -> std::io::Result<()> { /// let f1 = File::open("log.txt")?; @@ -466,8 +465,8 @@ impl Seek for BufReader { /// /// ```no_run /// use std::{ - /// io::{self, BufRead, BufReader, Seek}, /// fs::File, + /// io::{self, BufRead, BufReader, Seek}, /// }; /// /// fn main() -> io::Result<()> { diff --git a/library/std/src/io/buffered/bufwriter.rs b/library/std/src/io/buffered/bufwriter.rs index 6acb937e78479..60cd164b84cbb 100644 --- a/library/std/src/io/buffered/bufwriter.rs +++ b/library/std/src/io/buffered/bufwriter.rs @@ -37,7 +37,7 @@ use crate::ptr; /// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap(); /// /// for i in 0..10 { -/// stream.write(&[i+1]).unwrap(); +/// stream.write(&[i + 1]).unwrap(); /// } /// ``` /// @@ -53,7 +53,7 @@ use crate::ptr; /// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); /// /// for i in 0..10 { -/// stream.write(&[i+1]).unwrap(); +/// stream.write(&[i + 1]).unwrap(); /// } /// stream.flush().unwrap(); /// ``` @@ -61,7 +61,6 @@ use crate::ptr; /// By wrapping the stream with a `BufWriter`, these ten writes are all grouped /// together by the buffer and will all be written out in one system call when /// the `stream` is flushed. -/// // HACK(#78696): can't use `crate` for associated items /// [`TcpStream::write`]: super::super::super::net::TcpStream::write /// [`TcpStream`]: crate::net::TcpStream @@ -455,15 +454,17 @@ impl BufWriter { /// /// struct PanickingWriter; /// impl Write for PanickingWriter { -/// fn write(&mut self, buf: &[u8]) -> io::Result { panic!() } -/// fn flush(&mut self) -> io::Result<()> { panic!() } +/// fn write(&mut self, buf: &[u8]) -> io::Result { +/// panic!() +/// } +/// fn flush(&mut self) -> io::Result<()> { +/// panic!() +/// } /// } /// /// let mut stream = BufWriter::new(PanickingWriter); /// write!(stream, "some data").unwrap(); -/// let result = catch_unwind(AssertUnwindSafe(|| { -/// stream.flush().unwrap() -/// })); +/// let result = catch_unwind(AssertUnwindSafe(|| stream.flush().unwrap())); /// assert!(result.is_err()); /// let (recovered_writer, buffered_data) = stream.into_parts(); /// assert!(matches!(recovered_writer, PanickingWriter)); diff --git a/library/std/src/io/buffered/linewriter.rs b/library/std/src/io/buffered/linewriter.rs index a26a4ab330e7a..027fb8fc0168d 100644 --- a/library/std/src/io/buffered/linewriter.rs +++ b/library/std/src/io/buffered/linewriter.rs @@ -42,16 +42,15 @@ use crate::io::{self, buffered::LineWriterShim, BufWriter, IntoInnerError, IoSli /// // the internal buffer is filled). /// assert_eq!(fs::read_to_string("poem.txt")?, ""); /// file.write_all(b"\n")?; -/// assert_eq!( -/// fs::read_to_string("poem.txt")?, -/// "I shall be telling this with a sigh\n", -/// ); +/// assert_eq!(fs::read_to_string("poem.txt")?, "I shall be telling this with a sigh\n",); /// /// // Write the rest of the poem. -/// file.write_all(b"Somewhere ages and ages hence: +/// file.write_all( +/// b"Somewhere ages and ages hence: /// Two roads diverged in a wood, and I - /// I took the one less traveled by, -/// And that has made all the difference.")?; +/// And that has made all the difference.", +/// )?; /// /// // The last line of the poem doesn't end in a newline, so /// // we have to flush or drop the `LineWriter` to finish diff --git a/library/std/src/io/cursor.rs b/library/std/src/io/cursor.rs index d98ab021cadb1..b0f70748799d7 100644 --- a/library/std/src/io/cursor.rs +++ b/library/std/src/io/cursor.rs @@ -29,9 +29,9 @@ use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut, SeekFrom}; /// [`File`]: crate::fs::File /// /// ```no_run +/// use std::fs::File; /// use std::io::prelude::*; /// use std::io::{self, SeekFrom}; -/// use std::fs::File; /// /// // a library function we've written /// fn write_ten_bytes_at_end(writer: &mut W) -> io::Result<()> { @@ -161,8 +161,8 @@ impl Cursor { /// # Examples /// /// ``` - /// use std::io::Cursor; /// use std::io::prelude::*; + /// use std::io::Cursor; /// use std::io::SeekFrom; /// /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); diff --git a/library/std/src/io/error.rs b/library/std/src/io/error.rs index 3cabf24492eaf..67aef42b04265 100644 --- a/library/std/src/io/error.rs +++ b/library/std/src/io/error.rs @@ -342,7 +342,6 @@ pub enum ErrorKind { // ErrorKinds which are primarily categorisations for OS error // codes should be added above. - // /// An error returned when an operation could not be completed because an /// "end of file" was reached prematurely. /// @@ -360,7 +359,6 @@ pub enum ErrorKind { // "Unusual" error kinds which do not correspond simply to (sets // of) OS error codes, should be added just above this comment. // `Other` and `Uncategorised` should remain at the end: - // /// A custom error that does not fall under any other I/O error kind. /// /// This can be used to construct your own [`Error`]s that do not match any @@ -705,9 +703,9 @@ impl Error { /// # Examples /// /// ``` + /// use std::fmt::Display; /// use std::io::{Error, ErrorKind}; /// use std::{error, fmt}; - /// use std::fmt::Display; /// /// #[derive(Debug)] /// struct MyError { @@ -716,9 +714,7 @@ impl Error { /// /// impl MyError { /// fn new() -> MyError { - /// MyError { - /// v: "oh no!".to_string() - /// } + /// MyError { v: "oh no!".to_string() } /// } /// /// fn change_message(&mut self, new_message: &str) { @@ -822,9 +818,9 @@ impl Error { /// ``` /// #![feature(io_error_downcast)] /// + /// use std::error::Error; /// use std::fmt; /// use std::io; - /// use std::error::Error; /// /// #[derive(Debug)] /// enum E { @@ -833,7 +829,7 @@ impl Error { /// } /// /// impl fmt::Display for E { - /// // ... + /// // ... /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { /// # todo!() /// # } @@ -842,9 +838,7 @@ impl Error { /// /// impl From for E { /// fn from(err: io::Error) -> E { - /// err.downcast::() - /// .map(|b| *b) - /// .unwrap_or_else(E::Io) + /// err.downcast::().map(|b| *b).unwrap_or_else(E::Io) /// } /// } /// ``` diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index 23a13523fc275..a41b439602618 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -15,9 +15,9 @@ //! [`File`]s: //! //! ```no_run +//! use std::fs::File; //! use std::io; //! use std::io::prelude::*; -//! use std::fs::File; //! //! fn main() -> io::Result<()> { //! let mut f = File::open("foo.txt")?; @@ -43,10 +43,10 @@ //! coming from: //! //! ```no_run +//! use std::fs::File; //! use std::io; //! use std::io::prelude::*; //! use std::io::SeekFrom; -//! use std::fs::File; //! //! fn main() -> io::Result<()> { //! let mut f = File::open("foo.txt")?; @@ -78,10 +78,10 @@ //! methods to any reader: //! //! ```no_run +//! use std::fs::File; //! use std::io; //! use std::io::prelude::*; //! use std::io::BufReader; -//! use std::fs::File; //! //! fn main() -> io::Result<()> { //! let f = File::open("foo.txt")?; @@ -100,10 +100,10 @@ //! to [`write`][`Write::write`]: //! //! ```no_run +//! use std::fs::File; //! use std::io; //! use std::io::prelude::*; //! use std::io::BufWriter; -//! use std::fs::File; //! //! fn main() -> io::Result<()> { //! let f = File::create("foo.txt")?; @@ -112,7 +112,6 @@ //! //! // write a byte to the buffer //! writer.write(&[42])?; -//! //! } // the buffer is flushed once writer goes out of scope //! //! Ok(()) @@ -170,10 +169,10 @@ //! lines: //! //! ```no_run +//! use std::fs::File; //! use std::io; //! use std::io::prelude::*; //! use std::io::BufReader; -//! use std::fs::File; //! //! fn main() -> io::Result<()> { //! let f = File::open("foo.txt")?; @@ -500,9 +499,9 @@ where /// [`File`]s implement `Read`: /// /// ```no_run +/// use std::fs::File; /// use std::io; /// use std::io::prelude::*; -/// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut f = File::open("foo.txt")?; @@ -614,9 +613,9 @@ pub trait Read { /// [`TcpStream`]: crate::net::TcpStream /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut f = File::open("foo.txt")?; @@ -687,9 +686,9 @@ pub trait Read { /// [`File`]: crate::fs::File /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut f = File::open("foo.txt")?; @@ -731,9 +730,9 @@ pub trait Read { /// [`File`]: crate::fs::File /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut f = File::open("foo.txt")?; @@ -790,9 +789,9 @@ pub trait Read { /// [`File`]: crate::fs::File /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut f = File::open("foo.txt")?; @@ -853,9 +852,9 @@ pub trait Read { /// [`File`]: crate::fs::File /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::Read; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut f = File::open("foo.txt")?; @@ -867,7 +866,6 @@ pub trait Read { /// /// // read at most 5 bytes /// reference.take(5).read_to_end(&mut buffer)?; - /// /// } // drop our &mut reference so we can use f again /// /// // original file still usable, read the rest @@ -904,10 +902,10 @@ pub trait Read { /// [io::Error]: self::Error "io::Error" /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; /// use std::io::BufReader; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let f = BufReader::new(File::open("foo.txt")?); @@ -939,9 +937,9 @@ pub trait Read { /// [`File`]: crate::fs::File /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let f1 = File::open("foo.txt")?; @@ -980,9 +978,9 @@ pub trait Read { /// [`read()`]: Read::read /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let f = File::open("foo.txt")?; @@ -1356,8 +1354,8 @@ impl<'a> Deref for IoSlice<'a> { /// # Examples /// /// ```no_run -/// use std::io::prelude::*; /// use std::fs::File; +/// use std::io::prelude::*; /// /// fn main() -> std::io::Result<()> { /// let data = b"some bytes"; @@ -1412,8 +1410,8 @@ pub trait Write { /// # Examples /// /// ```no_run - /// use std::io::prelude::*; /// use std::fs::File; + /// use std::io::prelude::*; /// /// fn main() -> std::io::Result<()> { /// let mut buffer = File::create("foo.txt")?; @@ -1440,9 +1438,9 @@ pub trait Write { /// # Examples /// /// ```no_run - /// use std::io::IoSlice; - /// use std::io::prelude::*; /// use std::fs::File; + /// use std::io::prelude::*; + /// use std::io::IoSlice; /// /// fn main() -> std::io::Result<()> { /// let data1 = [1; 8]; @@ -1490,9 +1488,9 @@ pub trait Write { /// # Examples /// /// ```no_run + /// use std::fs::File; /// use std::io::prelude::*; /// use std::io::BufWriter; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { /// let mut buffer = BufWriter::new(File::create("foo.txt")?); @@ -1526,8 +1524,8 @@ pub trait Write { /// # Examples /// /// ```no_run - /// use std::io::prelude::*; /// use std::fs::File; + /// use std::io::prelude::*; /// /// fn main() -> std::io::Result<()> { /// let mut buffer = File::create("foo.txt")?; @@ -1586,14 +1584,10 @@ pub trait Write { /// #![feature(write_all_vectored)] /// # fn main() -> std::io::Result<()> { /// - /// use std::io::{Write, IoSlice}; + /// use std::io::{IoSlice, Write}; /// /// let mut writer = Vec::new(); - /// let bufs = &mut [ - /// IoSlice::new(&[1]), - /// IoSlice::new(&[2, 3]), - /// IoSlice::new(&[4, 5, 6]), - /// ]; + /// let bufs = &mut [IoSlice::new(&[1]), IoSlice::new(&[2, 3]), IoSlice::new(&[4, 5, 6])]; /// /// writer.write_all_vectored(bufs)?; /// // Note: the contents of `bufs` is now undefined, see the Notes section. @@ -1644,8 +1638,8 @@ pub trait Write { /// # Examples /// /// ```no_run - /// use std::io::prelude::*; /// use std::fs::File; + /// use std::io::prelude::*; /// /// fn main() -> std::io::Result<()> { /// let mut buffer = File::create("foo.txt")?; @@ -1700,8 +1694,8 @@ pub trait Write { /// # Examples /// /// ```no_run - /// use std::io::Write; /// use std::fs::File; + /// use std::io::Write; /// /// fn main() -> std::io::Result<()> { /// let mut buffer = File::create("foo.txt")?; @@ -1735,9 +1729,9 @@ pub trait Write { /// [`File`]: crate::fs::File /// /// ```no_run +/// use std::fs::File; /// use std::io; /// use std::io::prelude::*; -/// use std::fs::File; /// use std::io::SeekFrom; /// /// fn main() -> io::Result<()> { @@ -1778,14 +1772,10 @@ pub trait Seek { /// # Example /// /// ```no_run - /// use std::io::{Read, Seek, Write}; /// use std::fs::OpenOptions; + /// use std::io::{Read, Seek, Write}; /// - /// let mut f = OpenOptions::new() - /// .write(true) - /// .read(true) - /// .create(true) - /// .open("foo.txt").unwrap(); + /// let mut f = OpenOptions::new().write(true).read(true).create(true).open("foo.txt").unwrap(); /// /// let hello = "Hello!\n"; /// write!(f, "{hello}").unwrap(); @@ -1823,8 +1813,8 @@ pub trait Seek { /// ```no_run /// #![feature(seek_stream_len)] /// use std::{ - /// io::{self, Seek}, /// fs::File, + /// io::{self, Seek}, /// }; /// /// fn main() -> io::Result<()> { @@ -1857,8 +1847,8 @@ pub trait Seek { /// /// ```no_run /// use std::{ - /// io::{self, BufRead, BufReader, Seek}, /// fs::File, + /// io::{self, BufRead, BufReader, Seek}, /// }; /// /// fn main() -> io::Result<()> { @@ -1965,9 +1955,9 @@ fn read_until(r: &mut R, delim: u8, buf: &mut Vec) -> R /// [`lines`]: BufRead::lines /// /// ```no_run -/// use std::io::{self, BufReader}; -/// use std::io::prelude::*; /// use std::fs::File; +/// use std::io::prelude::*; +/// use std::io::{self, BufReader}; /// /// fn main() -> io::Result<()> { /// let f = File::open("foo.txt")?; @@ -2112,22 +2102,19 @@ pub trait BufRead: Read { /// let mut buf = vec![]; /// /// // cursor is at 'l' - /// let num_bytes = cursor.read_until(b'-', &mut buf) - /// .expect("reading from cursor won't fail"); + /// let num_bytes = cursor.read_until(b'-', &mut buf).expect("reading from cursor won't fail"); /// assert_eq!(num_bytes, 6); /// assert_eq!(buf, b"lorem-"); /// buf.clear(); /// /// // cursor is at 'i' - /// let num_bytes = cursor.read_until(b'-', &mut buf) - /// .expect("reading from cursor won't fail"); + /// let num_bytes = cursor.read_until(b'-', &mut buf).expect("reading from cursor won't fail"); /// assert_eq!(num_bytes, 5); /// assert_eq!(buf, b"ipsum"); /// buf.clear(); /// /// // cursor is at EOF - /// let num_bytes = cursor.read_until(b'-', &mut buf) - /// .expect("reading from cursor won't fail"); + /// let num_bytes = cursor.read_until(b'-', &mut buf).expect("reading from cursor won't fail"); /// assert_eq!(num_bytes, 0); /// assert_eq!(buf, b""); /// ``` @@ -2176,22 +2163,19 @@ pub trait BufRead: Read { /// let mut buf = String::new(); /// /// // cursor is at 'f' - /// let num_bytes = cursor.read_line(&mut buf) - /// .expect("reading from cursor won't fail"); + /// let num_bytes = cursor.read_line(&mut buf).expect("reading from cursor won't fail"); /// assert_eq!(num_bytes, 4); /// assert_eq!(buf, "foo\n"); /// buf.clear(); /// /// // cursor is at 'b' - /// let num_bytes = cursor.read_line(&mut buf) - /// .expect("reading from cursor won't fail"); + /// let num_bytes = cursor.read_line(&mut buf).expect("reading from cursor won't fail"); /// assert_eq!(num_bytes, 3); /// assert_eq!(buf, "bar"); /// buf.clear(); /// /// // cursor is at EOF - /// let num_bytes = cursor.read_line(&mut buf) - /// .expect("reading from cursor won't fail"); + /// let num_bytes = cursor.read_line(&mut buf).expect("reading from cursor won't fail"); /// assert_eq!(num_bytes, 0); /// assert_eq!(buf, ""); /// ``` @@ -2299,9 +2283,9 @@ impl Chain { /// # Examples /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut foo_file = File::open("foo.txt")?; @@ -2322,9 +2306,9 @@ impl Chain { /// # Examples /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut foo_file = File::open("foo.txt")?; @@ -2349,9 +2333,9 @@ impl Chain { /// # Examples /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut foo_file = File::open("foo.txt")?; @@ -2450,9 +2434,9 @@ impl Take { /// # Examples /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let f = File::open("foo.txt")?; @@ -2477,9 +2461,9 @@ impl Take { /// # Examples /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let f = File::open("foo.txt")?; @@ -2502,9 +2486,9 @@ impl Take { /// # Examples /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut file = File::open("foo.txt")?; @@ -2527,9 +2511,9 @@ impl Take { /// # Examples /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut file = File::open("foo.txt")?; @@ -2556,9 +2540,9 @@ impl Take { /// # Examples /// /// ```no_run + /// use std::fs::File; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { /// let mut file = File::open("foo.txt")?; diff --git a/library/std/src/keyword_docs.rs b/library/std/src/keyword_docs.rs index e35145c4ade48..d6714a8afc3df 100644 --- a/library/std/src/keyword_docs.rs +++ b/library/std/src/keyword_docs.rs @@ -251,7 +251,7 @@ mod continue_keyword {} /// ```rust /// # #[allow(unused_imports)] /// pub(crate) use std::io::Error as IoError; -/// pub(crate) enum CoolMarkerType { } +/// pub(crate) enum CoolMarkerType {} /// pub struct PublicThing { /// pub(crate) semi_secret_thing: bool, /// } @@ -343,13 +343,10 @@ mod else_keyword {} /// enum ComplexEnum { /// Nothing, /// Something(u32), -/// LotsOfThings { -/// usual_struct_stuff: bool, -/// blah: String, -/// } +/// LotsOfThings { usual_struct_stuff: bool, blah: String }, /// } /// -/// enum EmptyEnum { } +/// enum EmptyEnum {} /// ``` /// /// The first enum shown is the usual kind of enum you'd find in a C-style language. The second @@ -454,9 +451,7 @@ mod false_keyword {} /// /// impl Thing { /// pub fn new() -> Self { -/// Self { -/// foo: 42, -/// } +/// Self { foo: 42 } /// } /// } /// ``` @@ -471,7 +466,8 @@ mod false_keyword {} /// } /// /// fn generic_where(x: T) -> T -/// where T: std::ops::Add + Copy +/// where +/// T: std::ops::Add + Copy, /// { /// x + x + x /// } @@ -551,7 +547,9 @@ mod fn_keyword {} /// mut iter => loop { /// match iter.next() { /// None => break, -/// Some(loop_variable) => { code(); }, +/// Some(loop_variable) => { +/// code(); +/// } /// }; /// }, /// }; @@ -590,11 +588,7 @@ mod for_keyword {} /// println!("everything's fine!"); /// } /// -/// let greeting = if rude { -/// "sup nerd." -/// } else { -/// "hello, friend!" -/// }; +/// let greeting = if rude { "sup nerd." } else { "hello, friend!" }; /// /// if let Ok(x) = "123".parse::() { /// println!("{} double that and you get {}!", greeting, x * 2); @@ -619,10 +613,10 @@ mod for_keyword {} /// Some(x) => { /// // code /// # let _ = x; -/// }, +/// } /// _ => { /// // something else -/// }, +/// } /// } /// ``` /// @@ -766,10 +760,7 @@ mod in_keyword {} /// b: u64, /// } /// -/// let Example { a, b: _ } = Example { -/// a: true, -/// b: 10004, -/// }; +/// let Example { a, b: _ } = Example { a: true, b: 10004 }; /// assert!(a); /// ``` /// @@ -851,7 +842,7 @@ mod let_keyword {} /// counter = None; /// } else { /// println!("{i}"); -/// counter = Some (i + 1); +/// counter = Some(i + 1); /// } /// } /// ``` @@ -949,7 +940,7 @@ mod loop_keyword {} /// enum Outer { /// Double(Option, Option), /// Single(Option), -/// Empty +/// Empty, /// } /// /// let get_inner = Outer::Double(None, Some(String::new())); @@ -1027,9 +1018,7 @@ mod mod_keyword {} /// ```rust /// let data = vec![1, 2, 3]; /// -/// std::thread::spawn(move || { -/// println!("captured {data:?} by value") -/// }).join().unwrap(); +/// std::thread::spawn(move || println!("captured {data:?} by value")).join().unwrap(); /// /// // data was moved to the spawned thread, so we cannot use it here /// ``` @@ -1483,7 +1472,7 @@ mod static_keyword {} /// struct Regular { /// field1: f32, /// field2: String, -/// pub field3: bool +/// pub field3: bool, /// } /// /// struct Tuple(u32, String); @@ -1516,11 +1505,7 @@ mod static_keyword {} /// /// ```rust /// # struct Foo { field1: f32, field2: String, etc: bool } -/// let example = Foo { -/// field1: 42.0, -/// field2: "blah".to_string(), -/// etc: true, -/// }; +/// let example = Foo { field1: 42.0, field2: "blah".to_string(), etc: true }; /// ``` /// /// It's only possible to directly instantiate a struct using struct literal syntax when all of its @@ -1539,10 +1524,7 @@ mod static_keyword {} /// /// impl User { /// pub fn new(name: String) -> Self { -/// Self { -/// name, -/// admin: false, -/// } +/// Self { name, admin: false } /// } /// } /// ``` @@ -1554,10 +1536,7 @@ mod static_keyword {} /// ```rust /// # struct Foo { field1: String, field2: () } /// # let thing = Foo { field1: "".to_string(), field2: () }; -/// let updated_thing = Foo { -/// field1: "a new value".to_string(), -/// ..thing -/// }; +/// let updated_thing = Foo { field1: "a new value".to_string(), ..thing }; /// ``` /// /// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's @@ -1687,7 +1666,10 @@ mod super_keyword {} /// /// ```rust /// # #![allow(dead_code)] -/// fn debug_iter(it: I) where I::Item: std::fmt::Debug { +/// fn debug_iter(it: I) +/// where +/// I::Item: std::fmt::Debug, +/// { /// for elem in it { /// println!("{elem:#?}"); /// } @@ -2007,7 +1989,9 @@ mod type_keyword {} /// let b = &a as *const _; /// // SAFETY: `a` has not been dropped and references are always aligned, /// // so `b` is a valid address. -/// unsafe { assert_eq!(*b, deref_unchecked(b)); }; +/// unsafe { +/// assert_eq!(*b, deref_unchecked(b)); +/// }; /// ``` /// /// ## `unsafe` and traits diff --git a/library/std/src/macros.rs b/library/std/src/macros.rs index 6e4ba1404e551..07b509e98c0ab 100644 --- a/library/std/src/macros.rs +++ b/library/std/src/macros.rs @@ -275,11 +275,7 @@ macro_rules! eprintln { /// /// ```rust /// fn factorial(n: u32) -> u32 { -/// if dbg!(n <= 1) { -/// dbg!(1) -/// } else { -/// dbg!(n * factorial(n - 1)) -/// } +/// if dbg!(n <= 1) { dbg!(1) } else { dbg!(n * factorial(n - 1)) } /// } /// /// dbg!(factorial(4)); diff --git a/library/std/src/net/ip_addr.rs b/library/std/src/net/ip_addr.rs index 4f14fc28038ad..292978661c572 100644 --- a/library/std/src/net/ip_addr.rs +++ b/library/std/src/net/ip_addr.rs @@ -190,9 +190,8 @@ pub struct Ipv6Addr { /// Some(OrganizationLocal) => println!("Organization-Local scope"), /// Some(Global) => println!("Global scope"), /// Some(_) => println!("Unknown scope"), -/// None => println!("Not a multicast address!") +/// None => println!("Not a multicast address!"), /// } -/// /// ``` /// /// [IPv6 multicast address]: Ipv6Addr @@ -329,10 +328,7 @@ impl IpAddr { /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; /// /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true); - /// assert_eq!( - /// IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(), - /// true - /// ); + /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(), true); /// ``` #[rustc_const_unstable(feature = "const_ip", issue = "76205")] #[unstable(feature = "ip", issue = "27709")] @@ -423,7 +419,10 @@ impl IpAddr { /// /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).to_canonical().is_loopback(), true); /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1)).is_loopback(), false); - /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1)).to_canonical().is_loopback(), true); + /// assert_eq!( + /// IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1)).to_canonical().is_loopback(), + /// true + /// ); /// ``` #[inline] #[must_use = "this returns the result of the operation, \ @@ -912,8 +911,10 @@ impl Ipv4Addr { /// ``` /// use std::net::{Ipv4Addr, Ipv6Addr}; /// - /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(), - /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x2ff)); + /// assert_eq!( + /// Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(), + /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x2ff) + /// ); /// ``` #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")] #[stable(feature = "rust1", since = "1.0.0")] @@ -954,10 +955,7 @@ impl From for IpAddr { /// /// let addr = Ipv4Addr::new(127, 0, 0, 1); /// - /// assert_eq!( - /// IpAddr::V4(addr), - /// IpAddr::from(addr) - /// ) + /// assert_eq!(IpAddr::V4(addr), IpAddr::from(addr)) /// ``` #[inline] fn from(ipv4: Ipv4Addr) -> IpAddr { @@ -976,10 +974,7 @@ impl From for IpAddr { /// /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff); /// - /// assert_eq!( - /// IpAddr::V6(addr), - /// IpAddr::from(addr) - /// ); + /// assert_eq!(IpAddr::V6(addr), IpAddr::from(addr)); /// ``` #[inline] fn from(ipv6: Ipv6Addr) -> IpAddr { @@ -1228,8 +1223,10 @@ impl Ipv6Addr { /// ``` /// use std::net::Ipv6Addr; /// - /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(), - /// [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]); + /// assert_eq!( + /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(), + /// [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff] + /// ); /// ``` #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")] #[stable(feature = "rust1", since = "1.0.0")] @@ -1665,8 +1662,10 @@ impl Ipv6Addr { /// use std::net::{Ipv4Addr, Ipv6Addr}; /// /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None); - /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(), - /// Some(Ipv4Addr::new(192, 10, 2, 255))); + /// assert_eq!( + /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(), + /// Some(Ipv4Addr::new(192, 10, 2, 255)) + /// ); /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None); /// ``` #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")] @@ -1706,10 +1705,11 @@ impl Ipv6Addr { /// use std::net::{Ipv4Addr, Ipv6Addr}; /// /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None); - /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(), - /// Some(Ipv4Addr::new(192, 10, 2, 255))); - /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(), - /// Some(Ipv4Addr::new(0, 0, 0, 1))); + /// assert_eq!( + /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(), + /// Some(Ipv4Addr::new(192, 10, 2, 255)) + /// ); + /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(), Some(Ipv4Addr::new(0, 0, 0, 1))); /// ``` #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")] #[stable(feature = "rust1", since = "1.0.0")] @@ -1736,7 +1736,10 @@ impl Ipv6Addr { /// use std::net::Ipv6Addr; /// /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).is_loopback(), false); - /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).to_canonical().is_loopback(), true); + /// assert_eq!( + /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).to_canonical().is_loopback(), + /// true + /// ); /// ``` #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")] #[unstable(feature = "ip", issue = "27709")] @@ -1755,8 +1758,10 @@ impl Ipv6Addr { /// ``` /// use std::net::Ipv6Addr; /// - /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(), - /// [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + /// assert_eq!( + /// Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(), + /// [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + /// ); /// ``` #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")] #[stable(feature = "ipv6_to_octets", since = "1.12.0")] @@ -1943,10 +1948,7 @@ impl From for u128 { /// ``` /// use std::net::Ipv6Addr; /// - /// let addr = Ipv6Addr::new( - /// 0x1020, 0x3040, 0x5060, 0x7080, - /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D, - /// ); + /// let addr = Ipv6Addr::new(0x1020, 0x3040, 0x5060, 0x7080, 0x90A0, 0xB0C0, 0xD0E0, 0xF00D); /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr)); /// ``` #[inline] @@ -1965,11 +1967,9 @@ impl From for Ipv6Addr { /// /// let addr = Ipv6Addr::from(0x102030405060708090A0B0C0D0E0F00D_u128); /// assert_eq!( - /// Ipv6Addr::new( - /// 0x1020, 0x3040, 0x5060, 0x7080, - /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D, - /// ), - /// addr); + /// Ipv6Addr::new(0x1020, 0x3040, 0x5060, 0x7080, 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,), + /// addr + /// ); /// ``` #[inline] fn from(ip: u128) -> Ipv6Addr { @@ -1987,18 +1987,10 @@ impl From<[u8; 16]> for Ipv6Addr { /// use std::net::Ipv6Addr; /// /// let addr = Ipv6Addr::from([ - /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8, - /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8, + /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8, 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, + /// 10u8, /// ]); - /// assert_eq!( - /// Ipv6Addr::new( - /// 0x1918, 0x1716, - /// 0x1514, 0x1312, - /// 0x1110, 0x0f0e, - /// 0x0d0c, 0x0b0a - /// ), - /// addr - /// ); + /// assert_eq!(Ipv6Addr::new(0x1918, 0x1716, 0x1514, 0x1312, 0x1110, 0x0f0e, 0x0d0c, 0x0b0a), addr); /// ``` #[inline] fn from(octets: [u8; 16]) -> Ipv6Addr { @@ -2015,19 +2007,8 @@ impl From<[u16; 8]> for Ipv6Addr { /// ``` /// use std::net::Ipv6Addr; /// - /// let addr = Ipv6Addr::from([ - /// 525u16, 524u16, 523u16, 522u16, - /// 521u16, 520u16, 519u16, 518u16, - /// ]); - /// assert_eq!( - /// Ipv6Addr::new( - /// 0x20d, 0x20c, - /// 0x20b, 0x20a, - /// 0x209, 0x208, - /// 0x207, 0x206 - /// ), - /// addr - /// ); + /// let addr = Ipv6Addr::from([525u16, 524u16, 523u16, 522u16, 521u16, 520u16, 519u16, 518u16]); + /// assert_eq!(Ipv6Addr::new(0x20d, 0x20c, 0x20b, 0x20a, 0x209, 0x208, 0x207, 0x206), addr); /// ``` #[inline] fn from(segments: [u16; 8]) -> Ipv6Addr { @@ -2046,16 +2027,11 @@ impl From<[u8; 16]> for IpAddr { /// use std::net::{IpAddr, Ipv6Addr}; /// /// let addr = IpAddr::from([ - /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8, - /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8, + /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8, 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, + /// 10u8, /// ]); /// assert_eq!( - /// IpAddr::V6(Ipv6Addr::new( - /// 0x1918, 0x1716, - /// 0x1514, 0x1312, - /// 0x1110, 0x0f0e, - /// 0x0d0c, 0x0b0a - /// )), + /// IpAddr::V6(Ipv6Addr::new(0x1918, 0x1716, 0x1514, 0x1312, 0x1110, 0x0f0e, 0x0d0c, 0x0b0a)), /// addr /// ); /// ``` @@ -2074,17 +2050,9 @@ impl From<[u16; 8]> for IpAddr { /// ``` /// use std::net::{IpAddr, Ipv6Addr}; /// - /// let addr = IpAddr::from([ - /// 525u16, 524u16, 523u16, 522u16, - /// 521u16, 520u16, 519u16, 518u16, - /// ]); + /// let addr = IpAddr::from([525u16, 524u16, 523u16, 522u16, 521u16, 520u16, 519u16, 518u16]); /// assert_eq!( - /// IpAddr::V6(Ipv6Addr::new( - /// 0x20d, 0x20c, - /// 0x20b, 0x20a, - /// 0x209, 0x208, - /// 0x207, 0x206 - /// )), + /// IpAddr::V6(Ipv6Addr::new(0x20d, 0x20c, 0x20b, 0x20a, 0x209, 0x208, 0x207, 0x206)), /// addr /// ); /// ``` diff --git a/library/std/src/net/socket_addr.rs b/library/std/src/net/socket_addr.rs index 33b0dfa03e0ed..0ad3d29e37881 100644 --- a/library/std/src/net/socket_addr.rs +++ b/library/std/src/net/socket_addr.rs @@ -274,7 +274,7 @@ impl SocketAddrV4 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV4, Ipv4Addr}; + /// use std::net::{Ipv4Addr, SocketAddrV4}; /// /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080); /// ``` @@ -290,7 +290,7 @@ impl SocketAddrV4 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV4, Ipv4Addr}; + /// use std::net::{Ipv4Addr, SocketAddrV4}; /// /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080); /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1)); @@ -307,7 +307,7 @@ impl SocketAddrV4 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV4, Ipv4Addr}; + /// use std::net::{Ipv4Addr, SocketAddrV4}; /// /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080); /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1)); @@ -323,7 +323,7 @@ impl SocketAddrV4 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV4, Ipv4Addr}; + /// use std::net::{Ipv4Addr, SocketAddrV4}; /// /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080); /// assert_eq!(socket.port(), 8080); @@ -340,7 +340,7 @@ impl SocketAddrV4 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV4, Ipv4Addr}; + /// use std::net::{Ipv4Addr, SocketAddrV4}; /// /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080); /// socket.set_port(4242); @@ -365,7 +365,7 @@ impl SocketAddrV6 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV6, Ipv6Addr}; + /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0); /// ``` @@ -381,7 +381,7 @@ impl SocketAddrV6 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV6, Ipv6Addr}; + /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0); /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); @@ -398,7 +398,7 @@ impl SocketAddrV6 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV6, Ipv6Addr}; + /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0); /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0)); @@ -414,7 +414,7 @@ impl SocketAddrV6 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV6, Ipv6Addr}; + /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0); /// assert_eq!(socket.port(), 8080); @@ -431,7 +431,7 @@ impl SocketAddrV6 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV6, Ipv6Addr}; + /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0); /// socket.set_port(4242); @@ -457,7 +457,7 @@ impl SocketAddrV6 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV6, Ipv6Addr}; + /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0); /// assert_eq!(socket.flowinfo(), 10); @@ -476,7 +476,7 @@ impl SocketAddrV6 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV6, Ipv6Addr}; + /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0); /// socket.set_flowinfo(56); @@ -497,7 +497,7 @@ impl SocketAddrV6 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV6, Ipv6Addr}; + /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78); /// assert_eq!(socket.scope_id(), 78); @@ -516,7 +516,7 @@ impl SocketAddrV6 { /// # Examples /// /// ``` - /// use std::net::{SocketAddrV6, Ipv6Addr}; + /// use std::net::{Ipv6Addr, SocketAddrV6}; /// /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78); /// socket.set_scope_id(42); @@ -758,7 +758,7 @@ impl hash::Hash for SocketAddrV6 { /// Creating a [`SocketAddr`] iterator that yields one item: /// /// ``` -/// use std::net::{ToSocketAddrs, SocketAddr}; +/// use std::net::{SocketAddr, ToSocketAddrs}; /// /// let addr = SocketAddr::from(([127, 0, 0, 1], 443)); /// let mut addrs_iter = addr.to_socket_addrs().unwrap(); @@ -813,7 +813,7 @@ impl hash::Hash for SocketAddrV6 { /// different types: /// /// ```no_run -/// use std::net::{TcpStream, Ipv4Addr}; +/// use std::net::{Ipv4Addr, TcpStream}; /// /// let stream = TcpStream::connect(("127.0.0.1", 443)); /// // or diff --git a/library/std/src/net/tcp.rs b/library/std/src/net/tcp.rs index 69b72a81c5b6d..0700b5703d795 100644 --- a/library/std/src/net/tcp.rs +++ b/library/std/src/net/tcp.rs @@ -142,10 +142,8 @@ impl TcpStream { /// ```no_run /// use std::net::{SocketAddr, TcpStream}; /// - /// let addrs = [ - /// SocketAddr::from(([127, 0, 0, 1], 8080)), - /// SocketAddr::from(([127, 0, 0, 1], 8081)), - /// ]; + /// let addrs = + /// [SocketAddr::from(([127, 0, 0, 1], 8080)), SocketAddr::from(([127, 0, 0, 1], 8081))]; /// if let Ok(stream) = TcpStream::connect(&addrs[..]) { /// println!("Connected to the server!"); /// } else { @@ -180,10 +178,11 @@ impl TcpStream { /// ```no_run /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream}; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); - /// assert_eq!(stream.peer_addr().unwrap(), - /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080))); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); + /// assert_eq!( + /// stream.peer_addr().unwrap(), + /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)) + /// ); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn peer_addr(&self) -> io::Result { @@ -197,10 +196,8 @@ impl TcpStream { /// ```no_run /// use std::net::{IpAddr, Ipv4Addr, TcpStream}; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); - /// assert_eq!(stream.local_addr().unwrap().ip(), - /// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); + /// assert_eq!(stream.local_addr().unwrap().ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn local_addr(&self) -> io::Result { @@ -225,8 +222,7 @@ impl TcpStream { /// ```no_run /// use std::net::{Shutdown, TcpStream}; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.shutdown(Shutdown::Both).expect("shutdown call failed"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -246,8 +242,7 @@ impl TcpStream { /// ```no_run /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// let stream_clone = stream.try_clone().expect("clone failed..."); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -276,8 +271,7 @@ impl TcpStream { /// ```no_run /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_read_timeout(None).expect("set_read_timeout call failed"); /// ``` /// @@ -320,8 +314,7 @@ impl TcpStream { /// ```no_run /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_write_timeout(None).expect("set_write_timeout call failed"); /// ``` /// @@ -358,8 +351,7 @@ impl TcpStream { /// ```no_run /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_read_timeout(None).expect("set_read_timeout call failed"); /// assert_eq!(stream.read_timeout().unwrap(), None); /// ``` @@ -383,8 +375,7 @@ impl TcpStream { /// ```no_run /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_write_timeout(None).expect("set_write_timeout call failed"); /// assert_eq!(stream.write_timeout().unwrap(), None); /// ``` @@ -405,8 +396,7 @@ impl TcpStream { /// ```no_run /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:8000") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8000").expect("Couldn't connect to the server..."); /// let mut buf = [0; 10]; /// let len = stream.peek(&mut buf).expect("peek failed"); /// ``` @@ -431,8 +421,7 @@ impl TcpStream { /// use std::net::TcpStream; /// use std::time::Duration; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed"); /// ``` #[unstable(feature = "tcp_linger", issue = "88494")] @@ -452,8 +441,7 @@ impl TcpStream { /// use std::net::TcpStream; /// use std::time::Duration; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed"); /// assert_eq!(stream.linger().unwrap(), Some(Duration::from_secs(0))); /// ``` @@ -475,8 +463,7 @@ impl TcpStream { /// ```no_run /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_nodelay(true).expect("set_nodelay call failed"); /// ``` #[stable(feature = "net2_mutators", since = "1.9.0")] @@ -493,8 +480,7 @@ impl TcpStream { /// ```no_run /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_nodelay(true).expect("set_nodelay call failed"); /// assert_eq!(stream.nodelay().unwrap_or(false), true); /// ``` @@ -513,8 +499,7 @@ impl TcpStream { /// ```no_run /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_ttl(100).expect("set_ttl call failed"); /// ``` #[stable(feature = "net2_mutators", since = "1.9.0")] @@ -531,8 +516,7 @@ impl TcpStream { /// ```no_run /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_ttl(100).expect("set_ttl call failed"); /// assert_eq!(stream.ttl().unwrap_or(0), 100); /// ``` @@ -552,8 +536,7 @@ impl TcpStream { /// ```no_run /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.take_error().expect("No error was expected..."); /// ``` #[stable(feature = "net2_mutators", since = "1.9.0")] @@ -582,8 +565,8 @@ impl TcpStream { /// use std::io::{self, Read}; /// use std::net::TcpStream; /// - /// let mut stream = TcpStream::connect("127.0.0.1:7878") - /// .expect("Couldn't connect to the server..."); + /// let mut stream = + /// TcpStream::connect("127.0.0.1:7878").expect("Couldn't connect to the server..."); /// stream.set_nonblocking(true).expect("set_nonblocking call failed"); /// /// # fn wait_for_fd() { unimplemented!() } @@ -598,7 +581,7 @@ impl TcpStream { /// } /// Err(e) => panic!("encountered IO error: {e}"), /// }; - /// }; + /// } /// println!("bytes: {buf:?}"); /// ``` #[stable(feature = "net2_mutators", since = "1.9.0")] @@ -741,10 +724,7 @@ impl TcpListener { /// ```no_run /// use std::net::{SocketAddr, TcpListener}; /// - /// let addrs = [ - /// SocketAddr::from(([127, 0, 0, 1], 80)), - /// SocketAddr::from(([127, 0, 0, 1], 443)), - /// ]; + /// let addrs = [SocketAddr::from(([127, 0, 0, 1], 80)), SocketAddr::from(([127, 0, 0, 1], 443))]; /// let listener = TcpListener::bind(&addrs[..]).unwrap(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -760,8 +740,10 @@ impl TcpListener { /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener}; /// /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); - /// assert_eq!(listener.local_addr().unwrap(), - /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080))); + /// assert_eq!( + /// listener.local_addr().unwrap(), + /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)) + /// ); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn local_addr(&self) -> io::Result { @@ -825,7 +807,7 @@ impl TcpListener { /// use std::net::{TcpListener, TcpStream}; /// /// fn handle_connection(stream: TcpStream) { - /// //... + /// //... /// } /// /// fn main() -> std::io::Result<()> { @@ -862,14 +844,11 @@ impl TcpListener { /// /// fn listen_on(port: u16) -> impl Iterator { /// let listener = TcpListener::bind("127.0.0.1:80").unwrap(); - /// listener.into_incoming() - /// .filter_map(Result::ok) /* Ignore failed connections */ + /// listener.into_incoming().filter_map(Result::ok) /* Ignore failed connections */ /// } /// /// fn main() -> std::io::Result<()> { - /// for stream in listen_on(80) { - /// /* handle the connection here */ - /// } + /// for stream in listen_on(80) { /* handle the connection here */ } /// Ok(()) /// } /// ``` diff --git a/library/std/src/net/udp.rs b/library/std/src/net/udp.rs index 864e1b0f3450a..efbaf8fe6b57d 100644 --- a/library/std/src/net/udp.rs +++ b/library/std/src/net/udp.rs @@ -84,10 +84,8 @@ impl UdpSocket { /// ```no_run /// use std::net::{SocketAddr, UdpSocket}; /// - /// let addrs = [ - /// SocketAddr::from(([127, 0, 0, 1], 3400)), - /// SocketAddr::from(([127, 0, 0, 1], 3401)), - /// ]; + /// let addrs = + /// [SocketAddr::from(([127, 0, 0, 1], 3400)), SocketAddr::from(([127, 0, 0, 1], 3401))]; /// let socket = UdpSocket::bind(&addrs[..]).expect("couldn't bind to address"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -109,8 +107,7 @@ impl UdpSocket { /// /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address"); /// let mut buf = [0; 10]; - /// let (number_of_bytes, src_addr) = socket.recv_from(&mut buf) - /// .expect("Didn't receive data"); + /// let (number_of_bytes, src_addr) = socket.recv_from(&mut buf).expect("Didn't receive data"); /// let filled_buf = &mut buf[..number_of_bytes]; /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -138,8 +135,7 @@ impl UdpSocket { /// /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address"); /// let mut buf = [0; 10]; - /// let (number_of_bytes, src_addr) = socket.peek_from(&mut buf) - /// .expect("Didn't receive data"); + /// let (number_of_bytes, src_addr) = socket.peek_from(&mut buf).expect("Didn't receive data"); /// let filled_buf = &mut buf[..number_of_bytes]; /// ``` #[stable(feature = "peek", since = "1.18.0")] @@ -190,8 +186,10 @@ impl UdpSocket { /// /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address"); /// socket.connect("192.168.0.1:41203").expect("couldn't connect to address"); - /// assert_eq!(socket.peer_addr().unwrap(), - /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 41203))); + /// assert_eq!( + /// socket.peer_addr().unwrap(), + /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 41203)) + /// ); /// ``` /// /// If the socket isn't connected, it will return a [`NotConnected`] error. @@ -202,8 +200,7 @@ impl UdpSocket { /// use std::net::UdpSocket; /// /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address"); - /// assert_eq!(socket.peer_addr().unwrap_err().kind(), - /// std::io::ErrorKind::NotConnected); + /// assert_eq!(socket.peer_addr().unwrap_err().kind(), std::io::ErrorKind::NotConnected); /// ``` #[stable(feature = "udp_peer_addr", since = "1.40.0")] pub fn peer_addr(&self) -> io::Result { @@ -218,8 +215,10 @@ impl UdpSocket { /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket}; /// /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address"); - /// assert_eq!(socket.local_addr().unwrap(), - /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 34254))); + /// assert_eq!( + /// socket.local_addr().unwrap(), + /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 34254)) + /// ); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn local_addr(&self) -> io::Result { diff --git a/library/std/src/os/fd/raw.rs b/library/std/src/os/fd/raw.rs index f92a05066706d..9152f6fa7ab8f 100644 --- a/library/std/src/os/fd/raw.rs +++ b/library/std/src/os/fd/raw.rs @@ -230,8 +230,7 @@ impl<'a> AsRawFd for io::StderrLock<'a> { /// # use std::os::unix::io::AsRawFd; /// use std::net::UdpSocket; /// use std::sync::Arc; -/// trait MyTrait: AsRawFd { -/// } +/// trait MyTrait: AsRawFd {} /// impl MyTrait for Arc {} /// impl MyTrait for Box {} /// # } diff --git a/library/std/src/os/linux/process.rs b/library/std/src/os/linux/process.rs index 540363c03494e..9f9c251f9a33a 100644 --- a/library/std/src/os/linux/process.rs +++ b/library/std/src/os/linux/process.rs @@ -24,17 +24,12 @@ struct FileDesc; /// Example: /// ```no_run /// #![feature(linux_pidfd)] -/// use std::os::linux::process::{CommandExt, ChildExt}; +/// use std::os::linux::process::{ChildExt, CommandExt}; /// use std::process::Command; /// -/// let mut child = Command::new("echo") -/// .create_pidfd(true) -/// .spawn() -/// .expect("Failed to spawn child"); +/// let mut child = Command::new("echo").create_pidfd(true).spawn().expect("Failed to spawn child"); /// -/// let pidfd = child -/// .take_pidfd() -/// .expect("Failed to retrieve pidfd"); +/// let pidfd = child.take_pidfd().expect("Failed to retrieve pidfd"); /// /// // The file descriptor will be closed when `pidfd` is dropped. /// ``` diff --git a/library/std/src/os/net/tcp.rs b/library/std/src/os/net/tcp.rs index 5e9ee65a4152e..361addd1e8eca 100644 --- a/library/std/src/os/net/tcp.rs +++ b/library/std/src/os/net/tcp.rs @@ -28,8 +28,7 @@ pub trait TcpStreamExt: Sealed { /// use std::net::TcpStream; /// use std::os::linux::net::TcpStreamExt; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_quickack(true).expect("set_quickack call failed"); /// ``` #[unstable(feature = "tcp_quickack", issue = "96256")] @@ -46,8 +45,7 @@ pub trait TcpStreamExt: Sealed { /// use std::net::TcpStream; /// use std::os::linux::net::TcpStreamExt; /// - /// let stream = TcpStream::connect("127.0.0.1:8080") - /// .expect("Couldn't connect to the server..."); + /// let stream = TcpStream::connect("127.0.0.1:8080").expect("Couldn't connect to the server..."); /// stream.set_quickack(true).expect("set_quickack call failed"); /// assert_eq!(stream.quickack().unwrap_or(false), true); /// ``` diff --git a/library/std/src/os/unix/fs.rs b/library/std/src/os/unix/fs.rs index 3fc6cc44ce4c8..77fafdb57396e 100644 --- a/library/std/src/os/unix/fs.rs +++ b/library/std/src/os/unix/fs.rs @@ -37,8 +37,8 @@ pub trait FileExt { /// # Examples /// /// ```no_run - /// use std::io; /// use std::fs::File; + /// use std::io; /// use std::os::unix::prelude::FileExt; /// /// fn main() -> io::Result<()> { @@ -85,8 +85,8 @@ pub trait FileExt { /// # Examples /// /// ```no_run - /// use std::io; /// use std::fs::File; + /// use std::io; /// use std::os::unix::prelude::FileExt; /// /// fn main() -> io::Result<()> { @@ -376,8 +376,8 @@ pub trait MetadataExt { /// # Examples /// /// ```no_run - /// use std::io; /// use std::fs; + /// use std::io; /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { @@ -394,8 +394,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -411,16 +411,16 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; /// let mode = meta.mode(); - /// let user_has_write_access = mode & 0o200; + /// let user_has_write_access = mode & 0o200; /// let user_has_read_write_access = mode & 0o600; - /// let group_has_read_access = mode & 0o040; - /// let others_have_exec_access = mode & 0o001; + /// let group_has_read_access = mode & 0o040; + /// let others_have_exec_access = mode & 0o001; /// Ok(()) /// } /// ``` @@ -432,8 +432,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -449,8 +449,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -466,8 +466,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -483,8 +483,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -500,8 +500,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -517,8 +517,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -536,8 +536,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -553,8 +553,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -572,8 +572,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -589,8 +589,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -608,8 +608,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -625,8 +625,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -644,8 +644,8 @@ pub trait MetadataExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::MetadataExt; /// use std::io; + /// use std::os::unix::fs::MetadataExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("some_file")?; @@ -728,8 +728,8 @@ pub trait FileTypeExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::FileTypeExt; /// use std::io; + /// use std::os::unix::fs::FileTypeExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("block_device_file")?; @@ -746,8 +746,8 @@ pub trait FileTypeExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::FileTypeExt; /// use std::io; + /// use std::os::unix::fs::FileTypeExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("char_device_file")?; @@ -764,8 +764,8 @@ pub trait FileTypeExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::FileTypeExt; /// use std::io; + /// use std::os::unix::fs::FileTypeExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("fifo_file")?; @@ -782,8 +782,8 @@ pub trait FileTypeExt { /// /// ```no_run /// use std::fs; - /// use std::os::unix::fs::FileTypeExt; /// use std::io; + /// use std::os::unix::fs::FileTypeExt; /// /// fn main() -> io::Result<()> { /// let meta = fs::metadata("unix.socket")?; diff --git a/library/std/src/os/unix/net/addr.rs b/library/std/src/os/unix/net/addr.rs index 094085e19428c..1af72c2363d2b 100644 --- a/library/std/src/os/unix/net/addr.rs +++ b/library/std/src/os/unix/net/addr.rs @@ -75,7 +75,7 @@ enum AddressKind<'a> { /// Ok(sock) => sock, /// Err(e) => { /// println!("Couldn't bind: {e:?}"); -/// return +/// return; /// } /// }; /// let addr = socket.local_addr().expect("Couldn't get local address"); @@ -231,7 +231,7 @@ impl SocketAddr { /// /// ```no_run /// #![feature(unix_socket_abstract)] - /// use std::os::unix::net::{UnixListener, SocketAddr}; + /// use std::os::unix::net::{SocketAddr, UnixListener}; /// /// fn main() -> std::io::Result<()> { /// let namespace = b"hidden"; @@ -286,7 +286,7 @@ impl SocketAddr { /// /// ```no_run /// #![feature(unix_socket_abstract)] - /// use std::os::unix::net::{UnixListener, SocketAddr}; + /// use std::os::unix::net::{SocketAddr, UnixListener}; /// /// fn main() -> std::io::Result<()> { /// let addr = SocketAddr::from_abstract_namespace(b"hidden")?; diff --git a/library/std/src/os/unix/net/ancillary.rs b/library/std/src/os/unix/net/ancillary.rs index 7cc901a79445b..329c837302bde 100644 --- a/library/std/src/os/unix/net/ancillary.rs +++ b/library/std/src/os/unix/net/ancillary.rs @@ -456,8 +456,8 @@ impl<'a> Iterator for Messages<'a> { /// # Example /// ```no_run /// #![feature(unix_socket_ancillary_data)] -/// use std::os::unix::net::{UnixStream, SocketAncillary, AncillaryData}; /// use std::io::IoSliceMut; +/// use std::os::unix::net::{AncillaryData, SocketAncillary, UnixStream}; /// /// fn main() -> std::io::Result<()> { /// let sock = UnixStream::connect("/tmp/sock")?; @@ -538,8 +538,8 @@ impl<'a> SocketAncillary<'a> { /// /// ```no_run /// #![feature(unix_socket_ancillary_data)] - /// use std::os::unix::net::{UnixStream, SocketAncillary}; /// use std::io::IoSliceMut; + /// use std::os::unix::net::{SocketAncillary, UnixStream}; /// /// fn main() -> std::io::Result<()> { /// let sock = UnixStream::connect("/tmp/sock")?; @@ -572,9 +572,9 @@ impl<'a> SocketAncillary<'a> { /// /// ```no_run /// #![feature(unix_socket_ancillary_data)] - /// use std::os::unix::net::{UnixStream, SocketAncillary}; - /// use std::os::unix::io::AsRawFd; /// use std::io::IoSlice; + /// use std::os::unix::io::AsRawFd; + /// use std::os::unix::net::{SocketAncillary, UnixStream}; /// /// fn main() -> std::io::Result<()> { /// let sock = UnixStream::connect("/tmp/sock")?; @@ -607,7 +607,6 @@ impl<'a> SocketAncillary<'a> { /// If there was not enough space then no credentials was appended. /// Technically, that means this operation adds a control message with the level `SOL_SOCKET` /// and type `SCM_CREDENTIALS` or `SCM_CREDS`. - /// #[cfg(any(doc, target_os = "android", target_os = "linux", target_os = "netbsd",))] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn add_creds(&mut self, creds: &[SocketCred]) -> bool { @@ -630,8 +629,8 @@ impl<'a> SocketAncillary<'a> { /// /// ```no_run /// #![feature(unix_socket_ancillary_data)] - /// use std::os::unix::net::{UnixStream, SocketAncillary, AncillaryData}; /// use std::io::IoSliceMut; + /// use std::os::unix::net::{AncillaryData, SocketAncillary, UnixStream}; /// /// fn main() -> std::io::Result<()> { /// let sock = UnixStream::connect("/tmp/sock")?; diff --git a/library/std/src/os/unix/net/datagram.rs b/library/std/src/os/unix/net/datagram.rs index f758f88d0a370..c3e6b45440488 100644 --- a/library/std/src/os/unix/net/datagram.rs +++ b/library/std/src/os/unix/net/datagram.rs @@ -79,7 +79,7 @@ impl UnixDatagram { /// Ok(sock) => sock, /// Err(e) => { /// println!("Couldn't bind: {e:?}"); - /// return + /// return; /// } /// }; /// ``` @@ -101,7 +101,7 @@ impl UnixDatagram { /// /// ```no_run /// #![feature(unix_socket_abstract)] - /// use std::os::unix::net::{UnixDatagram}; + /// use std::os::unix::net::UnixDatagram; /// /// fn main() -> std::io::Result<()> { /// let sock1 = UnixDatagram::bind("path/to/socket")?; @@ -141,7 +141,7 @@ impl UnixDatagram { /// Ok(sock) => sock, /// Err(e) => { /// println!("Couldn't unbound: {e:?}"); - /// return + /// return; /// } /// }; /// ``` @@ -164,7 +164,7 @@ impl UnixDatagram { /// Ok((sock1, sock2)) => (sock1, sock2), /// Err(e) => { /// println!("Couldn't unbound: {e:?}"); - /// return + /// return; /// } /// }; /// ``` @@ -194,7 +194,7 @@ impl UnixDatagram { /// Ok(sock) => sock, /// Err(e) => { /// println!("Couldn't connect: {e:?}"); - /// return Err(e) + /// return Err(e); /// } /// }; /// Ok(()) @@ -216,7 +216,7 @@ impl UnixDatagram { /// /// ```no_run /// #![feature(unix_socket_abstract)] - /// use std::os::unix::net::{UnixDatagram}; + /// use std::os::unix::net::UnixDatagram; /// /// fn main() -> std::io::Result<()> { /// let bound = UnixDatagram::bind("/path/to/socket")?; @@ -227,7 +227,7 @@ impl UnixDatagram { /// Ok(sock) => sock, /// Err(e) => { /// println!("Couldn't connect: {e:?}"); - /// return Err(e) + /// return Err(e); /// } /// }; /// Ok(()) @@ -385,7 +385,6 @@ impl UnixDatagram { /// On success, returns the number of bytes read, if the data was truncated and the address from whence the msg came. /// /// # Examples - /// #[cfg_attr(any(target_os = "android", target_os = "linux"), doc = "```no_run")] #[cfg_attr(not(any(target_os = "android", target_os = "linux")), doc = "```ignore")] /// #![feature(unix_socket_ancillary_data)] @@ -435,7 +434,6 @@ impl UnixDatagram { /// On success, returns the number of bytes read and if the data was truncated. /// /// # Examples - /// #[cfg_attr(any(target_os = "android", target_os = "linux"), doc = "```no_run")] #[cfg_attr(not(any(target_os = "android", target_os = "linux")), doc = "```ignore")] /// #![feature(unix_socket_ancillary_data)] @@ -522,7 +520,7 @@ impl UnixDatagram { /// /// ```no_run /// #![feature(unix_socket_abstract)] - /// use std::os::unix::net::{UnixDatagram}; + /// use std::os::unix::net::UnixDatagram; /// /// fn main() -> std::io::Result<()> { /// let bound = UnixDatagram::bind("/path/to/socket")?; @@ -577,7 +575,6 @@ impl UnixDatagram { /// On success, returns the number of bytes written. /// /// # Examples - /// #[cfg_attr(any(target_os = "android", target_os = "linux"), doc = "```no_run")] #[cfg_attr(not(any(target_os = "android", target_os = "linux")), doc = "```ignore")] /// #![feature(unix_socket_ancillary_data)] @@ -619,7 +616,6 @@ impl UnixDatagram { /// On success, returns the number of bytes written. /// /// # Examples - /// #[cfg_attr(any(target_os = "android", target_os = "linux"), doc = "```no_run")] #[cfg_attr(not(any(target_os = "android", target_os = "linux")), doc = "```ignore")] /// #![feature(unix_socket_ancillary_data)] @@ -672,8 +668,7 @@ impl UnixDatagram { /// /// fn main() -> std::io::Result<()> { /// let sock = UnixDatagram::unbound()?; - /// sock.set_read_timeout(Some(Duration::new(1, 0))) - /// .expect("set_read_timeout function failed"); + /// sock.set_read_timeout(Some(Duration::new(1, 0))).expect("set_read_timeout function failed"); /// Ok(()) /// } /// ``` @@ -753,8 +748,7 @@ impl UnixDatagram { /// /// fn main() -> std::io::Result<()> { /// let sock = UnixDatagram::unbound()?; - /// sock.set_read_timeout(Some(Duration::new(1, 0))) - /// .expect("set_read_timeout function failed"); + /// sock.set_read_timeout(Some(Duration::new(1, 0))).expect("set_read_timeout function failed"); /// assert_eq!(sock.read_timeout()?, Some(Duration::new(1, 0))); /// Ok(()) /// } @@ -808,7 +802,6 @@ impl UnixDatagram { /// Set the socket option `SO_PASSCRED`. /// /// # Examples - /// #[cfg_attr(any(target_os = "android", target_os = "linux"), doc = "```no_run")] #[cfg_attr(not(any(target_os = "android", target_os = "linux")), doc = "```ignore")] /// #![feature(unix_socket_ancillary_data)] @@ -839,7 +832,6 @@ impl UnixDatagram { } /// Set the id of the socket for network filtering purpose - /// #[cfg_attr( any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"), doc = "```no_run" @@ -890,8 +882,8 @@ impl UnixDatagram { /// (see the documentation of [`Shutdown`]). /// /// ```no_run - /// use std::os::unix::net::UnixDatagram; /// use std::net::Shutdown; + /// use std::os::unix::net::UnixDatagram; /// /// fn main() -> std::io::Result<()> { /// let sock = UnixDatagram::unbound()?; diff --git a/library/std/src/os/unix/net/listener.rs b/library/std/src/os/unix/net/listener.rs index 02090afc82f7e..407c0dce06dc2 100644 --- a/library/std/src/os/unix/net/listener.rs +++ b/library/std/src/os/unix/net/listener.rs @@ -11,8 +11,8 @@ use crate::{fmt, io, mem}; /// # Examples /// /// ```no_run +/// use std::os::unix::net::{UnixListener, UnixStream}; /// use std::thread; -/// use std::os::unix::net::{UnixStream, UnixListener}; /// /// fn handle_client(stream: UnixStream) { /// // ... @@ -64,7 +64,7 @@ impl UnixListener { /// Ok(sock) => sock, /// Err(e) => { /// println!("Couldn't connect: {e:?}"); - /// return + /// return; /// } /// }; /// ``` @@ -91,7 +91,7 @@ impl UnixListener { /// /// ```no_run /// #![feature(unix_socket_abstract)] - /// use std::os::unix::net::{UnixListener}; + /// use std::os::unix::net::UnixListener; /// /// fn main() -> std::io::Result<()> { /// let listener1 = UnixListener::bind("path/to/socket")?; @@ -253,8 +253,8 @@ impl UnixListener { /// # Examples /// /// ```no_run + /// use std::os::unix::net::{UnixListener, UnixStream}; /// use std::thread; - /// use std::os::unix::net::{UnixStream, UnixListener}; /// /// fn handle_client(stream: UnixStream) { /// // ... @@ -347,8 +347,8 @@ impl<'a> IntoIterator for &'a UnixListener { /// # Examples /// /// ```no_run +/// use std::os::unix::net::{UnixListener, UnixStream}; /// use std::thread; -/// use std::os::unix::net::{UnixStream, UnixListener}; /// /// fn handle_client(stream: UnixStream) { /// // ... diff --git a/library/std/src/os/unix/net/stream.rs b/library/std/src/os/unix/net/stream.rs index dff8f6e856750..56950accb05f9 100644 --- a/library/std/src/os/unix/net/stream.rs +++ b/library/std/src/os/unix/net/stream.rs @@ -42,8 +42,8 @@ pub use ucred::UCred; /// # Examples /// /// ```no_run -/// use std::os::unix::net::UnixStream; /// use std::io::prelude::*; +/// use std::os::unix::net::UnixStream; /// /// fn main() -> std::io::Result<()> { /// let mut stream = UnixStream::connect("/path/to/my/socket")?; @@ -84,7 +84,7 @@ impl UnixStream { /// Ok(sock) => sock, /// Err(e) => { /// println!("Couldn't connect: {e:?}"); - /// return + /// return; /// } /// }; /// ``` @@ -117,7 +117,7 @@ impl UnixStream { /// Ok(sock) => sock, /// Err(e) => { /// println!("Couldn't connect: {e:?}"); - /// return Err(e) + /// return Err(e); /// } /// }; /// Ok(()) @@ -149,7 +149,7 @@ impl UnixStream { /// Ok((sock1, sock2)) => (sock1, sock2), /// Err(e) => { /// println!("Couldn't create a pair of sockets: {e:?}"); - /// return + /// return; /// } /// }; /// ``` @@ -306,8 +306,7 @@ impl UnixStream { /// /// fn main() -> std::io::Result<()> { /// let socket = UnixStream::connect("/tmp/sock")?; - /// socket.set_write_timeout(Some(Duration::new(1, 0))) - /// .expect("Couldn't set write timeout"); + /// socket.set_write_timeout(Some(Duration::new(1, 0))).expect("Couldn't set write timeout"); /// Ok(()) /// } /// ``` @@ -363,8 +362,7 @@ impl UnixStream { /// /// fn main() -> std::io::Result<()> { /// let socket = UnixStream::connect("/tmp/sock")?; - /// socket.set_write_timeout(Some(Duration::new(1, 0))) - /// .expect("Couldn't set write timeout"); + /// socket.set_write_timeout(Some(Duration::new(1, 0))).expect("Couldn't set write timeout"); /// assert_eq!(socket.write_timeout()?, Some(Duration::new(1, 0))); /// Ok(()) /// } @@ -397,7 +395,6 @@ impl UnixStream { /// Set the socket option `SO_PASSCRED`. /// /// # Examples - /// #[cfg_attr(any(target_os = "android", target_os = "linux"), doc = "```no_run")] #[cfg_attr(not(any(target_os = "android", target_os = "linux")), doc = "```ignore")] /// #![feature(unix_socket_ancillary_data)] @@ -428,7 +425,6 @@ impl UnixStream { } /// Set the id of the socket for network filtering purpose - /// #[cfg_attr( any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"), doc = "```no_run" @@ -484,8 +480,8 @@ impl UnixStream { /// # Examples /// /// ```no_run - /// use std::os::unix::net::UnixStream; /// use std::net::Shutdown; + /// use std::os::unix::net::UnixStream; /// /// fn main() -> std::io::Result<()> { /// let socket = UnixStream::connect("/tmp/sock")?; @@ -529,7 +525,6 @@ impl UnixStream { /// On success, returns the number of bytes read. /// /// # Examples - /// #[cfg_attr(any(target_os = "android", target_os = "linux"), doc = "```no_run")] #[cfg_attr(not(any(target_os = "android", target_os = "linux")), doc = "```ignore")] /// #![feature(unix_socket_ancillary_data)] @@ -578,7 +573,6 @@ impl UnixStream { /// On success, returns the number of bytes written. /// /// # Examples - /// #[cfg_attr(any(target_os = "android", target_os = "linux"), doc = "```no_run")] #[cfg_attr(not(any(target_os = "android", target_os = "linux")), doc = "```ignore")] /// #![feature(unix_socket_ancillary_data)] diff --git a/library/std/src/os/unix/process.rs b/library/std/src/os/unix/process.rs index 09b2bfe39f094..e060d5fc544dc 100644 --- a/library/std/src/os/unix/process.rs +++ b/library/std/src/os/unix/process.rs @@ -166,14 +166,10 @@ pub trait CommandExt: Sealed { /// A process group ID of 0 will use the process ID as the PGID. /// /// ```no_run - /// use std::process::Command; /// use std::os::unix::process::CommandExt; + /// use std::process::Command; /// - /// Command::new("sleep") - /// .arg("10") - /// .process_group(0) - /// .spawn()? - /// .wait()?; + /// Command::new("sleep").arg("10").process_group(0).spawn()?.wait()?; /// # /// # Ok::<_, Box>(()) /// ``` diff --git a/library/std/src/os/windows/fs.rs b/library/std/src/os/windows/fs.rs index a091f06dd532c..b38e797b30367 100644 --- a/library/std/src/os/windows/fs.rs +++ b/library/std/src/os/windows/fs.rs @@ -32,8 +32,8 @@ pub trait FileExt { /// # Examples /// /// ```no_run - /// use std::io; /// use std::fs::File; + /// use std::io; /// use std::os::windows::prelude::*; /// /// fn main() -> io::Result<()> { @@ -138,10 +138,7 @@ pub trait OpenOptionsExt { /// /// // Do not allow others to read or modify this file while we have it open /// // for writing. - /// let file = OpenOptions::new() - /// .write(true) - /// .share_mode(0) - /// .open("foo.txt"); + /// let file = OpenOptions::new().write(true).share_mode(0).open("foo.txt"); /// ``` /// /// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea @@ -249,10 +246,8 @@ pub trait OpenOptionsExt { /// let file = OpenOptions::new() /// .write(true) /// .create(true) - /// /// // Sets the flag value to `SecurityIdentification`. /// .security_qos_flags(winapi::SECURITY_IDENTIFICATION) - /// /// .open(r"\\.\pipe\MyPipe"); /// ``` /// @@ -310,8 +305,8 @@ pub trait MetadataExt { /// # Examples /// /// ```no_run - /// use std::io; /// use std::fs; + /// use std::io; /// use std::os::windows::prelude::*; /// /// fn main() -> io::Result<()> { @@ -340,8 +335,8 @@ pub trait MetadataExt { /// # Examples /// /// ```no_run - /// use std::io; /// use std::fs; + /// use std::io; /// use std::os::windows::prelude::*; /// /// fn main() -> io::Result<()> { @@ -375,8 +370,8 @@ pub trait MetadataExt { /// # Examples /// /// ```no_run - /// use std::io; /// use std::fs; + /// use std::io; /// use std::os::windows::prelude::*; /// /// fn main() -> io::Result<()> { @@ -408,8 +403,8 @@ pub trait MetadataExt { /// # Examples /// /// ```no_run - /// use std::io; /// use std::fs; + /// use std::io; /// use std::os::windows::prelude::*; /// /// fn main() -> io::Result<()> { @@ -431,8 +426,8 @@ pub trait MetadataExt { /// # Examples /// /// ```no_run - /// use std::io; /// use std::fs; + /// use std::io; /// use std::os::windows::prelude::*; /// /// fn main() -> io::Result<()> { diff --git a/library/std/src/path.rs b/library/std/src/path.rs index 9d63281627d66..d3a600fcc276d 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -28,8 +28,8 @@ //! slice and start asking questions: //! //! ``` -//! use std::path::Path; //! use std::ffi::OsStr; +//! use std::path::Path; //! //! let path = Path::new("/tmp/foo/bar.txt"); //! @@ -113,9 +113,9 @@ use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR} /// # Examples /// /// ``` -/// use std::path::{Component, Path, Prefix}; -/// use std::path::Prefix::*; /// use std::ffi::OsStr; +/// use std::path::Prefix::*; +/// use std::path::{Component, Path, Prefix}; /// /// fn get_path_prefix(s: &str) -> Prefix { /// let path = Path::new(s); @@ -126,15 +126,14 @@ use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR} /// } /// /// # if cfg!(windows) { -/// assert_eq!(Verbatim(OsStr::new("pictures")), -/// get_path_prefix(r"\\?\pictures\kittens")); -/// assert_eq!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")), -/// get_path_prefix(r"\\?\UNC\server\share")); +/// assert_eq!(Verbatim(OsStr::new("pictures")), get_path_prefix(r"\\?\pictures\kittens")); +/// assert_eq!( +/// VerbatimUNC(OsStr::new("server"), OsStr::new("share")), +/// get_path_prefix(r"\\?\UNC\server\share") +/// ); /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\")); -/// assert_eq!(DeviceNS(OsStr::new("BrainInterface")), -/// get_path_prefix(r"\\.\BrainInterface")); -/// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")), -/// get_path_prefix(r"\\server\share")); +/// assert_eq!(DeviceNS(OsStr::new("BrainInterface")), get_path_prefix(r"\\.\BrainInterface")); +/// assert_eq!(UNC(OsStr::new("server"), OsStr::new("share")), get_path_prefix(r"\\server\share")); /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris")); /// # } /// ``` @@ -212,8 +211,8 @@ impl<'a> Prefix<'a> { /// # Examples /// /// ``` - /// use std::path::Prefix::*; /// use std::ffi::OsStr; + /// use std::path::Prefix::*; /// /// assert!(Verbatim(OsStr::new("pictures")).is_verbatim()); /// assert!(VerbatimUNC(OsStr::new("server"), OsStr::new("share")).is_verbatim()); @@ -401,8 +400,8 @@ enum State { /// /// ``` /// # if cfg!(windows) { -/// use std::path::{Component, Path, Prefix}; /// use std::ffi::OsStr; +/// use std::path::{Component, Path, Prefix}; /// /// let path = Path::new(r"c:\you\later\"); /// match path.components().next().unwrap() { @@ -495,12 +494,15 @@ impl Hash for PrefixComponent<'_> { /// /// let path = Path::new("/tmp/foo/bar.txt"); /// let components = path.components().collect::>(); -/// assert_eq!(&components, &[ -/// Component::RootDir, -/// Component::Normal("tmp".as_ref()), -/// Component::Normal("foo".as_ref()), -/// Component::Normal("bar.txt".as_ref()), -/// ]); +/// assert_eq!( +/// &components, +/// &[ +/// Component::RootDir, +/// Component::Normal("tmp".as_ref()), +/// Component::Normal("foo".as_ref()), +/// Component::Normal("bar.txt".as_ref()), +/// ] +/// ); /// ``` #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[stable(feature = "rust1", since = "1.0.0")] @@ -1901,8 +1903,8 @@ impl AsRef for PathBuf { /// # Examples /// /// ``` -/// use std::path::Path; /// use std::ffi::OsStr; +/// use std::path::Path; /// /// // Note: this example does work on Windows /// let path = Path::new("./foo/bar.txt"); @@ -2215,8 +2217,8 @@ impl Path { /// # Examples /// /// ``` - /// use std::path::Path; /// use std::ffi::OsStr; + /// use std::path::Path; /// /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name()); /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name()); @@ -2362,7 +2364,6 @@ impl Path { /// before the *first* `.` /// /// [`Path::file_prefix`]: Path::file_prefix - /// #[stable(feature = "rust1", since = "1.0.0")] #[must_use] pub fn file_stem(&self) -> Option<&OsStr> { @@ -2396,7 +2397,6 @@ impl Path { /// before the *last* `.` /// /// [`Path::file_stem`]: Path::file_stem - /// #[unstable(feature = "path_file_prefix", issue = "86319")] #[must_use] pub fn file_prefix(&self) -> Option<&OsStr> { @@ -2527,8 +2527,8 @@ impl Path { /// # Examples /// /// ``` - /// use std::path::{Path, Component}; /// use std::ffi::OsStr; + /// use std::path::{Component, Path}; /// /// let mut components = Path::new("/tmp/foo.txt").components(); /// @@ -2563,8 +2563,8 @@ impl Path { /// # Examples /// /// ``` - /// use std::path::{self, Path}; /// use std::ffi::OsStr; + /// use std::path::{self, Path}; /// /// let mut it = Path::new("/tmp/foo.txt").iter(); /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string()))); @@ -2753,7 +2753,11 @@ impl Path { /// /// ```no_run /// use std::path::Path; - /// assert!(!Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt")); + /// assert!( + /// !Path::new("does_not_exist.txt") + /// .try_exists() + /// .expect("Can't check existence of file does_not_exist.txt") + /// ); /// assert!(Path::new("/root/secret_file.txt").try_exists().is_err()); /// ``` /// @@ -2833,7 +2837,6 @@ impl Path { /// permission error, this will return false. /// /// # Examples - /// #[cfg_attr(unix, doc = "```no_run")] #[cfg_attr(not(unix), doc = "```ignore")] /// use std::path::Path; @@ -3203,16 +3206,16 @@ impl Error for StripPrefixError { /// #![feature(absolute_path)] /// # #[cfg(unix)] /// fn main() -> std::io::Result<()> { -/// use std::path::{self, Path}; +/// use std::path::{self, Path}; /// -/// // Relative to absolute -/// let absolute = path::absolute("foo/./bar")?; -/// assert!(absolute.ends_with("foo/bar")); +/// // Relative to absolute +/// let absolute = path::absolute("foo/./bar")?; +/// assert!(absolute.ends_with("foo/bar")); /// -/// // Absolute to absolute -/// let absolute = path::absolute("/foo//test/.././bar.rs")?; -/// assert_eq!(absolute, Path::new("/foo/test/../bar.rs")); -/// Ok(()) +/// // Absolute to absolute +/// let absolute = path::absolute("/foo//test/.././bar.rs")?; +/// assert_eq!(absolute, Path::new("/foo/test/../bar.rs")); +/// Ok(()) /// } /// # #[cfg(not(unix))] /// # fn main() {} @@ -3228,17 +3231,17 @@ impl Error for StripPrefixError { /// #![feature(absolute_path)] /// # #[cfg(windows)] /// fn main() -> std::io::Result<()> { -/// use std::path::{self, Path}; +/// use std::path::{self, Path}; /// -/// // Relative to absolute -/// let absolute = path::absolute("foo/./bar")?; -/// assert!(absolute.ends_with(r"foo\bar")); +/// // Relative to absolute +/// let absolute = path::absolute("foo/./bar")?; +/// assert!(absolute.ends_with(r"foo\bar")); /// -/// // Absolute to absolute -/// let absolute = path::absolute(r"C:\foo//test\..\./bar.rs")?; +/// // Absolute to absolute +/// let absolute = path::absolute(r"C:\foo//test\..\./bar.rs")?; /// -/// assert_eq!(absolute, Path::new(r"C:\foo\bar.rs")); -/// Ok(()) +/// assert_eq!(absolute, Path::new(r"C:\foo\bar.rs")); +/// Ok(()) /// } /// # #[cfg(not(windows))] /// # fn main() {} diff --git a/library/std/src/primitive_docs.rs b/library/std/src/primitive_docs.rs index 331714a993c60..ea7b739aefcb4 100644 --- a/library/std/src/primitive_docs.rs +++ b/library/std/src/primitive_docs.rs @@ -78,9 +78,7 @@ mod prim_bool {} /// ``` /// #![feature(never_type)] /// # fn foo() -> u32 { -/// let x: ! = { -/// return 123 -/// }; +/// let x: ! = { return 123 }; /// # } /// ``` /// @@ -215,11 +213,7 @@ mod prim_bool {} /// use std::ops::Add; /// /// fn foo() -> impl Add { -/// if true { -/// unimplemented!() -/// } else { -/// 0 -/// } +/// if true { unimplemented!() } else { 0 } /// } /// ``` /// @@ -266,11 +260,9 @@ mod prim_bool {} /// Since `!` has no values, it has no default value either. It's true that we could write an /// `impl` for this which simply panics, but the same is true for any type (we could `impl /// Default` for (eg.) [`File`] by just making [`default()`] panic.) -/// #[doc = concat!("[`File`]: ", include_str!("../primitive_docs/fs_file.md"))] /// [`Debug`]: fmt::Debug /// [`default()`]: Default::default -/// #[unstable(feature = "never_type", issue = "35121")] mod prim_never {} @@ -322,8 +314,8 @@ mod prim_never {} /// ``` /// let c: char = 'a'; /// match c { -/// '\0' ..= '\u{D7FF}' => false, -/// '\u{E000}' ..= '\u{10FFFF}' => true, +/// '\0'..='\u{D7FF}' => false, +/// '\u{E000}'..='\u{10FFFF}' => true, /// }; /// ``` /// @@ -354,7 +346,6 @@ mod prim_never {} /// // five elements times one byte per element /// assert_eq!(5, s.len() * std::mem::size_of::()); /// ``` -/// #[doc = concat!("[`String`]: ", include_str!("../primitive_docs/string_string.md"))] /// /// As always, remember that a human intuition for 'character' might not map to @@ -428,14 +419,11 @@ mod prim_char {} /// 1i64; /// } /// -/// let is_i64 = { -/// returns_i64() -/// }; +/// let is_i64 = { returns_i64() }; /// let is_unit = { /// returns_i64(); /// }; /// ``` -/// #[stable(feature = "rust1", since = "1.0.0")] mod prim_unit {} @@ -649,7 +637,7 @@ mod prim_pointer {} /// ``` /// let array: [i32; 3] = [0; 3]; /// -/// for x in &array { } +/// for x in &array {} /// ``` /// /// You can use `::try_from(slice)` or `slice.try_into()` to get an array from @@ -664,7 +652,8 @@ mod prim_pointer {} /// You can use a [slice pattern] to move elements out of an array: /// /// ``` -/// fn move_away(_: String) { /* Do interesting things. */ } +/// fn move_away(_: String) { /* Do interesting things. */ +/// } /// /// let [john, roa] = ["John".to_string(), "Roa".to_string()]; /// move_away(john); @@ -979,7 +968,6 @@ mod prim_str {} /// sequentially until the first non-equal set is found. /// /// For more about tuples, see [the book](../book/ch03-02-data-types.html#the-tuple-type). -/// // Hardcoded anchor in src/librustdoc/html/format.rs // linked to as `#trait-implementations-1` /// # Trait implementations @@ -1050,7 +1038,6 @@ mod prim_str {} /// assert_eq!(x, 4); /// assert_eq!(y, 5); /// ``` -/// #[stable(feature = "rust1", since = "1.0.0")] mod prim_tuple {} @@ -1486,7 +1473,7 @@ mod prim_ref {} /// You cast function pointers directly to integers: /// /// ```rust -/// let fnptr: fn(i32) -> i32 = |x| x+2; +/// let fnptr: fn(i32) -> i32 = |x| x + 2; /// let fnptr_addr = fnptr as usize; /// ``` /// diff --git a/library/std/src/process.rs b/library/std/src/process.rs index 400d25beb26f3..f3a6dda22a505 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -11,10 +11,8 @@ //! ```no_run //! use std::process::Command; //! -//! let output = Command::new("echo") -//! .arg("Hello world") -//! .output() -//! .expect("Failed to execute command"); +//! let output = +//! Command::new("echo").arg("Hello world").output().expect("Failed to execute command"); //! //! assert_eq!(b"Hello world\n", output.stdout.as_slice()); //! ``` @@ -62,8 +60,8 @@ //! [`ChildStdin`] implements [`Write`]: //! //! ```no_run -//! use std::process::{Command, Stdio}; //! use std::io::Write; +//! use std::process::{Command, Stdio}; //! //! let mut child = Command::new("/bin/cat") //! .stdin(Stdio::piped()) @@ -81,9 +79,7 @@ //! stdin.write_all(b"test").expect("failed to write to stdin"); //! }); //! -//! let output = child -//! .wait_with_output() -//! .expect("failed to wait on child"); +//! let output = child.wait_with_output().expect("failed to wait on child"); //! //! assert_eq!(b"test", output.stdout.as_slice()); //! ``` @@ -153,13 +149,10 @@ use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; /// ```should_panic /// use std::process::Command; /// -/// let mut child = Command::new("/bin/cat") -/// .arg("file.txt") -/// .spawn() -/// .expect("failed to execute child"); +/// let mut child = +/// Command::new("/bin/cat").arg("file.txt").spawn().expect("failed to execute child"); /// -/// let ecode = child.wait() -/// .expect("failed to wait on child"); +/// let ecode = child.wait().expect("failed to wait on child"); /// /// assert!(ecode.success()); /// ``` @@ -462,16 +455,9 @@ impl fmt::Debug for ChildStderr { /// use std::process::Command; /// /// let output = if cfg!(target_os = "windows") { -/// Command::new("cmd") -/// .args(["/C", "echo hello"]) -/// .output() -/// .expect("failed to execute process") +/// Command::new("cmd").args(["/C", "echo hello"]).output().expect("failed to execute process") /// } else { -/// Command::new("sh") -/// .arg("-c") -/// .arg("echo hello") -/// .output() -/// .expect("failed to execute process") +/// Command::new("sh").arg("-c").arg("echo hello").output().expect("failed to execute process") /// }; /// /// let hello = output.stdout; @@ -484,8 +470,7 @@ impl fmt::Debug for ChildStderr { /// use std::process::Command; /// /// let mut echo_hello = Command::new("sh"); -/// echo_hello.arg("-c") -/// .arg("echo hello"); +/// echo_hello.arg("-c").arg("echo hello"); /// let hello_1 = echo_hello.output().expect("failed to execute process"); /// let hello_2 = echo_hello.output().expect("failed to execute process"); /// ``` @@ -549,9 +534,7 @@ impl Command { /// ```no_run /// use std::process::Command; /// - /// Command::new("sh") - /// .spawn() - /// .expect("sh command failed to start"); + /// Command::new("sh").spawn().expect("sh command failed to start"); /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn new>(program: S) -> Command { @@ -593,11 +576,7 @@ impl Command { /// ```no_run /// use std::process::Command; /// - /// Command::new("ls") - /// .arg("-l") - /// .arg("-a") - /// .spawn() - /// .expect("ls command failed to start"); + /// Command::new("ls").arg("-l").arg("-a").spawn().expect("ls command failed to start"); /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn arg>(&mut self, arg: S) -> &mut Command { @@ -623,10 +602,7 @@ impl Command { /// ```no_run /// use std::process::Command; /// - /// Command::new("ls") - /// .args(["-l", "-a"]) - /// .spawn() - /// .expect("ls command failed to start"); + /// Command::new("ls").args(["-l", "-a"]).spawn().expect("ls command failed to start"); /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn args(&mut self, args: I) -> &mut Command @@ -652,10 +628,7 @@ impl Command { /// ```no_run /// use std::process::Command; /// - /// Command::new("ls") - /// .env("PATH", "/bin") - /// .spawn() - /// .expect("ls command failed to start"); + /// Command::new("ls").env("PATH", "/bin").spawn().expect("ls command failed to start"); /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn env(&mut self, key: K, val: V) -> &mut Command @@ -674,22 +647,21 @@ impl Command { /// Basic usage: /// /// ```no_run - /// use std::process::{Command, Stdio}; - /// use std::env; /// use std::collections::HashMap; + /// use std::env; + /// use std::process::{Command, Stdio}; /// - /// let filtered_env : HashMap = - /// env::vars().filter(|&(ref k, _)| - /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH" - /// ).collect(); + /// let filtered_env: HashMap = env::vars() + /// .filter(|&(ref k, _)| k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH") + /// .collect(); /// /// Command::new("printenv") - /// .stdin(Stdio::null()) - /// .stdout(Stdio::inherit()) - /// .env_clear() - /// .envs(&filtered_env) - /// .spawn() - /// .expect("printenv failed to start"); + /// .stdin(Stdio::null()) + /// .stdout(Stdio::inherit()) + /// .env_clear() + /// .envs(&filtered_env) + /// .spawn() + /// .expect("printenv failed to start"); /// ``` #[stable(feature = "command_envs", since = "1.19.0")] pub fn envs(&mut self, vars: I) -> &mut Command @@ -713,10 +685,7 @@ impl Command { /// ```no_run /// use std::process::Command; /// - /// Command::new("ls") - /// .env_remove("PATH") - /// .spawn() - /// .expect("ls command failed to start"); + /// Command::new("ls").env_remove("PATH").spawn().expect("ls command failed to start"); /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn env_remove>(&mut self, key: K) -> &mut Command { @@ -733,10 +702,7 @@ impl Command { /// ```no_run /// use std::process::Command; /// - /// Command::new("ls") - /// .env_clear() - /// .spawn() - /// .expect("ls command failed to start"); + /// Command::new("ls").env_clear().spawn().expect("ls command failed to start"); /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn env_clear(&mut self) -> &mut Command { @@ -761,10 +727,7 @@ impl Command { /// ```no_run /// use std::process::Command; /// - /// Command::new("ls") - /// .current_dir("/bin") - /// .spawn() - /// .expect("ls command failed to start"); + /// Command::new("ls").current_dir("/bin").spawn().expect("ls command failed to start"); /// ``` /// /// [`canonicalize`]: crate::fs::canonicalize @@ -792,10 +755,7 @@ impl Command { /// ```no_run /// use std::process::{Command, Stdio}; /// - /// Command::new("ls") - /// .stdin(Stdio::null()) - /// .spawn() - /// .expect("ls command failed to start"); + /// Command::new("ls").stdin(Stdio::null()).spawn().expect("ls command failed to start"); /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn stdin>(&mut self, cfg: T) -> &mut Command { @@ -821,10 +781,7 @@ impl Command { /// ```no_run /// use std::process::{Command, Stdio}; /// - /// Command::new("ls") - /// .stdout(Stdio::null()) - /// .spawn() - /// .expect("ls command failed to start"); + /// Command::new("ls").stdout(Stdio::null()).spawn().expect("ls command failed to start"); /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn stdout>(&mut self, cfg: T) -> &mut Command { @@ -850,10 +807,7 @@ impl Command { /// ```no_run /// use std::process::{Command, Stdio}; /// - /// Command::new("ls") - /// .stderr(Stdio::null()) - /// .spawn() - /// .expect("ls command failed to start"); + /// Command::new("ls").stderr(Stdio::null()).spawn().expect("ls command failed to start"); /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn stderr>(&mut self, cfg: T) -> &mut Command { @@ -872,9 +826,7 @@ impl Command { /// ```no_run /// use std::process::Command; /// - /// Command::new("ls") - /// .spawn() - /// .expect("ls command failed to start"); + /// Command::new("ls").spawn().expect("ls command failed to start"); /// ``` #[stable(feature = "process", since = "1.0.0")] pub fn spawn(&mut self) -> io::Result { @@ -892,12 +844,10 @@ impl Command { /// # Examples /// /// ```should_panic - /// use std::process::Command; /// use std::io::{self, Write}; - /// let output = Command::new("/bin/cat") - /// .arg("file.txt") - /// .output() - /// .expect("failed to execute process"); + /// use std::process::Command; + /// let output = + /// Command::new("/bin/cat").arg("file.txt").output().expect("failed to execute process"); /// /// println!("status: {}", output.status); /// io::stdout().write_all(&output.stdout).unwrap(); @@ -923,10 +873,8 @@ impl Command { /// ```should_panic /// use std::process::Command; /// - /// let status = Command::new("/bin/cat") - /// .arg("file.txt") - /// .status() - /// .expect("failed to execute process"); + /// let status = + /// Command::new("/bin/cat").arg("file.txt").status().expect("failed to execute process"); /// /// println!("process finished with: {status}"); /// @@ -999,10 +947,7 @@ impl Command { /// let mut cmd = Command::new("ls"); /// cmd.env("TERM", "dumb").env_remove("TZ"); /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect(); - /// assert_eq!(envs, &[ - /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))), - /// (OsStr::new("TZ"), None) - /// ]); + /// assert_eq!(envs, &[(OsStr::new("TERM"), Some(OsStr::new("dumb"))), (OsStr::new("TZ"), None)]); /// ``` #[stable(feature = "command_access", since = "1.57.0")] pub fn get_envs(&self) -> CommandEnvs<'_> { @@ -1187,7 +1132,6 @@ impl Stdio { /// This is an issue when running any program that doesn't guarantee that it reads /// its entire stdin before writing more than a pipe buffer's worth of output. /// The size of a pipe buffer varies on different targets. - /// #[must_use] #[stable(feature = "process", since = "1.0.0")] pub fn piped() -> Stdio { @@ -1216,8 +1160,8 @@ impl Stdio { /// With stdin: /// /// ```no_run - /// use std::process::{Command, Stdio}; /// use std::io::{self, Write}; + /// use std::process::{Command, Stdio}; /// /// let output = Command::new("rev") /// .stdin(Stdio::inherit()) @@ -1315,10 +1259,8 @@ impl From for Stdio { /// ```rust,no_run /// use std::process::{Command, Stdio}; /// - /// let reverse = Command::new("rev") - /// .stdin(Stdio::piped()) - /// .spawn() - /// .expect("failed reverse command"); + /// let reverse = + /// Command::new("rev").stdin(Stdio::piped()).spawn().expect("failed reverse command"); /// /// let _echo = Command::new("echo") /// .arg("Hello, world!") @@ -1351,7 +1293,7 @@ impl From for Stdio { /// .expect("failed echo command"); /// /// let reverse = Command::new("rev") - /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here + /// .stdin(hello.stdout.unwrap()) // Converted into a Stdio here /// .output() /// .expect("failed reverse command"); /// @@ -1409,7 +1351,7 @@ impl From for Stdio { /// let file = File::open("foo.txt").unwrap(); /// /// let reverse = Command::new("rev") - /// .stdin(file) // Implicit File conversion into a Stdio + /// .stdin(file) // Implicit File conversion into a Stdio /// .output() /// .expect("failed reverse command"); /// @@ -1467,10 +1409,8 @@ impl ExitStatus { /// # if cfg!(unix) { /// use std::process::Command; /// - /// let status = Command::new("ls") - /// .arg("/dev/nonexistent") - /// .status() - /// .expect("ls could not be executed"); + /// let status = + /// Command::new("ls").arg("/dev/nonexistent").status().expect("ls could not be executed"); /// /// println!("ls: {status}"); /// status.exit_ok().expect_err("/dev/nonexistent could be listed!"); @@ -1489,10 +1429,7 @@ impl ExitStatus { /// ```rust,no_run /// use std::process::Command; /// - /// let status = Command::new("mkdir") - /// .arg("projects") - /// .status() - /// .expect("failed to execute mkdir"); + /// let status = Command::new("mkdir").arg("projects").status().expect("failed to execute mkdir"); /// /// if status.success() { /// println!("'projects/' directory created"); @@ -1522,14 +1459,11 @@ impl ExitStatus { /// ```no_run /// use std::process::Command; /// - /// let status = Command::new("mkdir") - /// .arg("projects") - /// .status() - /// .expect("failed to execute mkdir"); + /// let status = Command::new("mkdir").arg("projects").status().expect("failed to execute mkdir"); /// /// match status.code() { /// Some(code) => println!("Exited with status code: {code}"), - /// None => println!("Process terminated by signal") + /// None => println!("Process terminated by signal"), /// } /// ``` #[must_use] @@ -1573,7 +1507,7 @@ impl crate::sealed::Sealed for ExitStatusError {} /// # if cfg!(unix) { /// use std::process::{Command, ExitStatusError}; /// -/// fn run(cmd: &str) -> Result<(),ExitStatusError> { +/// fn run(cmd: &str) -> Result<(), ExitStatusError> { /// Command::new(cmd).status().unwrap().exit_ok()?; /// Ok(()) /// } @@ -1976,13 +1910,10 @@ impl Child { /// .spawn() /// .expect("failed to execute child"); /// - /// let output = child - /// .wait_with_output() - /// .expect("failed to wait on child"); + /// let output = child.wait_with_output().expect("failed to wait on child"); /// /// assert!(output.status.success()); /// ``` - /// #[stable(feature = "process", since = "1.0.0")] pub fn wait_with_output(mut self) -> io::Result { drop(self.stdin.take()); @@ -2131,7 +2062,6 @@ pub fn abort() -> ! { /// println!("My pid is {}", process::id()); /// ``` /// -/// #[must_use] #[stable(feature = "getpid", since = "1.26.0")] pub fn id() -> u32 { diff --git a/library/std/src/sync/barrier.rs b/library/std/src/sync/barrier.rs index 11836b7b694b3..a31f0eb83648c 100644 --- a/library/std/src/sync/barrier.rs +++ b/library/std/src/sync/barrier.rs @@ -19,7 +19,7 @@ use crate::sync::{Condvar, Mutex}; /// let c = Arc::clone(&barrier); /// // The same messages will be printed together. /// // You will NOT see any interleaving. -/// handles.push(thread::spawn(move|| { +/// handles.push(thread::spawn(move || { /// println!("before wait"); /// c.wait(); /// println!("after wait"); @@ -111,7 +111,7 @@ impl Barrier { /// let c = Arc::clone(&barrier); /// // The same messages will be printed together. /// // You will NOT see any interleaving. - /// handles.push(thread::spawn(move|| { + /// handles.push(thread::spawn(move || { /// println!("before wait"); /// c.wait(); /// println!("after wait"); diff --git a/library/std/src/sync/condvar.rs b/library/std/src/sync/condvar.rs index eb1e7135a6e41..7a924abdffa59 100644 --- a/library/std/src/sync/condvar.rs +++ b/library/std/src/sync/condvar.rs @@ -57,7 +57,7 @@ impl WaitTimeoutResult { /// started = result.0; /// if *started == true { /// // We received the notification and the value has been updated, we can leave. - /// break + /// break; /// } /// } /// ``` @@ -83,14 +83,14 @@ impl WaitTimeoutResult { /// # Examples /// /// ``` -/// use std::sync::{Arc, Mutex, Condvar}; +/// use std::sync::{Arc, Condvar, Mutex}; /// use std::thread; /// /// let pair = Arc::new((Mutex::new(false), Condvar::new())); /// let pair2 = Arc::clone(&pair); /// /// // Inside of our lock, spawn a new thread, and then wait for it to start. -/// thread::spawn(move|| { +/// thread::spawn(move || { /// let (lock, cvar) = &*pair2; /// let mut started = lock.lock().unwrap(); /// *started = true; @@ -162,13 +162,13 @@ impl Condvar { /// # Examples /// /// ``` - /// use std::sync::{Arc, Mutex, Condvar}; + /// use std::sync::{Arc, Condvar, Mutex}; /// use std::thread; /// /// let pair = Arc::new((Mutex::new(false), Condvar::new())); /// let pair2 = Arc::clone(&pair); /// - /// thread::spawn(move|| { + /// thread::spawn(move || { /// let (lock, cvar) = &*pair2; /// let mut started = lock.lock().unwrap(); /// *started = true; @@ -217,13 +217,13 @@ impl Condvar { /// # Examples /// /// ``` - /// use std::sync::{Arc, Mutex, Condvar}; + /// use std::sync::{Arc, Condvar, Mutex}; /// use std::thread; /// /// let pair = Arc::new((Mutex::new(true), Condvar::new())); /// let pair2 = Arc::clone(&pair); /// - /// thread::spawn(move|| { + /// thread::spawn(move || { /// let (lock, cvar) = &*pair2; /// let mut pending = lock.lock().unwrap(); /// *pending = false; @@ -234,7 +234,7 @@ impl Condvar { /// // Wait for the thread to start up. /// let (lock, cvar) = &*pair; /// // As long as the value inside the `Mutex` is `true`, we wait. - /// let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| { *pending }).unwrap(); + /// let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| *pending).unwrap(); /// ``` #[stable(feature = "wait_until", since = "1.42.0")] pub fn wait_while<'a, T, F>( @@ -276,13 +276,13 @@ impl Condvar { /// # Examples /// /// ``` - /// use std::sync::{Arc, Mutex, Condvar}; + /// use std::sync::{Arc, Condvar, Mutex}; /// use std::thread; /// /// let pair = Arc::new((Mutex::new(false), Condvar::new())); /// let pair2 = Arc::clone(&pair); /// - /// thread::spawn(move|| { + /// thread::spawn(move || { /// let (lock, cvar) = &*pair2; /// let mut started = lock.lock().unwrap(); /// *started = true; @@ -300,7 +300,7 @@ impl Condvar { /// started = result.0; /// if *started == true { /// // We received the notification and the value has been updated, we can leave. - /// break + /// break; /// } /// } /// ``` @@ -347,14 +347,14 @@ impl Condvar { /// # Examples /// /// ``` - /// use std::sync::{Arc, Mutex, Condvar}; + /// use std::sync::{Arc, Condvar, Mutex}; /// use std::thread; /// use std::time::Duration; /// /// let pair = Arc::new((Mutex::new(false), Condvar::new())); /// let pair2 = Arc::clone(&pair); /// - /// thread::spawn(move|| { + /// thread::spawn(move || { /// let (lock, cvar) = &*pair2; /// let mut started = lock.lock().unwrap(); /// *started = true; @@ -372,7 +372,7 @@ impl Condvar { /// started = result.0; /// if *started == true { /// // We received the notification and the value has been updated, we can leave. - /// break + /// break; /// } /// } /// ``` @@ -415,14 +415,14 @@ impl Condvar { /// # Examples /// /// ``` - /// use std::sync::{Arc, Mutex, Condvar}; + /// use std::sync::{Arc, Condvar, Mutex}; /// use std::thread; /// use std::time::Duration; /// /// let pair = Arc::new((Mutex::new(true), Condvar::new())); /// let pair2 = Arc::clone(&pair); /// - /// thread::spawn(move|| { + /// thread::spawn(move || { /// let (lock, cvar) = &*pair2; /// let mut pending = lock.lock().unwrap(); /// *pending = false; @@ -432,11 +432,11 @@ impl Condvar { /// /// // wait for the thread to start up /// let (lock, cvar) = &*pair; - /// let result = cvar.wait_timeout_while( - /// lock.lock().unwrap(), - /// Duration::from_millis(100), - /// |&mut pending| pending, - /// ).unwrap(); + /// let result = cvar + /// .wait_timeout_while(lock.lock().unwrap(), Duration::from_millis(100), |&mut pending| { + /// pending + /// }) + /// .unwrap(); /// if result.1.timed_out() { /// // timed-out without the condition ever evaluating to false. /// } @@ -480,13 +480,13 @@ impl Condvar { /// # Examples /// /// ``` - /// use std::sync::{Arc, Mutex, Condvar}; + /// use std::sync::{Arc, Condvar, Mutex}; /// use std::thread; /// /// let pair = Arc::new((Mutex::new(false), Condvar::new())); /// let pair2 = Arc::clone(&pair); /// - /// thread::spawn(move|| { + /// thread::spawn(move || { /// let (lock, cvar) = &*pair2; /// let mut started = lock.lock().unwrap(); /// *started = true; @@ -520,13 +520,13 @@ impl Condvar { /// # Examples /// /// ``` - /// use std::sync::{Arc, Mutex, Condvar}; + /// use std::sync::{Arc, Condvar, Mutex}; /// use std::thread; /// /// let pair = Arc::new((Mutex::new(false), Condvar::new())); /// let pair2 = Arc::clone(&pair); /// - /// thread::spawn(move|| { + /// thread::spawn(move || { /// let (lock, cvar) = &*pair2; /// let mut started = lock.lock().unwrap(); /// *started = true; diff --git a/library/std/src/sync/lazy_lock.rs b/library/std/src/sync/lazy_lock.rs index 535cc1c42fcfd..a2f4111fc9515 100644 --- a/library/std/src/sync/lazy_lock.rs +++ b/library/std/src/sync/lazy_lock.rs @@ -29,7 +29,9 @@ use crate::sync::OnceLock; /// println!("ready"); /// std::thread::spawn(|| { /// println!("{:?}", HASHMAP.get(&13)); -/// }).join().unwrap(); +/// }) +/// .join() +/// .unwrap(); /// println!("{:?}", HASHMAP.get(&74)); /// /// // Prints: diff --git a/library/std/src/sync/mpsc/mod.rs b/library/std/src/sync/mpsc/mod.rs index e85a872396518..a1267c923d1cf 100644 --- a/library/std/src/sync/mpsc/mod.rs +++ b/library/std/src/sync/mpsc/mod.rs @@ -46,12 +46,12 @@ //! Simple usage: //! //! ``` -//! use std::thread; //! use std::sync::mpsc::channel; +//! use std::thread; //! //! // Create a simple streaming channel //! let (tx, rx) = channel(); -//! thread::spawn(move|| { +//! thread::spawn(move || { //! tx.send(10).unwrap(); //! }); //! assert_eq!(rx.recv().unwrap(), 10); @@ -60,8 +60,8 @@ //! Shared usage: //! //! ``` -//! use std::thread; //! use std::sync::mpsc::channel; +//! use std::thread; //! //! // Create a shared channel that can be sent along from many threads //! // where tx is the sending half (tx for transmission), and rx is the receiving @@ -69,7 +69,7 @@ //! let (tx, rx) = channel(); //! for i in 0..10 { //! let tx = tx.clone(); -//! thread::spawn(move|| { +//! thread::spawn(move || { //! tx.send(i).unwrap(); //! }); //! } @@ -95,11 +95,11 @@ //! Synchronous channels: //! //! ``` -//! use std::thread; //! use std::sync::mpsc::sync_channel; +//! use std::thread; //! //! let (tx, rx) = sync_channel::(0); -//! thread::spawn(move|| { +//! thread::spawn(move || { //! // This will wait for the parent thread to start receiving //! tx.send(53).unwrap(); //! }); @@ -698,7 +698,7 @@ impl UnsafeFlavor for Receiver { /// let (sender, receiver) = channel(); /// /// // Spawn off an expensive computation -/// thread::spawn(move|| { +/// thread::spawn(move || { /// # fn expensive_computation() {} /// sender.send(expensive_computation()).unwrap(); /// }); @@ -749,7 +749,7 @@ pub fn channel() -> (Sender, Receiver) { /// // this returns immediately /// sender.send(1).unwrap(); /// -/// thread::spawn(move|| { +/// thread::spawn(move || { /// // this will block until the previous message has been received /// sender.send(2).unwrap(); /// }); @@ -943,11 +943,11 @@ impl SyncSender { /// let (sync_sender, receiver) = sync_channel(0); /// /// thread::spawn(move || { - /// println!("sending message..."); - /// sync_sender.send(1).unwrap(); - /// // Thread is now blocked until the message is received + /// println!("sending message..."); + /// sync_sender.send(1).unwrap(); + /// // Thread is now blocked until the message is received /// - /// println!("...message received!"); + /// println!("...message received!"); /// }); /// /// let msg = receiver.recv().unwrap(); @@ -1061,7 +1061,7 @@ impl Receiver { /// # Examples /// /// ```rust - /// use std::sync::mpsc::{Receiver, channel}; + /// use std::sync::mpsc::{channel, Receiver}; /// /// let (_, receiver): (_, Receiver) = channel(); /// @@ -1135,8 +1135,8 @@ impl Receiver { /// /// ``` /// use std::sync::mpsc; - /// use std::thread; /// use std::sync::mpsc::RecvError; + /// use std::thread; /// /// let (send, recv) = mpsc::channel(); /// let handle = thread::spawn(move || { @@ -1231,9 +1231,9 @@ impl Receiver { /// Successfully receiving value before encountering timeout: /// /// ```no_run + /// use std::sync::mpsc; /// use std::thread; /// use std::time::Duration; - /// use std::sync::mpsc; /// /// let (send, recv) = mpsc::channel(); /// @@ -1241,18 +1241,15 @@ impl Receiver { /// send.send('a').unwrap(); /// }); /// - /// assert_eq!( - /// recv.recv_timeout(Duration::from_millis(400)), - /// Ok('a') - /// ); + /// assert_eq!(recv.recv_timeout(Duration::from_millis(400)), Ok('a')); /// ``` /// /// Receiving an error upon reaching timeout: /// /// ```no_run + /// use std::sync::mpsc; /// use std::thread; /// use std::time::Duration; - /// use std::sync::mpsc; /// /// let (send, recv) = mpsc::channel(); /// @@ -1261,10 +1258,7 @@ impl Receiver { /// send.send('a').unwrap(); /// }); /// - /// assert_eq!( - /// recv.recv_timeout(Duration::from_millis(400)), - /// Err(mpsc::RecvTimeoutError::Timeout) - /// ); + /// assert_eq!(recv.recv_timeout(Duration::from_millis(400)), Err(mpsc::RecvTimeoutError::Timeout)); /// ``` #[stable(feature = "mpsc_recv_timeout", since = "1.12.0")] pub fn recv_timeout(&self, timeout: Duration) -> Result { @@ -1301,9 +1295,9 @@ impl Receiver { /// /// ```no_run /// #![feature(deadline_api)] + /// use std::sync::mpsc; /// use std::thread; /// use std::time::{Duration, Instant}; - /// use std::sync::mpsc; /// /// let (send, recv) = mpsc::channel(); /// @@ -1311,19 +1305,16 @@ impl Receiver { /// send.send('a').unwrap(); /// }); /// - /// assert_eq!( - /// recv.recv_deadline(Instant::now() + Duration::from_millis(400)), - /// Ok('a') - /// ); + /// assert_eq!(recv.recv_deadline(Instant::now() + Duration::from_millis(400)), Ok('a')); /// ``` /// /// Receiving an error upon reaching deadline: /// /// ```no_run /// #![feature(deadline_api)] + /// use std::sync::mpsc; /// use std::thread; /// use std::time::{Duration, Instant}; - /// use std::sync::mpsc; /// /// let (send, recv) = mpsc::channel(); /// diff --git a/library/std/src/sync/mutex.rs b/library/std/src/sync/mutex.rs index de851c8fbbed5..cacbe373fa016 100644 --- a/library/std/src/sync/mutex.rs +++ b/library/std/src/sync/mutex.rs @@ -43,9 +43,9 @@ use crate::sys_common::mutex as sys; /// # Examples /// /// ``` +/// use std::sync::mpsc::channel; /// use std::sync::{Arc, Mutex}; /// use std::thread; -/// use std::sync::mpsc::channel; /// /// const N: usize = 10; /// @@ -95,7 +95,8 @@ use crate::sys_common::mutex as sys; /// // This panic while holding the lock (`_guard` is in scope) will poison /// // the mutex. /// panic!(); -/// }).join(); +/// }) +/// .join(); /// /// // The lock is poisoned by this point, but the returned result can be /// // pattern matched on to return the underlying guard on both branches. @@ -152,11 +153,9 @@ use crate::sys_common::mutex as sys; /// // no deadlock. /// *res_mutex.lock().unwrap() += result; /// -/// threads.into_iter().for_each(|thread| { -/// thread -/// .join() -/// .expect("The thread creating or execution failed !") -/// }); +/// threads +/// .into_iter() +/// .for_each(|thread| thread.join().expect("The thread creating or execution failed !")); /// /// assert_eq!(*res_mutex.lock().unwrap(), 800); /// ``` @@ -258,7 +257,9 @@ impl Mutex { /// /// thread::spawn(move || { /// *c_mutex.lock().unwrap() = 10; - /// }).join().expect("thread::spawn failed"); + /// }) + /// .join() + /// .expect("thread::spawn failed"); /// assert_eq!(*mutex.lock().unwrap(), 10); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -305,7 +306,9 @@ impl Mutex { /// } else { /// println!("try_lock failed"); /// } - /// }).join().expect("thread::spawn failed"); + /// }) + /// .join() + /// .expect("thread::spawn failed"); /// assert_eq!(*mutex.lock().unwrap(), 10); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -357,7 +360,8 @@ impl Mutex { /// let _ = thread::spawn(move || { /// let _lock = c_mutex.lock().unwrap(); /// panic!(); // the mutex gets poisoned - /// }).join(); + /// }) + /// .join(); /// assert_eq!(mutex.is_poisoned(), true); /// ``` #[inline] @@ -388,7 +392,8 @@ impl Mutex { /// let _ = thread::spawn(move || { /// let _lock = c_mutex.lock().unwrap(); /// panic!(); // the mutex gets poisoned - /// }).join(); + /// }) + /// .join(); /// /// assert_eq!(mutex.is_poisoned(), true); /// let x = mutex.lock().unwrap_or_else(|mut e| { diff --git a/library/std/src/sync/once_lock.rs b/library/std/src/sync/once_lock.rs index 37413ec62a717..1c4b4076e853b 100644 --- a/library/std/src/sync/once_lock.rs +++ b/library/std/src/sync/once_lock.rs @@ -20,11 +20,11 @@ use crate::sync::Once; /// assert!(CELL.get().is_none()); /// /// std::thread::spawn(|| { -/// let value: &String = CELL.get_or_init(|| { -/// "Hello, World!".to_string() -/// }); +/// let value: &String = CELL.get_or_init(|| "Hello, World!".to_string()); /// assert_eq!(value, "Hello, World!"); -/// }).join().unwrap(); +/// }) +/// .join() +/// .unwrap(); /// /// let value: Option<&String> = CELL.get(); /// assert!(value.is_some()); @@ -117,7 +117,9 @@ impl OnceLock { /// /// std::thread::spawn(|| { /// assert_eq!(CELL.set(92), Ok(())); - /// }).join().unwrap(); + /// }) + /// .join() + /// .unwrap(); /// /// assert_eq!(CELL.set(62), Err(62)); /// assert_eq!(CELL.get(), Some(&92)); @@ -195,9 +197,7 @@ impl OnceLock { /// let cell = OnceLock::new(); /// assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); /// assert!(cell.get().is_none()); - /// let value = cell.get_or_try_init(|| -> Result { - /// Ok(92) - /// }); + /// let value = cell.get_or_try_init(|| -> Result { Ok(92) }); /// assert_eq!(value, Ok(&92)); /// assert_eq!(cell.get(), Some(&92)) /// ``` diff --git a/library/std/src/sync/poison.rs b/library/std/src/sync/poison.rs index 741312d5537e9..808c765cfb8b8 100644 --- a/library/std/src/sync/poison.rs +++ b/library/std/src/sync/poison.rs @@ -80,7 +80,8 @@ pub struct Guard { /// let mut data = c_mutex.lock().unwrap(); /// *data = 2; /// panic!(); -/// }).join(); +/// }) +/// .join(); /// /// match mutex.lock() { /// Ok(_) => unreachable!(), @@ -188,7 +189,8 @@ impl PoisonError { /// let mut data = c_mutex.lock().unwrap(); /// data.insert(10); /// panic!(); - /// }).join(); + /// }) + /// .join(); /// /// let p_err = mutex.lock().unwrap_err(); /// let data = p_err.into_inner(); diff --git a/library/std/src/sync/rwlock.rs b/library/std/src/sync/rwlock.rs index 8b387760768c5..106016d4c85e7 100644 --- a/library/std/src/sync/rwlock.rs +++ b/library/std/src/sync/rwlock.rs @@ -205,7 +205,9 @@ impl RwLock { /// thread::spawn(move || { /// let r = c_lock.read(); /// assert!(r.is_ok()); - /// }).join().unwrap(); + /// }) + /// .join() + /// .unwrap(); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] @@ -371,7 +373,8 @@ impl RwLock { /// let _ = thread::spawn(move || { /// let _lock = c_lock.write().unwrap(); /// panic!(); // the lock gets poisoned - /// }).join(); + /// }) + /// .join(); /// assert_eq!(lock.is_poisoned(), true); /// ``` #[inline] @@ -402,7 +405,8 @@ impl RwLock { /// let _ = thread::spawn(move || { /// let _lock = c_lock.write().unwrap(); /// panic!(); // the mutex gets poisoned - /// }).join(); + /// }) + /// .join(); /// /// assert_eq!(lock.is_poisoned(), true); /// let guard = lock.write().unwrap_or_else(|mut e| { diff --git a/library/std/src/sys/itron/condvar.rs b/library/std/src/sys/itron/condvar.rs index 008cd8fb1e392..a2e9e464d3097 100644 --- a/library/std/src/sys/itron/condvar.rs +++ b/library/std/src/sys/itron/condvar.rs @@ -177,7 +177,6 @@ mod waiter_queue { /// - `*waiter_ptr` must be valid until it's removed from the queue. /// /// - `*waiter_ptr` must not have been previously inserted to a `WaiterQueue`. - /// pub unsafe fn insert(&mut self, mut waiter_ptr: NonNull) { unsafe { let waiter = waiter_ptr.as_mut(); diff --git a/library/std/src/sys/sgx/abi/reloc.rs b/library/std/src/sys/sgx/abi/reloc.rs index 02dff0ad29fc3..52a1dad5277c1 100644 --- a/library/std/src/sys/sgx/abi/reloc.rs +++ b/library/std/src/sys/sgx/abi/reloc.rs @@ -24,7 +24,7 @@ pub fn relocate_elf_rela() { from_raw_parts::>(mem::rel_ptr(RELA), RELACOUNT) // unsafe ok: link-time constant }; for rela in relas { - if rela.info != (/*0 << 32 |*/R_X86_64_RELATIVE as u64) { + if rela.info != (/* 0 << 32 | */R_X86_64_RELATIVE as u64) { rtabort!("Invalid relocation"); } unsafe { *mem::rel_ptr_mut::<*const ()>(rela.offset) = mem::rel_ptr(rela.addend) }; diff --git a/library/std/src/sys/windows/c/errors.rs b/library/std/src/sys/windows/c/errors.rs index 23dcc119db9f6..3b0346dc9a208 100644 --- a/library/std/src/sys/windows/c/errors.rs +++ b/library/std/src/sys/windows/c/errors.rs @@ -1596,7 +1596,7 @@ pub const ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY: DWORD = 13879; pub const ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN: DWORD = 13881; pub const ERROR_IPSEC_IKE_MM_LIMIT: DWORD = 13882; pub const ERROR_IPSEC_IKE_NEGOTIATION_DISABLED: DWORD = 13883; -/*pub const ERROR_IPSEC_IKE_NEG_STATUS_END: DWORD = 13884)*/ +/* pub const ERROR_IPSEC_IKE_NEG_STATUS_END: DWORD = 13884) */ pub const ERROR_IPSEC_IKE_QM_LIMIT: DWORD = 13884; pub const ERROR_IPSEC_IKE_MM_EXPIRED: DWORD = 13885; pub const ERROR_IPSEC_IKE_PEER_MM_ASSUMED_INVALID: DWORD = 13886; diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs index 05023df1bb24b..ae29a500b62e0 100644 --- a/library/std/src/thread/mod.rs +++ b/library/std/src/thread/mod.rs @@ -264,9 +264,11 @@ pub use self::local::statik::Key as __StaticLocalKeyInner; /// /// let builder = thread::Builder::new(); /// -/// let handler = builder.spawn(|| { -/// // thread code -/// }).unwrap(); +/// let handler = builder +/// .spawn(|| { +/// // thread code +/// }) +/// .unwrap(); /// /// handler.join().unwrap(); /// ``` @@ -298,13 +300,13 @@ impl Builder { /// ``` /// use std::thread; /// - /// let builder = thread::Builder::new() - /// .name("foo".into()) - /// .stack_size(32 * 1024); + /// let builder = thread::Builder::new().name("foo".into()).stack_size(32 * 1024); /// - /// let handler = builder.spawn(|| { - /// // thread code - /// }).unwrap(); + /// let handler = builder + /// .spawn(|| { + /// // thread code + /// }) + /// .unwrap(); /// /// handler.join().unwrap(); /// ``` @@ -326,12 +328,9 @@ impl Builder { /// ``` /// use std::thread; /// - /// let builder = thread::Builder::new() - /// .name("foo".into()); + /// let builder = thread::Builder::new().name("foo".into()); /// - /// let handler = builder.spawn(|| { - /// assert_eq!(thread::current().name(), Some("foo")) - /// }).unwrap(); + /// let handler = builder.spawn(|| assert_eq!(thread::current().name(), Some("foo"))).unwrap(); /// /// handler.join().unwrap(); /// ``` @@ -395,9 +394,11 @@ impl Builder { /// /// let builder = thread::Builder::new(); /// - /// let handler = builder.spawn(|| { - /// // thread code - /// }).unwrap(); + /// let handler = builder + /// .spawn(|| { + /// // thread code + /// }) + /// .unwrap(); /// /// handler.join().unwrap(); /// ``` @@ -457,9 +458,11 @@ impl Builder { /// let thread_x = &x; /// /// let handler = unsafe { - /// builder.spawn_unchecked(move || { - /// println!("x = {}", *thread_x); - /// }).unwrap() + /// builder + /// .spawn_unchecked(move || { + /// println!("x = {}", *thread_x); + /// }) + /// .unwrap() /// }; /// /// // caller has to ensure `join()` is called, otherwise @@ -660,14 +663,13 @@ impl Builder { /// of values to a thread. /// /// ``` -/// use std::thread; /// use std::sync::mpsc::channel; +/// use std::thread; /// /// let (tx, rx) = channel(); /// /// let sender = thread::spawn(move || { -/// tx.send("Hello, thread".to_owned()) -/// .expect("Unable to send on channel"); +/// tx.send("Hello, thread".to_owned()).expect("Unable to send on channel"); /// }); /// /// let receiver = thread::spawn(move || { @@ -956,8 +958,11 @@ impl Drop for PanicGuard { /// # Examples /// /// ``` +/// use std::sync::{ +/// atomic::{AtomicBool, Ordering}, +/// Arc, +/// }; /// use std::thread; -/// use std::sync::{Arc, atomic::{Ordering, AtomicBool}}; /// use std::time::Duration; /// /// let flag = Arc::new(AtomicBool::new(false)); @@ -1043,7 +1048,7 @@ pub fn park_timeout_ms(ms: u32) { /// /// ```rust,no_run /// use std::thread::park_timeout; -/// use std::time::{Instant, Duration}; +/// use std::time::{Duration, Instant}; /// /// let timeout = Duration::from_secs(2); /// let beginning_park = Instant::now(); @@ -1089,9 +1094,7 @@ pub fn park_timeout(dur: Duration) { /// ``` /// use std::thread; /// -/// let other_thread = thread::spawn(|| { -/// thread::current().id() -/// }); +/// let other_thread = thread::spawn(|| thread::current().id()); /// /// let other_thread_id = other_thread.join().unwrap(); /// assert!(thread::current().id() != other_thread_id); @@ -1267,9 +1270,7 @@ impl Thread { /// ``` /// use std::thread; /// - /// let other_thread = thread::spawn(|| { - /// thread::current().id() - /// }); + /// let other_thread = thread::spawn(|| thread::current().id()); /// /// let other_thread_id = other_thread.join().unwrap(); /// assert!(thread::current().id() != other_thread_id); @@ -1294,9 +1295,11 @@ impl Thread { /// /// let builder = thread::Builder::new(); /// - /// let handler = builder.spawn(|| { - /// assert!(thread::current().name().is_none()); - /// }).unwrap(); + /// let handler = builder + /// .spawn(|| { + /// assert!(thread::current().name().is_none()); + /// }) + /// .unwrap(); /// /// handler.join().unwrap(); /// ``` @@ -1306,12 +1309,9 @@ impl Thread { /// ``` /// use std::thread; /// - /// let builder = thread::Builder::new() - /// .name("foo".into()); + /// let builder = thread::Builder::new().name("foo".into()); /// - /// let handler = builder.spawn(|| { - /// assert_eq!(thread::current().name(), Some("foo")) - /// }).unwrap(); + /// let handler = builder.spawn(|| assert_eq!(thread::current().name(), Some("foo"))).unwrap(); /// /// handler.join().unwrap(); /// ``` @@ -1366,12 +1366,13 @@ impl fmt::Debug for Thread { /// Matching on the result of a joined thread: /// /// ```no_run -/// use std::{fs, thread, panic}; +/// use std::{fs, panic, thread}; /// /// fn copy_in_thread() -> thread::Result<()> { /// thread::spawn(|| { /// fs::copy("foo.txt", "bar.txt").unwrap(); -/// }).join() +/// }) +/// .join() /// } /// /// fn main() { @@ -1483,9 +1484,11 @@ impl<'scope, T> JoinInner<'scope, T> { /// /// let builder = thread::Builder::new(); /// -/// let join_handle: thread::JoinHandle<_> = builder.spawn(|| { -/// // some work here -/// }).unwrap(); +/// let join_handle: thread::JoinHandle<_> = builder +/// .spawn(|| { +/// // some work here +/// }) +/// .unwrap(); /// ``` /// /// A thread being detached and outliving the thread that spawned it: @@ -1532,9 +1535,11 @@ impl JoinHandle { /// /// let builder = thread::Builder::new(); /// - /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| { - /// // some work here - /// }).unwrap(); + /// let join_handle: thread::JoinHandle<_> = builder + /// .spawn(|| { + /// // some work here + /// }) + /// .unwrap(); /// /// let thread = join_handle.thread(); /// println!("thread id: {:?}", thread.id()); @@ -1573,9 +1578,11 @@ impl JoinHandle { /// /// let builder = thread::Builder::new(); /// - /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| { - /// // some work here - /// }).unwrap(); + /// let join_handle: thread::JoinHandle<_> = builder + /// .spawn(|| { + /// // some work here + /// }) + /// .unwrap(); /// join_handle.join().expect("Couldn't join on the associated thread"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/std/src/thread/scoped.rs b/library/std/src/thread/scoped.rs index e6dbf35bd0286..fa9648d43e697 100644 --- a/library/std/src/thread/scoped.rs +++ b/library/std/src/thread/scoped.rs @@ -218,23 +218,21 @@ impl Builder { /// thread::scope(|s| { /// thread::Builder::new() /// .name("first".to_string()) - /// .spawn_scoped(s, || - /// { - /// println!("hello from the {:?} scoped thread", thread::current().name()); - /// // We can borrow `a` here. - /// dbg!(&a); - /// }) - /// .unwrap(); + /// .spawn_scoped(s, || { + /// println!("hello from the {:?} scoped thread", thread::current().name()); + /// // We can borrow `a` here. + /// dbg!(&a); + /// }) + /// .unwrap(); /// thread::Builder::new() /// .name("second".to_string()) - /// .spawn_scoped(s, || - /// { - /// println!("hello from the {:?} scoped thread", thread::current().name()); - /// // We can even mutably borrow `x` here, - /// // because no other threads are using it. - /// x += a[0] + a[2]; - /// }) - /// .unwrap(); + /// .spawn_scoped(s, || { + /// println!("hello from the {:?} scoped thread", thread::current().name()); + /// // We can even mutably borrow `x` here, + /// // because no other threads are using it. + /// x += a[0] + a[2]; + /// }) + /// .unwrap(); /// println!("hello from the main thread"); /// }); /// diff --git a/library/std/src/time.rs b/library/std/src/time.rs index 34e18b5fa8778..942702b43947c 100644 --- a/library/std/src/time.rs +++ b/library/std/src/time.rs @@ -70,16 +70,16 @@ pub use core::time::TryFromFloatSecsError; /// Example: /// /// ```no_run -/// use std::time::{Duration, Instant}; /// use std::thread::sleep; +/// use std::time::{Duration, Instant}; /// /// fn main() { -/// let now = Instant::now(); +/// let now = Instant::now(); /// -/// // we sleep for 2 seconds -/// sleep(Duration::new(2, 0)); -/// // it prints '2' -/// println!("{}", now.elapsed().as_secs()); +/// // we sleep for 2 seconds +/// sleep(Duration::new(2, 0)); +/// // it prints '2' +/// println!("{}", now.elapsed().as_secs()); /// } /// ``` /// @@ -92,7 +92,7 @@ pub use core::time::TryFromFloatSecsError; /// the following snippet is fine on Linux but panics on macOS: /// /// ```no_run -/// use std::time::{Instant, Duration}; +/// use std::time::{Duration, Instant}; /// /// let now = Instant::now(); /// let max_seconds = u64::MAX / 1_000_000_000; @@ -148,7 +148,6 @@ pub use core::time::TryFromFloatSecsError; /// [`elapsed`]: Instant::elapsed /// [`sub`]: Instant::sub /// [`checked_duration_since`]: Instant::checked_duration_since -/// #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[stable(feature = "time2", since = "1.8.0")] pub struct Instant(time::Instant); @@ -179,24 +178,24 @@ pub struct Instant(time::Instant); /// Example: /// /// ```no_run -/// use std::time::{Duration, SystemTime}; /// use std::thread::sleep; +/// use std::time::{Duration, SystemTime}; /// /// fn main() { -/// let now = SystemTime::now(); -/// -/// // we sleep for 2 seconds -/// sleep(Duration::new(2, 0)); -/// match now.elapsed() { -/// Ok(elapsed) => { -/// // it prints '2' -/// println!("{}", elapsed.as_secs()); -/// } -/// Err(e) => { -/// // an error occurred! -/// println!("Error: {e:?}"); -/// } -/// } +/// let now = SystemTime::now(); +/// +/// // we sleep for 2 seconds +/// sleep(Duration::new(2, 0)); +/// match now.elapsed() { +/// Ok(elapsed) => { +/// // it prints '2' +/// println!("{}", elapsed.as_secs()); +/// } +/// Err(e) => { +/// // an error occurred! +/// println!("Error: {e:?}"); +/// } +/// } /// } /// ``` /// @@ -290,8 +289,8 @@ impl Instant { /// # Examples /// /// ```no_run - /// use std::time::{Duration, Instant}; /// use std::thread::sleep; + /// use std::time::{Duration, Instant}; /// /// let now = Instant::now(); /// sleep(Duration::new(1, 0)); @@ -316,8 +315,8 @@ impl Instant { /// # Examples /// /// ```no_run - /// use std::time::{Duration, Instant}; /// use std::thread::sleep; + /// use std::time::{Duration, Instant}; /// /// let now = Instant::now(); /// sleep(Duration::new(1, 0)); @@ -337,8 +336,8 @@ impl Instant { /// # Examples /// /// ```no_run - /// use std::time::{Duration, Instant}; /// use std::thread::sleep; + /// use std::time::{Duration, Instant}; /// /// let now = Instant::now(); /// sleep(Duration::new(1, 0)); @@ -516,8 +515,7 @@ impl SystemTime { /// /// let sys_time = SystemTime::now(); /// let new_sys_time = SystemTime::now(); - /// let difference = new_sys_time.duration_since(sys_time) - /// .expect("Clock may have gone backwards"); + /// let difference = new_sys_time.duration_since(sys_time).expect("Clock may have gone backwards"); /// println!("{difference:?}"); /// ``` #[stable(feature = "time2", since = "1.8.0")]