diff --git a/compiler/rustc_data_structures/src/marker.rs b/compiler/rustc_data_structures/src/marker.rs index 2fe2a30c36751..505a7a4c9d465 100644 --- a/compiler/rustc_data_structures/src/marker.rs +++ b/compiler/rustc_data_structures/src/marker.rs @@ -85,7 +85,7 @@ impl_dyn_send!( [std::sync::LazyLock where T: DynSend, F: DynSend] [std::collections::HashSet where K: DynSend, S: DynSend] [std::collections::HashMap where K: DynSend, V: DynSend, S: DynSend] - [std::collections::BTreeMap where K: DynSend, V: DynSend, A: std::alloc::Allocator + Clone + DynSend] + [std::collections::BTreeMap where K: DynSend, V: DynSend, A: std::alloc::AllocatorClone + DynSend] [Vec where T: DynSend, A: std::alloc::Allocator + DynSend] [Box where T: ?Sized + DynSend, A: std::alloc::Allocator + DynSend] [crate::sync::RwLock where T: DynSend] @@ -168,7 +168,7 @@ impl_dyn_sync!( [std::sync::LazyLock where T: DynSend + DynSync, F: DynSend] [std::collections::HashSet where K: DynSync, S: DynSync] [std::collections::HashMap where K: DynSync, V: DynSync, S: DynSync] - [std::collections::BTreeMap where K: DynSync, V: DynSync, A: std::alloc::Allocator + Clone + DynSync] + [std::collections::BTreeMap where K: DynSync, V: DynSync, A: std::alloc::AllocatorClone + DynSync] [Vec where T: DynSync, A: std::alloc::Allocator + DynSync] [Box where T: ?Sized + DynSync, A: std::alloc::Allocator + DynSync] [crate::sync::RwLock where T: DynSend + DynSync] diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index ce575758a775a..9bac421564b60 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -2706,15 +2706,10 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { struct RegionFolder<'a, 'tcx> { tcx: TyCtxt<'tcx>, current_index: ty::DebruijnIndex, + /// Regions bound by the binder being named (and placeholders) that have + /// already been named. region_map: UnordMap, ty::Region<'tcx>>, - name: &'a mut ( - dyn FnMut( - Option, // Debruijn index of the folded late-bound region - ty::DebruijnIndex, // Index corresponding to binder level - ty::BoundRegion<'tcx>, - ) -> ty::Region<'tcx> - + 'a - ), + name: &'a mut (dyn FnMut(ty::BoundRegion<'tcx>) -> ty::Region<'tcx> + 'a), } impl<'a, 'tcx> ty::TypeFolder> for RegionFolder<'a, 'tcx> { @@ -2745,8 +2740,13 @@ impl<'a, 'tcx> ty::TypeFolder> for RegionFolder<'a, 'tcx> { fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { let name = &mut self.name; let region = match r.kind() { - ty::ReBound(ty::BoundVarIndexKind::Bound(db), br) if db >= self.current_index => { - *self.region_map.entry(br).or_insert_with(|| name(Some(db), self.current_index, br)) + // Only name regions bound by the binder being named. Regions bound by an + // enclosing binder that merely escape through this one keep their name + // (they were named when that binder was folded) and their index, and must + // not end up in `region_map`, which callers use to build `for<...>` lists + // (#102392, #134410). + ty::ReBound(ty::BoundVarIndexKind::Bound(db), br) if db == self.current_index => { + *self.region_map.entry(br).or_insert_with(|| name(br)) } ty::RePlaceholder(ty::PlaceholderRegion { bound: ty::BoundRegion { kind, .. }, @@ -2759,10 +2759,7 @@ impl<'a, 'tcx> ty::TypeFolder> for RegionFolder<'a, 'tcx> { _ => { // Index doesn't matter, since this is just for naming and these never get bound let br = ty::BoundRegion { var: ty::BoundVar::ZERO, kind }; - *self - .region_map - .entry(br) - .or_insert_with(|| name(None, self.current_index, br)) + *self.region_map.entry(br).or_insert_with(|| name(br)) } } } @@ -2871,13 +2868,8 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { let trim_path = with_forced_trimmed_paths(); // Closure used in `RegionFolder` to create names for anonymous late-bound - // regions. We use two `DebruijnIndex`es (one for the currently folded - // late-bound region and the other for the binder level) to determine - // whether a name has already been created for the currently folded region, - // see issue #102392. - let mut name = |lifetime_idx: Option, - binder_level_idx: ty::DebruijnIndex, - br: ty::BoundRegion<'tcx>| { + // regions. + let mut name = |br: ty::BoundRegion<'tcx>| { let (name, kind) = if let Some(name) = br.kind.get_name(tcx) { (name, br.kind) } else { @@ -2885,16 +2877,6 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { (name, ty::BoundRegionKind::NamedForPrinting(name)) }; - if let Some(lt_idx) = lifetime_idx { - if lt_idx > binder_level_idx { - return ty::Region::new_bound( - tcx, - ty::INNERMOST, - ty::BoundRegion { var: br.var, kind }, - ); - } - } - // Unconditionally render `unsafe<>`. if !trim_path || mode == WrapBinderMode::Unsafe { start_or_continue(self, mode.start_str(), ", "); diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 58be46690b788..613791448eb5b 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -808,7 +808,6 @@ impl Box { /// ``` #[unstable(feature = "clone_from_ref", issue = "149075")] //#[unstable(feature = "allocator_api", issue = "32838")] - #[must_use] #[inline] pub fn try_clone_from_ref(src: &T) -> Result, AllocError> { Box::try_clone_from_ref_in(src, Global) @@ -860,7 +859,6 @@ impl Box { /// ``` #[unstable(feature = "clone_from_ref", issue = "149075")] //#[unstable(feature = "allocator_api", issue = "32838")] - #[must_use] #[inline] pub fn try_clone_from_ref_in(src: &T, alloc: A) -> Result, AllocError> { struct DeallocDropGuard<'a, A: Allocator>(Layout, &'a A, NonNull); @@ -1156,7 +1154,6 @@ impl Box<[T], A> { /// ``` #[unstable(feature = "alloc_slice_into_array", issue = "148082")] #[inline] - #[must_use] pub fn into_array(self) -> Result, Self> { if self.len() == N { let (ptr, alloc) = Self::into_raw_with_allocator(self); diff --git a/library/alloc/src/bstr.rs b/library/alloc/src/bstr.rs index 9aa3064da886f..f48b2d52e80c1 100644 --- a/library/alloc/src/bstr.rs +++ b/library/alloc/src/bstr.rs @@ -42,7 +42,7 @@ use crate::vec::Vec; /// showing invalid UTF-8 as hex escapes or the Unicode replacement character, respectively. #[unstable(feature = "bstr", issue = "134915")] #[repr(transparent)] -#[derive(Clone)] +#[derive(Clone, Default)] #[doc(alias = "BString")] pub struct ByteString(pub Vec); @@ -187,13 +187,6 @@ impl BorrowMut for ByteString { // `impl BorrowMut for Vec` omitted to avoid inference failures -#[unstable(feature = "bstr", issue = "134915")] -impl Default for ByteString { - fn default() -> Self { - ByteString(Vec::new()) - } -} - // Omitted due to inference failures // // #[unstable(feature = "bstr", issue = "134915")] diff --git a/library/alloc/src/collections/btree/append.rs b/library/alloc/src/collections/btree/append.rs index cc8d793e98e4d..4f11b1f6ea432 100644 --- a/library/alloc/src/collections/btree/append.rs +++ b/library/alloc/src/collections/btree/append.rs @@ -1,4 +1,4 @@ -use core::alloc::Allocator; +use core::alloc::AllocatorClone; use super::node::{self, Root}; @@ -6,12 +6,8 @@ impl Root { /// Pushes all key-value pairs to the end of the tree, incrementing a /// `length` variable along the way. The latter makes it easier for the /// caller to avoid a leak when the iterator panicks. - pub(super) fn bulk_push( - &mut self, - iter: I, - length: &mut usize, - alloc: A, - ) where + pub(super) fn bulk_push(&mut self, iter: I, length: &mut usize, alloc: A) + where I: Iterator, { let mut cur_node = self.borrow_mut().last_leaf_edge().into_node(); diff --git a/library/alloc/src/collections/btree/fix.rs b/library/alloc/src/collections/btree/fix.rs index b0c6759794691..0b36c203c1170 100644 --- a/library/alloc/src/collections/btree/fix.rs +++ b/library/alloc/src/collections/btree/fix.rs @@ -1,4 +1,4 @@ -use core::alloc::Allocator; +use core::alloc::AllocatorClone; use super::map::MIN_LEN; use super::node::ForceResult::*; @@ -10,7 +10,7 @@ impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { /// sibling. If successful but at the cost of shrinking the parent node, /// returns that shrunk parent node. Returns an `Err` if the node is /// an empty root. - fn fix_node_through_parent( + fn fix_node_through_parent( self, alloc: A, ) -> Result, K, V, marker::Internal>>, Self> { @@ -57,10 +57,7 @@ impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { /// /// This method does not expect ancestors to already be underfull upon entry /// and panics if it encounters an empty ancestor. - pub(super) fn fix_node_and_affected_ancestors( - mut self, - alloc: A, - ) -> bool { + pub(super) fn fix_node_and_affected_ancestors(mut self, alloc: A) -> bool { loop { match self.fix_node_through_parent(alloc.clone()) { Ok(Some(parent)) => self = parent.forget_type(), @@ -73,7 +70,7 @@ impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { impl Root { /// Removes empty levels on the top, but keeps an empty leaf if the entire tree is empty. - pub(super) fn fix_top(&mut self, alloc: A) { + pub(super) fn fix_top(&mut self, alloc: A) { while self.height() > 0 && self.len() == 0 { self.pop_internal_level(alloc.clone()); } @@ -82,7 +79,7 @@ impl Root { /// Stocks up or merge away any underfull nodes on the right border of the /// tree. The other nodes, those that are not the root nor a rightmost edge, /// must already have at least MIN_LEN elements. - pub(super) fn fix_right_border(&mut self, alloc: A) { + pub(super) fn fix_right_border(&mut self, alloc: A) { self.fix_top(alloc.clone()); if self.len() > 0 { self.borrow_mut().last_kv().fix_right_border_of_right_edge(alloc.clone()); @@ -91,7 +88,7 @@ impl Root { } /// The symmetric clone of `fix_right_border`. - pub(super) fn fix_left_border(&mut self, alloc: A) { + pub(super) fn fix_left_border(&mut self, alloc: A) { self.fix_top(alloc.clone()); if self.len() > 0 { self.borrow_mut().first_kv().fix_left_border_of_left_edge(alloc.clone()); @@ -121,14 +118,14 @@ impl Root { } impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::KV> { - fn fix_left_border_of_left_edge(mut self, alloc: A) { + fn fix_left_border_of_left_edge(mut self, alloc: A) { while let Internal(internal_kv) = self.force() { self = internal_kv.fix_left_child(alloc.clone()).first_kv(); debug_assert!(self.reborrow().into_node().len() > MIN_LEN); } } - fn fix_right_border_of_right_edge(mut self, alloc: A) { + fn fix_right_border_of_right_edge(mut self, alloc: A) { while let Internal(internal_kv) = self.force() { self = internal_kv.fix_right_child(alloc.clone()).last_kv(); debug_assert!(self.reborrow().into_node().len() > MIN_LEN); @@ -141,7 +138,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, /// provisions an extra element to allow merging its children in turn /// without becoming underfull. /// Returns the left child. - fn fix_left_child( + fn fix_left_child( self, alloc: A, ) -> NodeRef, K, V, marker::LeafOrInternal> { @@ -164,7 +161,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, /// provisions an extra element to allow merging its children in turn /// without becoming underfull. /// Returns wherever the right child ended up. - fn fix_right_child( + fn fix_right_child( self, alloc: A, ) -> NodeRef, K, V, marker::LeafOrInternal> { diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs index d8421d3c3f70a..80317ab2f17ed 100644 --- a/library/alloc/src/collections/btree/map.rs +++ b/library/alloc/src/collections/btree/map.rs @@ -17,7 +17,7 @@ use super::node::{self, Handle, NodeRef, Root, marker}; use super::search::SearchBound; use super::search::SearchResult::*; use super::set_val::SetValZST; -use crate::alloc::{Allocator, Global}; +use crate::alloc::{AllocatorClone, Global}; use crate::vec::Vec; mod entry; @@ -189,7 +189,7 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT; pub struct BTreeMap< K, V, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { root: Option>, length: usize, @@ -203,7 +203,7 @@ pub struct BTreeMap< } #[stable(feature = "btree_drop", since = "1.7.0")] -unsafe impl<#[may_dangle] K, #[may_dangle] V, A: Allocator + Clone> Drop for BTreeMap { +unsafe impl<#[may_dangle] K, #[may_dangle] V, A: AllocatorClone> Drop for BTreeMap { fn drop(&mut self) { drop(unsafe { ptr::read(self) }.into_iter()) } @@ -214,7 +214,7 @@ unsafe impl<#[may_dangle] K, #[may_dangle] V, A: Allocator + Clone> Drop for BTr // Maybe we can fix it nonetheless with a crater run, or if the `UnwindSafe` // traits are deprecated, or disarmed (no longer causing hard errors) in the future. #[stable(feature = "btree_unwindsafe", since = "1.64.0")] -impl core::panic::UnwindSafe for BTreeMap +impl core::panic::UnwindSafe for BTreeMap where A: core::panic::UnwindSafe, K: core::panic::RefUnwindSafe, @@ -223,9 +223,9 @@ where } #[stable(feature = "rust1", since = "1.0.0")] -impl Clone for BTreeMap { +impl Clone for BTreeMap { fn clone(&self) -> BTreeMap { - fn clone_subtree<'a, K: Clone, V: Clone, A: Allocator + Clone>( + fn clone_subtree<'a, K: Clone, V: Clone, A: AllocatorClone>( node: NodeRef, K, V, marker::LeafOrInternal>, alloc: A, ) -> BTreeMap @@ -309,7 +309,7 @@ impl Clone for BTreeMap { } // Internal functionality for `BTreeSet`. -impl BTreeMap { +impl BTreeMap { pub(super) fn replace(&mut self, key: K) -> Option where K: Ord, @@ -444,7 +444,7 @@ impl<'a, K: 'a, V: 'a> Default for IterMut<'a, K, V> { pub struct IntoIter< K, V, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { range: LazyLeafRange, length: usize, @@ -452,7 +452,7 @@ pub struct IntoIter< alloc: A, } -impl IntoIter { +impl IntoIter { /// Returns an iterator of references over the remaining items. #[inline] pub(super) fn iter(&self) -> Iter<'_, K, V> { @@ -461,7 +461,7 @@ impl IntoIter { } #[stable(feature = "collection_debug", since = "1.17.0")] -impl Debug for IntoIter { +impl Debug for IntoIter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.iter()).finish() } @@ -470,7 +470,7 @@ impl Debug for IntoIter { #[stable(feature = "default_iters", since = "1.70.0")] impl Default for IntoIter where - A: Allocator + Default + Clone, + A: AllocatorClone + Default, { /// Creates an empty `btree_map::IntoIter`. /// @@ -552,13 +552,13 @@ impl fmt::Debug for ValuesMut<'_, K, V> { pub struct IntoKeys< K, V, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { inner: IntoIter, } #[stable(feature = "map_into_keys_values", since = "1.54.0")] -impl fmt::Debug for IntoKeys { +impl fmt::Debug for IntoKeys { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish() } @@ -575,13 +575,13 @@ impl fmt::Debug for IntoKeys { pub struct IntoValues< K, V, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { inner: IntoIter, } #[stable(feature = "map_into_keys_values", since = "1.54.0")] -impl fmt::Debug for IntoValues { +impl fmt::Debug for IntoValues { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish() } @@ -653,7 +653,7 @@ impl BTreeMap { } } -impl BTreeMap { +impl BTreeMap { /// Clears the map, removing all elements. /// /// # Examples @@ -670,7 +670,7 @@ impl BTreeMap { pub fn clear(&mut self) { // avoid moving the allocator drop(BTreeMap { - root: mem::replace(&mut self.root, None), + root: self.root.take(), length: mem::replace(&mut self.length, 0), alloc: self.alloc.clone(), _marker: PhantomData, @@ -697,7 +697,7 @@ impl BTreeMap { } } -impl BTreeMap { +impl BTreeMap { /// Returns a reference to the value corresponding to the key. /// /// The key may be any borrowed form of the map's key type, but the ordering @@ -1719,7 +1719,7 @@ impl BTreeMap { } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a BTreeMap { +impl<'a, K, V, A: AllocatorClone> IntoIterator for &'a BTreeMap { type Item = (&'a K, &'a V); type IntoIter = Iter<'a, K, V>; @@ -1797,7 +1797,7 @@ impl Clone for Iter<'_, K, V> { } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a mut BTreeMap { +impl<'a, K, V, A: AllocatorClone> IntoIterator for &'a mut BTreeMap { type Item = (&'a K, &'a mut V); type IntoIter = IterMut<'a, K, V>; @@ -1876,7 +1876,7 @@ impl<'a, K, V> IterMut<'a, K, V> { } #[stable(feature = "rust1", since = "1.0.0")] -impl IntoIterator for BTreeMap { +impl IntoIterator for BTreeMap { type Item = (K, V); type IntoIter = IntoIter; @@ -1902,11 +1902,11 @@ impl IntoIterator for BTreeMap { } #[stable(feature = "btree_drop", since = "1.7.0")] -impl Drop for IntoIter { +impl Drop for IntoIter { fn drop(&mut self) { - struct DropGuard<'a, K, V, A: Allocator + Clone>(&'a mut IntoIter); + struct DropGuard<'a, K, V, A: AllocatorClone>(&'a mut IntoIter); - impl<'a, K, V, A: Allocator + Clone> Drop for DropGuard<'a, K, V, A> { + impl<'a, K, V, A: AllocatorClone> Drop for DropGuard<'a, K, V, A> { fn drop(&mut self) { // Continue the same loop we perform below. This only runs when unwinding, so we // don't have to care about panics this time (they'll abort). @@ -1926,7 +1926,7 @@ impl Drop for IntoIter { } } -impl IntoIter { +impl IntoIter { /// Core of a `next` method returning a dying KV handle, /// invalidated by further calls to this function and some others. fn dying_next( @@ -1957,7 +1957,7 @@ impl IntoIter { } #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for IntoIter { +impl Iterator for IntoIter { type Item = (K, V); fn next(&mut self) -> Option<(K, V)> { @@ -1971,7 +1971,7 @@ impl Iterator for IntoIter { } #[stable(feature = "rust1", since = "1.0.0")] -impl DoubleEndedIterator for IntoIter { +impl DoubleEndedIterator for IntoIter { fn next_back(&mut self) -> Option<(K, V)> { // SAFETY: we consume the dying handle immediately. self.dying_next_back().map(unsafe { |kv| kv.into_key_val() }) @@ -1979,17 +1979,17 @@ impl DoubleEndedIterator for IntoIter { } #[stable(feature = "rust1", since = "1.0.0")] -impl ExactSizeIterator for IntoIter { +impl ExactSizeIterator for IntoIter { fn len(&self) -> usize { self.length } } #[unstable(feature = "trusted_len", issue = "37572")] -unsafe impl TrustedLen for IntoIter {} +unsafe impl TrustedLen for IntoIter {} #[stable(feature = "fused", since = "1.26.0")] -impl FusedIterator for IntoIter {} +impl FusedIterator for IntoIter {} #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> Iterator for Keys<'a, K, V> { @@ -2133,7 +2133,7 @@ pub struct ExtractIf< V, R, F, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { pred: F, inner: ExtractIfInner<'a, K, V, R>, @@ -2163,7 +2163,7 @@ impl fmt::Debug for ExtractIf<'_, K, V, R, F, A> where K: fmt::Debug, V: fmt::Debug, - A: Allocator + Clone, + A: AllocatorClone, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ExtractIf").field("peek", &self.inner.peek()).finish_non_exhaustive() @@ -2171,7 +2171,7 @@ where } #[stable(feature = "btree_extract_if", since = "1.91.0")] -impl Iterator for ExtractIf<'_, K, V, R, F, A> +impl Iterator for ExtractIf<'_, K, V, R, F, A> where K: PartialOrd, R: RangeBounds, @@ -2196,7 +2196,7 @@ impl<'a, K, V, R> ExtractIfInner<'a, K, V, R> { } /// Implementation of a typical `ExtractIf::next` method, given the predicate. - pub(super) fn next(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)> + pub(super) fn next(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)> where K: PartialOrd, R: RangeBounds, @@ -2360,7 +2360,7 @@ impl Default for ValuesMut<'_, K, V> { } #[stable(feature = "map_into_keys_values", since = "1.54.0")] -impl Iterator for IntoKeys { +impl Iterator for IntoKeys { type Item = K; fn next(&mut self) -> Option { @@ -2391,29 +2391,29 @@ impl Iterator for IntoKeys { } #[stable(feature = "map_into_keys_values", since = "1.54.0")] -impl DoubleEndedIterator for IntoKeys { +impl DoubleEndedIterator for IntoKeys { fn next_back(&mut self) -> Option { self.inner.next_back().map(|(k, _)| k) } } #[stable(feature = "map_into_keys_values", since = "1.54.0")] -impl ExactSizeIterator for IntoKeys { +impl ExactSizeIterator for IntoKeys { fn len(&self) -> usize { self.inner.len() } } #[unstable(feature = "trusted_len", issue = "37572")] -unsafe impl TrustedLen for IntoKeys {} +unsafe impl TrustedLen for IntoKeys {} #[stable(feature = "map_into_keys_values", since = "1.54.0")] -impl FusedIterator for IntoKeys {} +impl FusedIterator for IntoKeys {} #[stable(feature = "default_iters", since = "1.70.0")] impl Default for IntoKeys where - A: Allocator + Default + Clone, + A: AllocatorClone + Default, { /// Creates an empty `btree_map::IntoKeys`. /// @@ -2428,7 +2428,7 @@ where } #[stable(feature = "map_into_keys_values", since = "1.54.0")] -impl Iterator for IntoValues { +impl Iterator for IntoValues { type Item = V; fn next(&mut self) -> Option { @@ -2445,29 +2445,29 @@ impl Iterator for IntoValues { } #[stable(feature = "map_into_keys_values", since = "1.54.0")] -impl DoubleEndedIterator for IntoValues { +impl DoubleEndedIterator for IntoValues { fn next_back(&mut self) -> Option { self.inner.next_back().map(|(_, v)| v) } } #[stable(feature = "map_into_keys_values", since = "1.54.0")] -impl ExactSizeIterator for IntoValues { +impl ExactSizeIterator for IntoValues { fn len(&self) -> usize { self.inner.len() } } #[unstable(feature = "trusted_len", issue = "37572")] -unsafe impl TrustedLen for IntoValues {} +unsafe impl TrustedLen for IntoValues {} #[stable(feature = "map_into_keys_values", since = "1.54.0")] -impl FusedIterator for IntoValues {} +impl FusedIterator for IntoValues {} #[stable(feature = "default_iters", since = "1.70.0")] impl Default for IntoValues where - A: Allocator + Default + Clone, + A: AllocatorClone + Default, { /// Creates an empty `btree_map::IntoValues`. /// @@ -2555,7 +2555,7 @@ impl FromIterator<(K, V)> for BTreeMap { } #[stable(feature = "rust1", since = "1.0.0")] -impl Extend<(K, V)> for BTreeMap { +impl Extend<(K, V)> for BTreeMap { #[inline] fn extend>(&mut self, iter: T) { iter.into_iter().for_each(move |(k, v)| { @@ -2570,9 +2570,7 @@ impl Extend<(K, V)> for BTreeMap { } #[stable(feature = "extend_ref", since = "1.2.0")] -impl<'a, K: Ord + Copy, V: Copy, A: Allocator + Clone> Extend<(&'a K, &'a V)> - for BTreeMap -{ +impl<'a, K: Ord + Copy, V: Copy, A: AllocatorClone> Extend<(&'a K, &'a V)> for BTreeMap { fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); } @@ -2584,7 +2582,7 @@ impl<'a, K: Ord + Copy, V: Copy, A: Allocator + Clone> Extend<(&'a K, &'a V)> } #[stable(feature = "rust1", since = "1.0.0")] -impl Hash for BTreeMap { +impl Hash for BTreeMap { fn hash(&self, state: &mut H) { state.write_length_prefix(self.len()); for elt in self { @@ -2603,17 +2601,17 @@ const impl Default for BTreeMap { } #[stable(feature = "rust1", since = "1.0.0")] -impl PartialEq for BTreeMap { +impl PartialEq for BTreeMap { fn eq(&self, other: &BTreeMap) -> bool { self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b) } } #[stable(feature = "rust1", since = "1.0.0")] -impl Eq for BTreeMap {} +impl Eq for BTreeMap {} #[stable(feature = "rust1", since = "1.0.0")] -impl PartialOrd for BTreeMap { +impl PartialOrd for BTreeMap { #[inline] fn partial_cmp(&self, other: &BTreeMap) -> Option { self.iter().partial_cmp(other.iter()) @@ -2621,7 +2619,7 @@ impl PartialOrd for BTreeMap } #[stable(feature = "rust1", since = "1.0.0")] -impl Ord for BTreeMap { +impl Ord for BTreeMap { #[inline] fn cmp(&self, other: &BTreeMap) -> Ordering { self.iter().cmp(other.iter()) @@ -2629,14 +2627,14 @@ impl Ord for BTreeMap { } #[stable(feature = "rust1", since = "1.0.0")] -impl Debug for BTreeMap { +impl Debug for BTreeMap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_map().entries(self.iter()).finish() } } #[stable(feature = "rust1", since = "1.0.0")] -impl Index<&Q> for BTreeMap +impl Index<&Q> for BTreeMap where K: Borrow + Ord, Q: Ord, @@ -2679,7 +2677,7 @@ impl From<[(K, V); N]> for BTreeMap { } } -impl BTreeMap { +impl BTreeMap { /// Gets an iterator over the entries of the map, sorted by key. /// /// # Examples @@ -3422,7 +3420,7 @@ impl<'a, K, V, A> CursorMutKey<'a, K, V, A> { } // Now the tree editing operations -impl<'a, K: Ord, V, A: Allocator + Clone> CursorMutKey<'a, K, V, A> { +impl<'a, K: Ord, V, A: AllocatorClone> CursorMutKey<'a, K, V, A> { /// Inserts a new key-value pair into the map in the gap that the /// cursor is currently pointing to. /// @@ -3627,7 +3625,7 @@ impl<'a, K: Ord, V, A: Allocator + Clone> CursorMutKey<'a, K, V, A> { } } -impl<'a, K: Ord, V, A: Allocator + Clone> CursorMut<'a, K, V, A> { +impl<'a, K: Ord, V, A: AllocatorClone> CursorMut<'a, K, V, A> { /// Inserts a new key-value pair into the map in the gap that the /// cursor is currently pointing to. /// diff --git a/library/alloc/src/collections/btree/map/entry.rs b/library/alloc/src/collections/btree/map/entry.rs index 1c2ad5c568e6a..d3a9651799ab8 100644 --- a/library/alloc/src/collections/btree/map/entry.rs +++ b/library/alloc/src/collections/btree/map/entry.rs @@ -7,7 +7,7 @@ use Entry::*; use super::super::borrow::DormantMutRef; use super::super::node::{Handle, NodeRef, marker}; use super::BTreeMap; -use crate::alloc::{Allocator, Global}; +use crate::alloc::{AllocatorClone, Global}; /// A view into a single entry in a map, which may either be vacant or occupied. /// @@ -20,7 +20,7 @@ pub enum Entry< 'a, K: 'a, V: 'a, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { /// A vacant entry. #[stable(feature = "rust1", since = "1.0.0")] @@ -32,7 +32,7 @@ pub enum Entry< } #[stable(feature = "debug_btree_map", since = "1.12.0")] -impl Debug for Entry<'_, K, V, A> { +impl Debug for Entry<'_, K, V, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(), @@ -48,7 +48,7 @@ pub struct VacantEntry< 'a, K, V, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { pub(super) key: K, /// `None` for a (empty) map without root @@ -63,7 +63,7 @@ pub struct VacantEntry< } #[stable(feature = "debug_btree_map", since = "1.12.0")] -impl Debug for VacantEntry<'_, K, V, A> { +impl Debug for VacantEntry<'_, K, V, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("VacantEntry").field(self.key()).finish() } @@ -76,7 +76,7 @@ pub struct OccupiedEntry< 'a, K, V, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { pub(super) handle: Handle, K, V, marker::LeafOrInternal>, marker::KV>, pub(super) dormant_map: DormantMutRef<'a, BTreeMap>, @@ -89,7 +89,7 @@ pub struct OccupiedEntry< } #[stable(feature = "debug_btree_map", since = "1.12.0")] -impl Debug for OccupiedEntry<'_, K, V, A> { +impl Debug for OccupiedEntry<'_, K, V, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish() } @@ -104,7 +104,7 @@ pub struct OccupiedError< 'a, K: 'a, V: 'a, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { /// The entry in the map that was already occupied. pub entry: OccupiedEntry<'a, K, V, A>, @@ -115,7 +115,7 @@ pub struct OccupiedError< } #[unstable(feature = "map_try_insert", issue = "82766")] -impl Debug for OccupiedError<'_, K, V, A> { +impl Debug for OccupiedError<'_, K, V, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("OccupiedError") .field("key", self.entry.key()) @@ -126,7 +126,7 @@ impl Debug for OccupiedError<'_, } } -impl<'a, K: Ord, V, A: Allocator + Clone> Entry<'a, K, V, A> { +impl<'a, K: Ord, V, A: AllocatorClone> Entry<'a, K, V, A> { /// Ensures a value is in the entry by inserting the default if empty, and returns /// a mutable reference to the value in the entry. /// @@ -345,7 +345,7 @@ impl<'a, K: Ord, V, A: Allocator + Clone> Entry<'a, K, V, A> { } } -impl<'a, K: Ord, V: Default, A: Allocator + Clone> Entry<'a, K, V, A> { +impl<'a, K: Ord, V: Default, A: AllocatorClone> Entry<'a, K, V, A> { #[stable(feature = "entry_or_default", since = "1.28.0")] /// Ensures a value is in the entry by inserting the default value if empty, /// and returns a mutable reference to the value in the entry. @@ -368,7 +368,7 @@ impl<'a, K: Ord, V: Default, A: Allocator + Clone> Entry<'a, K, V, A> { } } -impl<'a, K: Ord, V, A: Allocator + Clone> VacantEntry<'a, K, V, A> { +impl<'a, K: Ord, V, A: AllocatorClone> VacantEntry<'a, K, V, A> { /// Gets a reference to the key that would be used when inserting a value /// through the VacantEntry. /// @@ -479,7 +479,7 @@ impl<'a, K: Ord, V, A: Allocator + Clone> VacantEntry<'a, K, V, A> { } } -impl<'a, K: Ord, V, A: Allocator + Clone> OccupiedEntry<'a, K, V, A> { +impl<'a, K: Ord, V, A: AllocatorClone> OccupiedEntry<'a, K, V, A> { /// Gets a reference to the key in the entry. /// /// # Examples diff --git a/library/alloc/src/collections/btree/navigate.rs b/library/alloc/src/collections/btree/navigate.rs index b2a7de74875d9..d5b514e67e82e 100644 --- a/library/alloc/src/collections/btree/navigate.rs +++ b/library/alloc/src/collections/btree/navigate.rs @@ -5,7 +5,7 @@ use core::{hint, ptr}; use super::node::ForceResult::*; use super::node::{Handle, NodeRef, marker}; use super::search::SearchBound; -use crate::alloc::Allocator; +use crate::alloc::AllocatorClone; // `front` and `back` are always both `None` or both `Some`. pub(super) struct LeafRange { front: Option, marker::Edge>>, @@ -190,7 +190,7 @@ impl LazyLeafRange { } #[inline] - pub(super) unsafe fn deallocating_next_unchecked( + pub(super) unsafe fn deallocating_next_unchecked( &mut self, alloc: A, ) -> Handle, marker::KV> { @@ -200,7 +200,7 @@ impl LazyLeafRange { } #[inline] - pub(super) unsafe fn deallocating_next_back_unchecked( + pub(super) unsafe fn deallocating_next_back_unchecked( &mut self, alloc: A, ) -> Handle, marker::KV> { @@ -210,7 +210,7 @@ impl LazyLeafRange { } #[inline] - pub(super) fn deallocating_end(&mut self, alloc: A) { + pub(super) fn deallocating_end(&mut self, alloc: A) { if let Some(front) = self.take_front() { front.deallocating_end(alloc) } @@ -456,7 +456,7 @@ impl Handle, marker::Edge> { /// `deallocating_next_back`. /// - The returned KV handle is only valid to access the key and value, /// and only valid until the next call to a `deallocating_` method. - unsafe fn deallocating_next( + unsafe fn deallocating_next( self, alloc: A, ) -> Option<(Self, Handle, marker::KV>)> @@ -488,7 +488,7 @@ impl Handle, marker::Edge> { /// `deallocating_next`. /// - The returned KV handle is only valid to access the key and value, /// and only valid until the next call to a `deallocating_` method. - unsafe fn deallocating_next_back( + unsafe fn deallocating_next_back( self, alloc: A, ) -> Option<(Self, Handle, marker::KV>)> @@ -513,7 +513,7 @@ impl Handle, marker::Edge> { /// both sides of the tree, and have hit the same edge. As it is intended /// only to be called when all keys and values have been returned, /// no cleanup is done on any of the keys or values. - fn deallocating_end(self, alloc: A) { + fn deallocating_end(self, alloc: A) { let mut edge = self.forget_node_type(); while let Some(parent_edge) = unsafe { edge.into_node().deallocate_and_ascend(alloc.clone()) } @@ -592,7 +592,7 @@ impl Handle, marker::Edge> { /// /// The only safe way to proceed with the updated handle is to compare it, drop it, /// or call this method or counterpart `deallocating_next_back_unchecked` again. - unsafe fn deallocating_next_unchecked( + unsafe fn deallocating_next_unchecked( &mut self, alloc: A, ) -> Handle, marker::KV> { @@ -613,7 +613,7 @@ impl Handle, marker::Edge> { /// /// The only safe way to proceed with the updated handle is to compare it, drop it, /// or call this method or counterpart `deallocating_next_unchecked` again. - unsafe fn deallocating_next_back_unchecked( + unsafe fn deallocating_next_back_unchecked( &mut self, alloc: A, ) -> Handle, marker::KV> { diff --git a/library/alloc/src/collections/btree/node.rs b/library/alloc/src/collections/btree/node.rs index 0c7afcc63b9b7..8088fec38ed6a 100644 --- a/library/alloc/src/collections/btree/node.rs +++ b/library/alloc/src/collections/btree/node.rs @@ -37,7 +37,7 @@ use core::num::NonZero; use core::ptr::{self, NonNull}; use core::slice::SliceIndex; -use crate::alloc::{Allocator, Layout}; +use crate::alloc::{Allocator, AllocatorClone, Layout}; use crate::boxed::Box; const B: usize = 6; @@ -83,7 +83,7 @@ impl LeafNode { } /// Creates a new boxed `LeafNode`. - fn new(alloc: A) -> Box { + fn new(alloc: A) -> Box { let mut leaf = Box::new_uninit_in(alloc); unsafe { // SAFETY: `leaf` points to a `LeafNode` @@ -117,7 +117,7 @@ impl InternalNode { /// An invariant of internal nodes is that they have at least one /// initialized and valid edge. This function does not set up /// such an edge. - unsafe fn new(alloc: A) -> Box { + unsafe fn new(alloc: A) -> Box { let mut node = Box::::new_uninit_in(alloc); unsafe { // SAFETY: argument points to the `node.data` `LeafNode` @@ -221,11 +221,11 @@ unsafe impl Send for NodeRef unsafe impl Send for NodeRef {} impl NodeRef { - pub(super) fn new_leaf(alloc: A) -> Self { + pub(super) fn new_leaf(alloc: A) -> Self { Self::from_new_leaf(LeafNode::new(alloc)) } - fn from_new_leaf(leaf: Box, A>) -> Self { + fn from_new_leaf(leaf: Box, A>) -> Self { // The allocator must be dropped, not leaked. See also `BTreeMap::alloc`. let (node, _alloc) = Box::into_non_null_with_allocator(leaf); NodeRef { height: 0, node, _marker: PhantomData } @@ -234,14 +234,14 @@ impl NodeRef { impl NodeRef { /// Creates a new internal (height > 0) `NodeRef` - fn new_internal(child: Root, alloc: A) -> Self { + fn new_internal(child: Root, alloc: A) -> Self { let mut new_node = unsafe { InternalNode::new(alloc) }; new_node.edges[0].write(child.node); NodeRef::from_new_internal(new_node, NonZero::new(child.height + 1).unwrap()) } /// Creates a new internal (height > 0) `NodeRef` from an existing internal node - fn from_new_internal( + fn from_new_internal( internal: Box, A>, height: NonZero, ) -> Self { @@ -401,7 +401,7 @@ impl NodeRef { /// Similar to `ascend`, gets a reference to a node's parent node, but also /// deallocates the current node in the process. This is unsafe because the /// current node will still be accessible despite being deallocated. - pub(super) unsafe fn deallocate_and_ascend( + pub(super) unsafe fn deallocate_and_ascend( self, alloc: A, ) -> Option, marker::Edge>> { @@ -588,14 +588,14 @@ impl NodeRef { impl NodeRef { /// Returns a new owned tree, with its own root node that is initially empty. - pub(super) fn new(alloc: A) -> Self { + pub(super) fn new(alloc: A) -> Self { NodeRef::new_leaf(alloc).forget_type() } /// Adds a new internal node with a single edge pointing to the previous root node, /// make that new node the root node, and return it. This increases the height by 1 /// and is the opposite of `pop_internal_level`. - pub(super) fn push_internal_level( + pub(super) fn push_internal_level( &mut self, alloc: A, ) -> NodeRef, K, V, marker::Internal> { @@ -614,7 +614,7 @@ impl NodeRef { /// rooted at the first child of `self`. /// /// Panics if there is no internal level, i.e., if the root node is a leaf. - pub(super) fn pop_internal_level(&mut self, alloc: A) { + pub(super) fn pop_internal_level(&mut self, alloc: A) { assert!(self.height > 0); let top = self.node; @@ -950,7 +950,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, mark /// /// Returns a dormant handle to the inserted node which can be reawakened /// once splitting is complete. - fn insert( + fn insert( self, key: K, val: V, @@ -1017,7 +1017,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, /// Inserts a new key-value pair and an edge that will go to the right of that new pair /// between this edge and the key-value pair to the right of this edge. This method splits /// the node if there isn't enough room. - fn insert( + fn insert( mut self, key: K, val: V, @@ -1055,7 +1055,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, mark /// If the returned result is some `SplitResult`, the `left` field will be the root node. /// The returned pointer points to the inserted value, which in the case of `SplitResult` /// is in the `left` or `right` tree. - pub(super) fn insert_recursing( + pub(super) fn insert_recursing( self, key: K, value: V, @@ -1250,7 +1250,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, mark /// - The key and value pointed to by this handle are extracted. /// - All the key-value pairs to the right of this handle are put into a newly /// allocated node. - pub(super) fn split( + pub(super) fn split( mut self, alloc: A, ) -> SplitResult<'a, K, V, marker::Leaf> { @@ -1285,7 +1285,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, /// - The key and value pointed to by this handle are extracted. /// - All the edges and key-value pairs to the right of this handle are put into /// a newly allocated node. - pub(super) fn split( + pub(super) fn split( mut self, alloc: A, ) -> SplitResult<'a, K, V, marker::Internal> { @@ -1458,7 +1458,7 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { /// the left child node and returns the shrunk parent node. /// /// Panics unless we `.can_merge()`. - pub(super) fn merge_tracking_parent( + pub(super) fn merge_tracking_parent( self, alloc: A, ) -> NodeRef, K, V, marker::Internal> { @@ -1469,7 +1469,7 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { /// the left child node and returns that child node. /// /// Panics unless we `.can_merge()`. - pub(super) fn merge_tracking_child( + pub(super) fn merge_tracking_child( self, alloc: A, ) -> NodeRef, K, V, marker::LeafOrInternal> { @@ -1481,7 +1481,7 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { /// where the tracked child edge ended up, /// /// Panics unless we `.can_merge()`. - pub(super) fn merge_tracking_child_edge( + pub(super) fn merge_tracking_child_edge( self, track_edge_idx: LeftOrRight, alloc: A, diff --git a/library/alloc/src/collections/btree/remove.rs b/library/alloc/src/collections/btree/remove.rs index 9d870b86f34a0..b21c7e78b5bb3 100644 --- a/library/alloc/src/collections/btree/remove.rs +++ b/library/alloc/src/collections/btree/remove.rs @@ -1,4 +1,4 @@ -use core::alloc::Allocator; +use core::alloc::AllocatorClone; use super::map::MIN_LEN; use super::node::ForceResult::*; @@ -10,7 +10,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInter /// the leaf edge corresponding to that former pair. It's possible this empties /// a root node that is internal, which the caller should pop from the map /// holding the tree. The caller should also decrement the map's length. - pub(super) fn remove_kv_tracking( + pub(super) fn remove_kv_tracking( self, handle_emptied_internal_root: F, alloc: A, @@ -23,7 +23,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInter } impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { - fn remove_leaf_kv( + fn remove_leaf_kv( self, handle_emptied_internal_root: F, alloc: A, @@ -76,7 +76,7 @@ impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, mark } impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { - fn remove_internal_kv( + fn remove_internal_kv( self, handle_emptied_internal_root: F, alloc: A, diff --git a/library/alloc/src/collections/btree/set.rs b/library/alloc/src/collections/btree/set.rs index d06daa7c6c1b7..7c211e200f42d 100644 --- a/library/alloc/src/collections/btree/set.rs +++ b/library/alloc/src/collections/btree/set.rs @@ -10,7 +10,7 @@ use core::ops::{BitAnd, BitOr, BitXor, Bound, RangeBounds, Sub}; use super::map::{self, BTreeMap, Keys}; use super::merge_iter::MergeIterInner; use super::set_val::SetValZST; -use crate::alloc::{Allocator, Global}; +use crate::alloc::{AllocatorClone, Global}; use crate::vec::Vec; mod entry; @@ -77,44 +77,44 @@ pub use self::entry::{Entry, OccupiedEntry, VacantEntry}; #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeSet")] pub struct BTreeSet< T, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { map: BTreeMap, } #[stable(feature = "rust1", since = "1.0.0")] -impl Hash for BTreeSet { +impl Hash for BTreeSet { fn hash(&self, state: &mut H) { self.map.hash(state) } } #[stable(feature = "rust1", since = "1.0.0")] -impl PartialEq for BTreeSet { +impl PartialEq for BTreeSet { fn eq(&self, other: &BTreeSet) -> bool { self.map.eq(&other.map) } } #[stable(feature = "rust1", since = "1.0.0")] -impl Eq for BTreeSet {} +impl Eq for BTreeSet {} #[stable(feature = "rust1", since = "1.0.0")] -impl PartialOrd for BTreeSet { +impl PartialOrd for BTreeSet { fn partial_cmp(&self, other: &BTreeSet) -> Option { self.map.partial_cmp(&other.map) } } #[stable(feature = "rust1", since = "1.0.0")] -impl Ord for BTreeSet { +impl Ord for BTreeSet { fn cmp(&self, other: &BTreeSet) -> Ordering { self.map.cmp(&other.map) } } #[stable(feature = "rust1", since = "1.0.0")] -impl Clone for BTreeSet { +impl Clone for BTreeSet { fn clone(&self) -> Self { BTreeSet { map: self.map.clone() } } @@ -153,7 +153,7 @@ impl fmt::Debug for Iter<'_, T> { #[derive(Debug)] pub struct IntoIter< T, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { iter: super::map::IntoIter, } @@ -183,11 +183,11 @@ pub struct Range<'a, T: 'a> { pub struct Difference< 'a, T: 'a, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { inner: DifferenceInner<'a, T, A>, } -enum DifferenceInner<'a, T: 'a, A: Allocator + Clone> { +enum DifferenceInner<'a, T: 'a, A: AllocatorClone> { Stitch { // iterate all of `self` and some of `other`, spotting matches along the way self_iter: Iter<'a, T>, @@ -202,7 +202,7 @@ enum DifferenceInner<'a, T: 'a, A: Allocator + Clone> { } // Explicit Debug impl necessary because of issue #26925 -impl Debug for DifferenceInner<'_, T, A> { +impl Debug for DifferenceInner<'_, T, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { DifferenceInner::Stitch { self_iter, other_iter } => f @@ -221,7 +221,7 @@ impl Debug for DifferenceInner<'_, T, A> { } #[stable(feature = "collection_debug", since = "1.17.0")] -impl fmt::Debug for Difference<'_, T, A> { +impl fmt::Debug for Difference<'_, T, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("Difference").field(&self.inner).finish() } @@ -257,11 +257,11 @@ impl fmt::Debug for SymmetricDifference<'_, T> { pub struct Intersection< 'a, T: 'a, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { inner: IntersectionInner<'a, T, A>, } -enum IntersectionInner<'a, T: 'a, A: Allocator + Clone> { +enum IntersectionInner<'a, T: 'a, A: AllocatorClone> { Stitch { // iterate similarly sized sets jointly, spotting matches along the way a: Iter<'a, T>, @@ -276,7 +276,7 @@ enum IntersectionInner<'a, T: 'a, A: Allocator + Clone> { } // Explicit Debug impl necessary because of issue #26925 -impl Debug for IntersectionInner<'_, T, A> { +impl Debug for IntersectionInner<'_, T, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { IntersectionInner::Stitch { a, b } => { @@ -293,7 +293,7 @@ impl Debug for IntersectionInner<'_, T, A> { } #[stable(feature = "collection_debug", since = "1.17.0")] -impl Debug for Intersection<'_, T, A> { +impl Debug for Intersection<'_, T, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("Intersection").field(&self.inner).finish() } @@ -346,7 +346,7 @@ impl BTreeSet { } } -impl BTreeSet { +impl BTreeSet { /// Makes a new `BTreeSet` with a reasonable choice of B. /// /// # Examples @@ -901,7 +901,7 @@ impl BTreeSet { where T: Ord, { - self.map.insert(value, SetValZST::default()).is_none() + self.map.insert(value, SetValZST).is_none() } /// Adds a value to the set, replacing the existing element, if any, that is @@ -1481,9 +1481,9 @@ impl FromIterator for BTreeSet { } } -impl BTreeSet { +impl BTreeSet { fn from_sorted_iter>(iter: I, alloc: A) -> BTreeSet { - let iter = iter.map(|k| (k, SetValZST::default())); + let iter = iter.map(|k| (k, SetValZST)); let map = BTreeMap::bulk_build_from_sorted_iter(iter, alloc); BTreeSet { map } } @@ -1517,7 +1517,7 @@ impl From<[T; N]> for BTreeSet { } #[stable(feature = "rust1", since = "1.0.0")] -impl IntoIterator for BTreeSet { +impl IntoIterator for BTreeSet { type Item = T; type IntoIter = IntoIter; @@ -1539,7 +1539,7 @@ impl IntoIterator for BTreeSet { } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, T, A: Allocator + Clone> IntoIterator for &'a BTreeSet { +impl<'a, T, A: AllocatorClone> IntoIterator for &'a BTreeSet { type Item = &'a T; type IntoIter = Iter<'a, T>; @@ -1559,7 +1559,7 @@ pub struct ExtractIf< T, R, F, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { pred: F, inner: super::map::ExtractIfInner<'a, T, SetValZST, R>, @@ -1571,7 +1571,7 @@ pub struct ExtractIf< impl fmt::Debug for ExtractIf<'_, T, R, F, A> where T: fmt::Debug, - A: Allocator + Clone, + A: AllocatorClone, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ExtractIf") @@ -1581,7 +1581,7 @@ where } #[stable(feature = "btree_extract_if", since = "1.91.0")] -impl Iterator for ExtractIf<'_, T, R, F, A> +impl Iterator for ExtractIf<'_, T, R, F, A> where T: PartialOrd, R: RangeBounds, @@ -1601,7 +1601,7 @@ where } #[stable(feature = "btree_extract_if", since = "1.91.0")] -impl FusedIterator for ExtractIf<'_, T, R, F, A> +impl FusedIterator for ExtractIf<'_, T, R, F, A> where T: PartialOrd, R: RangeBounds, @@ -1610,7 +1610,7 @@ where } #[stable(feature = "rust1", since = "1.0.0")] -impl Extend for BTreeSet { +impl Extend for BTreeSet { #[inline] fn extend>(&mut self, iter: Iter) { iter.into_iter().for_each(move |elem| { @@ -1625,7 +1625,7 @@ impl Extend for BTreeSet { } #[stable(feature = "extend_ref", since = "1.2.0")] -impl<'a, T: 'a + Ord + Copy, A: Allocator + Clone> Extend<&'a T> for BTreeSet { +impl<'a, T: 'a + Ord + Copy, A: AllocatorClone> Extend<&'a T> for BTreeSet { fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } @@ -1645,7 +1645,7 @@ impl Default for BTreeSet { } #[stable(feature = "rust1", since = "1.0.0")] -impl Sub<&BTreeSet> for &BTreeSet { +impl Sub<&BTreeSet> for &BTreeSet { type Output = BTreeSet; /// Returns the difference of `self` and `rhs` as a new `BTreeSet`. @@ -1670,7 +1670,7 @@ impl Sub<&BTreeSet> for &BTreeSet BitXor<&BTreeSet> for &BTreeSet { +impl BitXor<&BTreeSet> for &BTreeSet { type Output = BTreeSet; /// Returns the symmetric difference of `self` and `rhs` as a new `BTreeSet`. @@ -1695,7 +1695,7 @@ impl BitXor<&BTreeSet> for &BTreeSet } #[stable(feature = "rust1", since = "1.0.0")] -impl BitAnd<&BTreeSet> for &BTreeSet { +impl BitAnd<&BTreeSet> for &BTreeSet { type Output = BTreeSet; /// Returns the intersection of `self` and `rhs` as a new `BTreeSet`. @@ -1720,7 +1720,7 @@ impl BitAnd<&BTreeSet> for &BTreeSet } #[stable(feature = "rust1", since = "1.0.0")] -impl BitOr<&BTreeSet> for &BTreeSet { +impl BitOr<&BTreeSet> for &BTreeSet { type Output = BTreeSet; /// Returns the union of `self` and `rhs` as a new `BTreeSet`. @@ -1745,7 +1745,7 @@ impl BitOr<&BTreeSet> for &BTreeSet< } #[stable(feature = "rust1", since = "1.0.0")] -impl Debug for BTreeSet { +impl Debug for BTreeSet { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_set().entries(self.iter()).finish() } @@ -1810,7 +1810,7 @@ unsafe impl TrustedLen for Iter<'_, T> {} impl FusedIterator for Iter<'_, T> {} #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for IntoIter { +impl Iterator for IntoIter { type Item = T; fn next(&mut self) -> Option { @@ -1837,29 +1837,29 @@ impl Default for Iter<'_, T> { } #[stable(feature = "rust1", since = "1.0.0")] -impl DoubleEndedIterator for IntoIter { +impl DoubleEndedIterator for IntoIter { fn next_back(&mut self) -> Option { self.iter.next_back().map(|(k, _)| k) } } #[stable(feature = "rust1", since = "1.0.0")] -impl ExactSizeIterator for IntoIter { +impl ExactSizeIterator for IntoIter { fn len(&self) -> usize { self.iter.len() } } #[unstable(feature = "trusted_len", issue = "37572")] -unsafe impl TrustedLen for IntoIter {} +unsafe impl TrustedLen for IntoIter {} #[stable(feature = "fused", since = "1.26.0")] -impl FusedIterator for IntoIter {} +impl FusedIterator for IntoIter {} #[stable(feature = "default_iters", since = "1.70.0")] impl Default for IntoIter where - A: Allocator + Default + Clone, + A: AllocatorClone + Default, { /// Creates an empty `btree_set::IntoIter`. /// @@ -1932,7 +1932,7 @@ impl Default for Range<'_, T> { } #[stable(feature = "rust1", since = "1.0.0")] -impl Clone for Difference<'_, T, A> { +impl Clone for Difference<'_, T, A> { fn clone(&self) -> Self { Difference { inner: match &self.inner { @@ -1949,7 +1949,7 @@ impl Clone for Difference<'_, T, A> { } } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, T: Ord, A: Allocator + Clone> Iterator for Difference<'a, T, A> { +impl<'a, T: Ord, A: AllocatorClone> Iterator for Difference<'a, T, A> { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { @@ -1996,7 +1996,7 @@ impl<'a, T: Ord, A: Allocator + Clone> Iterator for Difference<'a, T, A> { } #[stable(feature = "fused", since = "1.26.0")] -impl FusedIterator for Difference<'_, T, A> {} +impl FusedIterator for Difference<'_, T, A> {} #[stable(feature = "rust1", since = "1.0.0")] impl Clone for SymmetricDifference<'_, T> { @@ -2034,7 +2034,7 @@ impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> { impl FusedIterator for SymmetricDifference<'_, T> {} #[stable(feature = "rust1", since = "1.0.0")] -impl Clone for Intersection<'_, T, A> { +impl Clone for Intersection<'_, T, A> { fn clone(&self) -> Self { Intersection { inner: match &self.inner { @@ -2050,7 +2050,7 @@ impl Clone for Intersection<'_, T, A> { } } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, T: Ord, A: Allocator + Clone> Iterator for Intersection<'a, T, A> { +impl<'a, T: Ord, A: AllocatorClone> Iterator for Intersection<'a, T, A> { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { @@ -2091,7 +2091,7 @@ impl<'a, T: Ord, A: Allocator + Clone> Iterator for Intersection<'a, T, A> { } #[stable(feature = "fused", since = "1.26.0")] -impl FusedIterator for Intersection<'_, T, A> {} +impl FusedIterator for Intersection<'_, T, A> {} #[stable(feature = "rust1", since = "1.0.0")] impl Clone for Union<'_, T> { @@ -2356,7 +2356,7 @@ impl<'a, T, A> CursorMutKey<'a, T, A> { } } -impl<'a, T: Ord, A: Allocator + Clone> CursorMut<'a, T, A> { +impl<'a, T: Ord, A: AllocatorClone> CursorMut<'a, T, A> { /// Inserts a new element into the set in the gap that the /// cursor is currently pointing to. /// @@ -2442,7 +2442,7 @@ impl<'a, T: Ord, A: Allocator + Clone> CursorMut<'a, T, A> { } } -impl<'a, T: Ord, A: Allocator + Clone> CursorMutKey<'a, T, A> { +impl<'a, T: Ord, A: AllocatorClone> CursorMutKey<'a, T, A> { /// Inserts a new element into the set in the gap that the /// cursor is currently pointing to. /// diff --git a/library/alloc/src/collections/btree/set/entry.rs b/library/alloc/src/collections/btree/set/entry.rs index a60d22f9ece71..89bc09bca2f5c 100644 --- a/library/alloc/src/collections/btree/set/entry.rs +++ b/library/alloc/src/collections/btree/set/entry.rs @@ -3,7 +3,7 @@ use core::fmt::{self, Debug}; use Entry::*; use super::{SetValZST, map}; -use crate::alloc::{Allocator, Global}; +use crate::alloc::{AllocatorClone, Global}; /// A view into a single entry in a set, which may either be vacant or occupied. /// @@ -42,7 +42,7 @@ use crate::alloc::{Allocator, Global}; pub enum Entry< 'a, T, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { /// An occupied entry. /// @@ -84,7 +84,7 @@ pub enum Entry< } #[unstable(feature = "btree_set_entry", issue = "133549")] -impl Debug for Entry<'_, T, A> { +impl Debug for Entry<'_, T, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(), @@ -133,13 +133,13 @@ impl Debug for Entry<'_, T, A> { pub struct OccupiedEntry< 'a, T, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { pub(super) inner: map::OccupiedEntry<'a, T, SetValZST, A>, } #[unstable(feature = "btree_set_entry", issue = "133549")] -impl Debug for OccupiedEntry<'_, T, A> { +impl Debug for OccupiedEntry<'_, T, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("OccupiedEntry").field("value", self.get()).finish() } @@ -175,19 +175,19 @@ impl Debug for OccupiedEntry<'_, T, A> { pub struct VacantEntry< 'a, T, - #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global, + #[unstable(feature = "allocator_api", issue = "32838")] A: AllocatorClone = Global, > { pub(super) inner: map::VacantEntry<'a, T, SetValZST, A>, } #[unstable(feature = "btree_set_entry", issue = "133549")] -impl Debug for VacantEntry<'_, T, A> { +impl Debug for VacantEntry<'_, T, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("VacantEntry").field(self.get()).finish() } } -impl<'a, T: Ord, A: Allocator + Clone> Entry<'a, T, A> { +impl<'a, T: Ord, A: AllocatorClone> Entry<'a, T, A> { /// Sets the value of the entry, and returns an `OccupiedEntry`. /// /// # Examples @@ -266,7 +266,7 @@ impl<'a, T: Ord, A: Allocator + Clone> Entry<'a, T, A> { } } -impl<'a, T: Ord, A: Allocator + Clone> OccupiedEntry<'a, T, A> { +impl<'a, T: Ord, A: AllocatorClone> OccupiedEntry<'a, T, A> { /// Gets a reference to the value in the entry. /// /// # Examples @@ -316,7 +316,7 @@ impl<'a, T: Ord, A: Allocator + Clone> OccupiedEntry<'a, T, A> { } } -impl<'a, T: Ord, A: Allocator + Clone> VacantEntry<'a, T, A> { +impl<'a, T: Ord, A: AllocatorClone> VacantEntry<'a, T, A> { /// Gets a reference to the value that would be used when inserting /// through the `VacantEntry`. /// diff --git a/library/alloc/src/collections/btree/split.rs b/library/alloc/src/collections/btree/split.rs index 87a79e6cf3f93..5d5f379c2da44 100644 --- a/library/alloc/src/collections/btree/split.rs +++ b/library/alloc/src/collections/btree/split.rs @@ -1,4 +1,4 @@ -use core::alloc::Allocator; +use core::alloc::AllocatorClone; use core::borrow::Borrow; use super::node::ForceResult::*; @@ -31,7 +31,7 @@ impl Root { /// and if the ordering of `Q` corresponds to that of `K`. /// If `self` respects all `BTreeMap` tree invariants, then both /// `self` and the returned tree will respect those invariants. - pub(super) fn split_off( + pub(super) fn split_off( &mut self, key: &Q, alloc: A, @@ -69,7 +69,7 @@ impl Root { } /// Creates a tree consisting of empty nodes. - fn new_pillar(height: usize, alloc: A) -> Self { + fn new_pillar(height: usize, alloc: A) -> Self { let mut root = Root::new(alloc.clone()); for _ in 0..height { root.push_internal_level(alloc.clone()); diff --git a/library/alloc/src/collections/linked_list.rs b/library/alloc/src/collections/linked_list.rs index 8939b2f12f49c..a0542d2b5737c 100644 --- a/library/alloc/src/collections/linked_list.rs +++ b/library/alloc/src/collections/linked_list.rs @@ -369,7 +369,7 @@ impl LinkedList { // Fix the head ptr of the second part self.head = Some(split_node); - self.len = self.len - at; + self.len -= at; first_part } else { diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index 9095fc0d4abf4..b007e3054ee6a 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -2049,6 +2049,7 @@ impl VecDeque { /// assert!(deque.is_empty()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] + #[expect(clippy::manual_clear, reason = "implements clear")] #[inline] pub fn clear(&mut self) { self.truncate(0); @@ -3312,7 +3313,7 @@ impl VecDeque { F: FnMut(&'a T) -> Ordering, { let (front, back) = self.as_slices(); - let cmp_back = back.first().map(|elem| f(elem)); + let cmp_back = back.first().map(&mut f); if let Some(Ordering::Equal) = cmp_back { Ok(front.len()) @@ -3423,7 +3424,7 @@ impl VecDeque { { let (front, back) = self.as_slices(); - if let Some(true) = back.first().map(|v| pred(v)) { + if let Some(true) = back.first().map(&mut pred) { back.partition_point(pred) + front.len() } else { front.partition_point(pred) diff --git a/library/alloc/src/io/buffered/bufreader.rs b/library/alloc/src/io/buffered/bufreader.rs index e8b3302e29b98..e8be1abc56e17 100644 --- a/library/alloc/src/io/buffered/bufreader.rs +++ b/library/alloc/src/io/buffered/bufreader.rs @@ -153,7 +153,7 @@ impl BufReader { let new = self.buf.read_more(&mut self.inner)?; if new == 0 { // end of file, no more bytes to read - return Ok(&self.buf.buffer()[..]); + return Ok(self.buf.buffer()); } debug_assert_eq!(self.buf.pos(), 0); } diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index 2b0b1ade64087..89b15a169dce0 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -59,6 +59,7 @@ #![allow(unused_features)] #![allow(incomplete_features)] #![allow(unused_attributes)] +#![expect(clippy::partialeq_ne_impl, reason = "we need to implement ne for a lot of alloc types")] #![stable(feature = "alloc", since = "1.36.0")] #![doc( html_playground_url = "https://play.rust-lang.org/", diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 8d954d90c615d..37714859ede38 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -1266,7 +1266,6 @@ impl Rc<[T], A> { /// ``` #[unstable(feature = "alloc_slice_into_array", issue = "148082")] #[inline] - #[must_use] pub fn into_array(self) -> Result, Self> { if self.len() == N { let (ptr, alloc) = Self::into_raw_with_allocator(self); diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index e72449d670ed2..cca6f881e1740 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -1425,7 +1425,6 @@ impl Arc<[T], A> { /// ``` #[unstable(feature = "alloc_slice_into_array", issue = "148082")] #[inline] - #[must_use] pub fn into_array(self) -> Result, Self> { if self.len() == N { let (ptr, alloc) = Self::into_raw_with_allocator(self); diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 94b21334c120c..bd15ec798460f 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -1749,7 +1749,6 @@ impl Vec { /// ``` #[cfg(not(no_global_oom_handling))] #[unstable(feature = "alloc_slice_into_array", issue = "148082")] - #[must_use] pub fn into_array(self) -> Result, Self> { if self.len() == N { // SAFETY: `Box::into_array` is guaranteed to return `Ok` if the diff --git a/library/core/src/ascii/ascii_char.rs b/library/core/src/ascii/ascii_char.rs index de1adf9c9ec7c..801144826a2ed 100644 --- a/library/core/src/ascii/ascii_char.rs +++ b/library/core/src/ascii/ascii_char.rs @@ -635,7 +635,7 @@ impl AsciiChar { pub const fn eq_ignore_case(self, other: Self) -> bool { // FIXME(const-hack) `arg.to_u8().to_ascii_lowercase()` -> `arg.to_lowercase()` // once `PartialEq` is const for `Self`. - self.to_u8().to_ascii_lowercase() == other.to_u8().to_ascii_lowercase() + self.to_u8().eq_ignore_ascii_case(&other.to_u8()) } /// Converts this value to its upper case equivalent in-place. diff --git a/library/core/src/char/methods.rs b/library/core/src/char/methods.rs index f6930e0a60d42..ad0ae512f0f72 100644 --- a/library/core/src/char/methods.rs +++ b/library/core/src/char/methods.rs @@ -1,5 +1,7 @@ //! impl char {} +#![expect(clippy::manual_is_ascii_check, reason = "this module implements various is_ascii checks")] + use super::*; use crate::panic::const_panic; use crate::slice; @@ -343,6 +345,7 @@ impl char { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")] + #[expect(clippy::to_digit_is_some, reason = "implements is_digit")] #[inline] pub const fn is_digit(self, radix: u32) -> bool { self.to_digit(radix).is_some() @@ -1985,6 +1988,7 @@ impl char { /// [to_ascii_lowercase]: #method.to_ascii_lowercase #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")] + #[expect(clippy::manual_ignore_case_cmp, reason = "implements eq_ignore_ascii_case")] #[inline] pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool { self.to_ascii_lowercase() == other.to_ascii_lowercase() diff --git a/library/core/src/field.rs b/library/core/src/field.rs index 915a4c07b9e23..5a8ae7759bc1e 100644 --- a/library/core/src/field.rs +++ b/library/core/src/field.rs @@ -78,7 +78,7 @@ impl Default for FieldRepresentingType { fn default() -> Self { - Self { _phantom: PhantomData::default() } + Self { _phantom: PhantomData } } } diff --git a/library/core/src/hash/mod.rs b/library/core/src/hash/mod.rs index c7c8d57e1010d..f1a93a880e7f4 100644 --- a/library/core/src/hash/mod.rs +++ b/library/core/src/hash/mod.rs @@ -691,6 +691,7 @@ pub trait BuildHasher { /// ); /// ``` #[stable(feature = "build_hasher_simple_hash_one", since = "1.71.0")] + #[expect(clippy::manual_hash_one, reason = "implements hash_one")] fn hash_one(&self, x: T) -> u64 where Self: Sized, diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 2316fc4318918..673454abaf04f 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -2915,14 +2915,9 @@ pub const fn contract_check_ensures bool + Copy, Ret>( // Do nothing ret } else { - match cond { - crate::option::Option::Some(cond) => { - if !cond(&ret) { - // Emit no unwind panic in case this was a safety requirement. - crate::panicking::panic_nounwind("failed ensures check"); - } - }, - crate::option::Option::None => {}, + if let crate::option::Option::Some(cond) = cond && !cond(&ret) { + // Emit no unwind panic in case this was a safety requirement. + crate::panicking::panic_nounwind("failed ensures check"); } ret } diff --git a/library/core/src/io/error.rs b/library/core/src/io/error.rs index 8491a42537092..c0de8822b456b 100644 --- a/library/core/src/io/error.rs +++ b/library/core/src/io/error.rs @@ -234,7 +234,6 @@ impl Error { #[doc(hidden)] #[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")] - #[must_use] #[inline] pub fn into_custom_owner(self) -> result::Result { if matches!(self.repr.data(), ErrorData::Custom(..)) { diff --git a/library/core/src/io/seek.rs b/library/core/src/io/seek.rs index 4c242c761dfe6..d24bf5ffb4024 100644 --- a/library/core/src/io/seek.rs +++ b/library/core/src/io/seek.rs @@ -142,6 +142,7 @@ pub trait Seek { /// } /// ``` #[stable(feature = "seek_convenience", since = "1.51.0")] + #[expect(clippy::seek_from_current, reason = "implements stream_position")] fn stream_position(&mut self) -> Result { self.seek(SeekFrom::Current(0)) } diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 89ae9179f4e25..4fbd3c6dc2142 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -186,6 +186,10 @@ #![feature(x86_amx_intrinsics)] // tidy-alphabetical-end +// tidy-alphabetical-start +#![expect(clippy::partialeq_ne_impl, reason = "we need to implement ne for a lot of core types")] +// tidy-alphabetical-end + // allow using `core::` in intra-doc links #[allow(unused_extern_crates)] extern crate self as core; @@ -359,7 +363,9 @@ pub mod primitive; unsafe_op_in_unsafe_fn, ambiguous_glob_reexports, deprecated_in_future, - unreachable_pub + unreachable_pub, + // FIXME: stdach is a submodule so clippy lints should be fixed (and ideally enforced) there + clippy::all, )] #[allow(rustdoc::bare_urls)] mod core_arch; diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs index 45b4b80e9e268..d52e817c9e3db 100644 --- a/library/core/src/num/f128.rs +++ b/library/core/src/num/f128.rs @@ -10,6 +10,7 @@ //! defined directly on the `f128` type. #![unstable(feature = "f128", issue = "116909")] +#![expect(clippy::approx_constant, reason = "this module defines f128 constants")] use crate::convert::{FloatToFloat, FloatToInt}; use crate::num::FpCategory; @@ -1499,6 +1500,7 @@ impl f128 { #[inline] #[unstable(feature = "f128", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")] pub const fn clamp(mut self, min: f128, max: f128) -> f128 { const_assert!( min <= max, @@ -1543,8 +1545,9 @@ impl f128 { #[inline] #[unstable(feature = "clamp_magnitude", issue = "148519")] #[must_use = "this returns the clamped value and does not modify the original"] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")] pub fn clamp_magnitude(self, limit: f128) -> f128 { - assert!(limit >= 0.0, "limit must be non-negative"); + assert!(limit >= 0.0, "limit must be non-negative and not NaN"); let limit = limit.abs(); // Canonicalises -0.0 to 0.0 self.clamp(-limit, limit) } diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs index e8f2e37f93c67..186e83a9cd6b5 100644 --- a/library/core/src/num/f16.rs +++ b/library/core/src/num/f16.rs @@ -10,6 +10,7 @@ //! defined directly on the `f16` type. #![unstable(feature = "f16", issue = "116909")] +#![expect(clippy::approx_constant, reason = "this module defines f16 constants")] use crate::convert::{FloatToFloat, FloatToInt}; use crate::num::FpCategory; @@ -1485,6 +1486,7 @@ impl f16 { #[inline] #[unstable(feature = "f16", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")] pub const fn clamp(mut self, min: f16, max: f16) -> f16 { const_assert!( min <= max, @@ -1529,8 +1531,9 @@ impl f16 { #[inline] #[unstable(feature = "clamp_magnitude", issue = "148519")] #[must_use = "this returns the clamped value and does not modify the original"] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")] pub fn clamp_magnitude(self, limit: f16) -> f16 { - assert!(limit >= 0.0, "limit must be non-negative"); + assert!(limit >= 0.0, "limit must be non-negative and not NaN"); let limit = limit.abs(); // Canonicalises -0.0 to 0.0 self.clamp(-limit, limit) } diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs index 723e64aa9ac54..3c6b58a2b4b25 100644 --- a/library/core/src/num/f32.rs +++ b/library/core/src/num/f32.rs @@ -10,6 +10,7 @@ //! defined directly on the `f32` type. #![stable(feature = "rust1", since = "1.0.0")] +#![expect(clippy::approx_constant, reason = "this module defines f32 constants")] use crate::convert::{FloatToFloat, FloatToInt}; use crate::num::FpCategory; @@ -438,7 +439,7 @@ impl f32 { /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS #[stable(feature = "assoc_int_consts", since = "1.43.0")] #[rustc_diagnostic_item = "f32_epsilon"] - pub const EPSILON: f32 = 1.19209290e-07_f32; + pub const EPSILON: f32 = 1.1920929e-07_f32; /// Smallest finite `f32` value. /// @@ -446,14 +447,14 @@ impl f32 { /// /// [`MAX`]: f32::MAX #[stable(feature = "assoc_int_consts", since = "1.43.0")] - pub const MIN: f32 = -3.40282347e+38_f32; + pub const MIN: f32 = -3.4028235e+38_f32; /// Smallest positive normal `f32` value. /// /// Equal to 2[`MIN_EXP`] − 1. /// /// [`MIN_EXP`]: f32::MIN_EXP #[stable(feature = "assoc_int_consts", since = "1.43.0")] - pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32; + pub const MIN_POSITIVE: f32 = 1.1754944e-38_f32; /// Largest finite `f32` value. /// /// Equal to @@ -462,7 +463,7 @@ impl f32 { /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS /// [`MAX_EXP`]: f32::MAX_EXP #[stable(feature = "assoc_int_consts", since = "1.43.0")] - pub const MAX: f32 = 3.40282347e+38_f32; + pub const MAX: f32 = 3.4028235e+38_f32; /// One greater than the minimum possible *normal* power of 2 exponent /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition). @@ -1659,6 +1660,7 @@ impl f32 { #[stable(feature = "clamp", since = "1.50.0")] #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "Nan is also invalid")] pub const fn clamp(mut self, min: f32, max: f32) -> f32 { const_assert!( min <= max, @@ -1700,8 +1702,9 @@ impl f32 { #[must_use = "this returns the clamped value and does not modify the original"] #[unstable(feature = "clamp_magnitude", issue = "148519")] #[inline] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")] pub fn clamp_magnitude(self, limit: f32) -> f32 { - assert!(limit >= 0.0, "limit must be non-negative"); + assert!(limit >= 0.0, "limit must be non-negative and not NaN"); let limit = limit.abs(); // Canonicalises -0.0 to 0.0 self.clamp(-limit, limit) } diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs index d23b3e5616302..8c433a5cf941d 100644 --- a/library/core/src/num/f64.rs +++ b/library/core/src/num/f64.rs @@ -10,6 +10,7 @@ //! defined directly on the `f64` type. #![stable(feature = "rust1", since = "1.0.0")] +#![expect(clippy::approx_constant, reason = "this module defines f64 constants")] use crate::convert::{FloatToFloat, FloatToInt}; use crate::num::FpCategory; @@ -437,7 +438,7 @@ impl f64 { /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS #[stable(feature = "assoc_int_consts", since = "1.43.0")] #[rustc_diagnostic_item = "f64_epsilon"] - pub const EPSILON: f64 = 2.2204460492503131e-16_f64; + pub const EPSILON: f64 = 2.220446049250313e-16_f64; /// Smallest finite `f64` value. /// @@ -1637,6 +1638,7 @@ impl f64 { #[stable(feature = "clamp", since = "1.50.0")] #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")] pub const fn clamp(mut self, min: f64, max: f64) -> f64 { const_assert!( min <= max, @@ -1678,8 +1680,9 @@ impl f64 { #[must_use = "this returns the clamped value and does not modify the original"] #[unstable(feature = "clamp_magnitude", issue = "148519")] #[inline] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")] pub fn clamp_magnitude(self, limit: f64) -> f64 { - assert!(limit >= 0.0, "limit must be non-negative"); + assert!(limit >= 0.0, "limit must be non-negative and not NaN"); let limit = limit.abs(); // Canonicalises -0.0 to 0.0 self.clamp(-limit, limit) } diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index 3fe7b95283446..db41d23770477 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -1,6 +1,7 @@ //! Numeric traits and functions for the built-in numeric types. #![stable(feature = "rust1", since = "1.0.0")] +#![expect(clippy::manual_is_ascii_check, reason = "this module implements various is_ascii checks")] use crate::convert::{BoundedCastFromInt, CheckedCastFromInt}; use crate::panic::const_panic; @@ -731,6 +732,7 @@ impl u8 { /// ``` #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")] + #[expect(clippy::manual_ignore_case_cmp, reason = "implements eq_ignore_ascii_case")] #[inline] pub const fn eq_ignore_ascii_case(&self, other: &u8) -> bool { self.to_ascii_lowercase() == other.to_ascii_lowercase() diff --git a/library/core/src/ops/range.rs b/library/core/src/ops/range.rs index ebb6c3ddb938c..19830365faa32 100644 --- a/library/core/src/ops/range.rs +++ b/library/core/src/ops/range.rs @@ -148,6 +148,7 @@ impl> Range { #[inline] #[stable(feature = "range_is_empty", since = "1.47.0")] #[rustc_const_unstable(feature = "const_range", issue = "none")] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "incomparable ranges are empty")] pub const fn is_empty(&self) -> bool where Idx: [const] PartialOrd, @@ -568,6 +569,7 @@ impl> RangeInclusive { #[stable(feature = "range_is_empty", since = "1.47.0")] #[inline] #[rustc_const_unstable(feature = "const_range", issue = "none")] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "incomparable ranges are empty")] pub const fn is_empty(&self) -> bool where Idx: [const] PartialOrd, diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 5d86f851dbd1d..201019037148d 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -737,6 +737,7 @@ impl Option { /// println!("still can print text: {text:?}"); /// ``` #[inline] + #[expect(clippy::match_as_ref, reason = "implements as_ref")] #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")] #[stable(feature = "rust1", since = "1.0.0")] pub const fn as_ref(&self) -> Option<&T> { @@ -759,6 +760,7 @@ impl Option { /// assert_eq!(x, Some(42)); /// ``` #[inline] + #[expect(clippy::match_as_ref, reason = "implements as_mut")] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_option", since = "1.83.0")] pub const fn as_mut(&mut self) -> Option<&mut T> { @@ -1823,7 +1825,7 @@ impl Option { // It could also be expressed as `unsafe { core::ptr::write(self, Some(f())) }`, but // no reason is currently known to use additional unsafe code here. - mem::forget(mem::replace(self, Some(f()))); + mem::forget(self.replace(f())); } // SAFETY: a `None` variant for `self` would have been replaced by a `Some` @@ -1896,6 +1898,7 @@ impl Option { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_option", since = "1.83.0")] + #[expect(clippy::mem_replace_option_with_none, reason = "implements Option::take")] pub const fn take(&mut self) -> Option { // FIXME(const-hack) replace `mem::replace` by `mem::take` when the latter is const ready mem::replace(self, None) @@ -1932,7 +1935,7 @@ impl Option { where P: [const] FnOnce(&mut T) -> bool + [const] Destruct, { - if self.as_mut().map_or(false, predicate) { self.take() } else { None } + if self.as_mut().is_some_and(predicate) { self.take() } else { None } } /// Replaces the actual value in the option by the value given in parameter, @@ -1955,6 +1958,7 @@ impl Option { #[inline] #[stable(feature = "option_replace", since = "1.31.0")] #[rustc_const_stable(feature = "const_option", since = "1.83.0")] + #[expect(clippy::mem_replace_option_with_some, reason = "implements Option::replace")] pub const fn replace(&mut self, value: T) -> Option { mem::replace(self, Some(value)) } @@ -2154,6 +2158,7 @@ impl Option<&T> { /// ``` #[must_use = "`self` will be dropped if the result is not used"] #[stable(feature = "rust1", since = "1.0.0")] + #[expect(clippy::map_clone, reason = "implements Option::cloned")] pub fn cloned(self) -> Option where T: Clone, @@ -2206,7 +2211,7 @@ impl Option<&mut T> { where T: Clone, { - self.as_deref().map(T::clone) + self.as_deref().cloned() } } diff --git a/library/core/src/panicking.rs b/library/core/src/panicking.rs index 46790b620127b..04722e4e2fc10 100644 --- a/library/core/src/panicking.rs +++ b/library/core/src/panicking.rs @@ -445,14 +445,14 @@ fn assert_failed_inner( match args { Some(args) => panic!( - r#"assertion `left {op} right` failed: {args} + r"assertion `left {op} right` failed: {args} left: {left:?} - right: {right:?}"# + right: {right:?}" ), None => panic!( - r#"assertion `left {op} right` failed + r"assertion `left {op} right` failed left: {left:?} - right: {right:?}"# + right: {right:?}" ), } } diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 5601621f1408e..06e7bbb91bbab 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -149,6 +149,7 @@ impl *const T { #[doc = include_str!("./docs/addr.md")] #[must_use] #[inline(always)] + #[expect(clippy::transmutes_expressible_as_ptr_casts, reason = "implements pointer cast")] #[stable(feature = "strict_provenance", since = "1.84.0")] pub fn addr(self) -> usize { // A pointer-to-integer transmute currently has exactly the right semantics: it returns the diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index 76eca86612a82..31e14fce4429a 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -140,6 +140,7 @@ impl *mut T { /// [without_provenance]: without_provenance_mut #[must_use] #[inline(always)] + #[expect(clippy::transmutes_expressible_as_ptr_casts, reason = "implements pointer cast")] #[stable(feature = "strict_provenance", since = "1.84.0")] pub fn addr(self) -> usize { // A pointer-to-integer transmute currently has exactly the right semantics: it returns the diff --git a/library/core/src/range.rs b/library/core/src/range.rs index 557587b4e9a88..81f4b2ce78c9c 100644 --- a/library/core/src/range.rs +++ b/library/core/src/range.rs @@ -162,6 +162,7 @@ impl> Range { #[inline] #[stable(feature = "new_range_api", since = "1.96.0")] #[rustc_const_unstable(feature = "const_range", issue = "none")] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "incomparable ranges are empty")] pub const fn is_empty(&self) -> bool where Idx: [const] PartialOrd, @@ -320,6 +321,7 @@ impl> RangeInclusive { #[stable(feature = "new_range_inclusive_api", since = "1.95.0")] #[inline] #[rustc_const_unstable(feature = "const_range", issue = "none")] + #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "incomparable ranges are empty")] pub const fn is_empty(&self) -> bool where Idx: [const] PartialOrd, diff --git a/library/core/src/result.rs b/library/core/src/result.rs index c38008cf73d2b..544282d942148 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1736,6 +1736,7 @@ impl Result<&T, E> { /// ``` #[inline] #[stable(feature = "result_cloned", since = "1.59.0")] + #[expect(clippy::map_clone, reason = "implements Result::cloned")] pub fn cloned(self) -> Result where T: Clone, diff --git a/library/core/src/slice/ascii.rs b/library/core/src/slice/ascii.rs index 2b6037b2ee53e..07920a36e6eda 100644 --- a/library/core/src/slice/ascii.rs +++ b/library/core/src/slice/ascii.rs @@ -666,10 +666,9 @@ const fn is_ascii(bytes: &[u8]) -> bool { } else { // For small inputs, use usize-at-a-time processing to avoid SSE2 call overhead. if bytes.len() < SIMD_MIN_LEN { - let chunks = bytes.chunks_exact(USIZE_SIZE); - let remainder = chunks.remainder(); + let (chunks, remainder) = bytes.as_chunks::(); for chunk in chunks { - let word = usize::from_ne_bytes(chunk.try_into().unwrap()); + let word = usize::from_ne_bytes(*chunk); if (word & NONASCII_MASK) != 0 { return false; } diff --git a/library/core/src/slice/cmp.rs b/library/core/src/slice/cmp.rs index 70d2392dfb3c6..acb74c9916dfd 100644 --- a/library/core/src/slice/cmp.rs +++ b/library/core/src/slice/cmp.rs @@ -386,6 +386,7 @@ impl SliceContains for T where T: PartialEq, { + #[expect(clippy::manual_contains, reason = "implements slice_contains")] default fn slice_contains(&self, x: &[Self]) -> bool { x.iter().any(|y| *y == *self) } @@ -393,6 +394,7 @@ where impl SliceContains for T { #[inline] + #[expect(clippy::manual_contains, reason = "implements slice_contains")] default fn slice_contains(&self, x: &[Self]) -> bool { if size_of::() == 1 { // SAFETY: `BytewiseEq` guarantees that values have no padding or provenance and diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index a054c9d742c88..1c721f2925eb5 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -1892,9 +1892,9 @@ impl<'a, T> Iterator for ChunksExact<'a, T> { #[inline] fn next(&mut self) -> Option<&'a [T]> { - self.v.split_at_checked(self.chunk_size).and_then(|(chunk, rest)| { + self.v.split_at_checked(self.chunk_size).map(|(chunk, rest)| { self.v = rest; - Some(chunk) + chunk }) } @@ -2048,9 +2048,9 @@ impl<'a, T> Iterator for ChunksExactMut<'a, T> { #[inline] fn next(&mut self) -> Option<&'a mut [T]> { // SAFETY: we have `&mut self`, so are allowed to temporarily materialize a mut slice - unsafe { &mut *self.v }.split_at_mut_checked(self.chunk_size).and_then(|(chunk, rest)| { + unsafe { &mut *self.v }.split_at_mut_checked(self.chunk_size).map(|(chunk, rest)| { self.v = rest; - Some(chunk) + chunk }) } diff --git a/library/core/src/slice/sort/select.rs b/library/core/src/slice/sort/select.rs index fc31013caf88c..30058f516867e 100644 --- a/library/core/src/slice/sort/select.rs +++ b/library/core/src/slice/sort/select.rs @@ -116,7 +116,7 @@ fn partition_at_index_loop<'a, T, F>( } v = &mut v[mid..]; - index = index - mid; + index -= mid; ancestor_pivot = None; continue; } diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index e676a3851112d..12208b95307ee 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -534,6 +534,7 @@ pub enum Ordering { note = "the `new` function is now preferred", suggestion = "AtomicBool::new(false)" )] +#[expect(clippy::declare_interior_mutable_const, reason = "legacy atomic initializer")] pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool::new(false); #[cfg(target_has_atomic_load_store = "8")] @@ -3939,6 +3940,7 @@ macro_rules! atomic_int_ptr_sized { note = "the `new` function is now preferred", suggestion = "AtomicIsize::new(0)", )] + #[expect(clippy::declare_interior_mutable_const, reason = "legacy atomic initializer")] pub const ATOMIC_ISIZE_INIT: AtomicIsize = AtomicIsize::new(0); /// An [`AtomicUsize`] initialized to `0`. @@ -3949,6 +3951,7 @@ macro_rules! atomic_int_ptr_sized { note = "the `new` function is now preferred", suggestion = "AtomicUsize::new(0)", )] + #[expect(clippy::declare_interior_mutable_const, reason = "legacy atomic initializer")] pub const ATOMIC_USIZE_INIT: AtomicUsize = AtomicUsize::new(0); )* }; } diff --git a/library/core/src/time.rs b/library/core/src/time.rs index 682a61a07d10f..816da7a2fb7f2 100644 --- a/library/core/src/time.rs +++ b/library/core/src/time.rs @@ -1361,7 +1361,7 @@ macro_rules! sum_durations { total_secs = total_secs .checked_add(total_nanos / NANOS_PER_SEC as u64) .expect("overflow in iter::sum over durations"); - total_nanos = total_nanos % NANOS_PER_SEC as u64; + total_nanos %= NANOS_PER_SEC as u64; Duration::new(total_secs, total_nanos as u32) }}; } diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index fef0b1b4df88e..2858680a20a49 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -1457,7 +1457,7 @@ where return false; } - self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v)) + self.iter().all(|(key, value)| other.get(key).is_some_and(|v| *value == *v)) } } diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index 3cc375b7290da..6ad20b192fa5c 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -3740,7 +3740,7 @@ impl DirBuilder { fn create_dir_all(&self, path: &Path) -> io::Result<()> { // if path's parent is None, it is "/" path, which should // return Ok immediately - if path.is_empty() || path.parent() == None { + if path.is_empty() || path.parent().is_none() { return Ok(()); } @@ -3751,7 +3751,7 @@ impl DirBuilder { // for relative paths like "foo/bar", the parent of // "foo" will be "" which there's no need to invoke // a mkdir syscall on - if ancestor.is_empty() || ancestor.parent() == None { + if ancestor.is_empty() || ancestor.parent().is_none() { break; } diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index cc652cb743353..92eccc27ee05d 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -738,7 +738,7 @@ mod panicking; #[path = "../../backtrace/src/lib.rs"] #[allow(dead_code, unused_attributes, implicit_provenance_casts, unsafe_op_in_unsafe_fn)] -#[allow(clippy::len_zero, clippy::needless_borrow)] // FIXME +#[allow(clippy::len_zero, clippy::needless_borrow, clippy::filter_map_next)] // FIXME mod backtrace_rs; #[stable(feature = "cfg_select", since = "1.95.0")] diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index 356b7daa293f4..5a4684a973942 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -175,7 +175,6 @@ pub fn set_hook(hook: Box) + 'static + Sync + Send>) { /// /// panic!("Normal panic"); /// ``` -#[must_use] #[stable(feature = "panic_hooks", since = "1.10.0")] pub fn take_hook() -> Box) + 'static + Sync + Send> { if thread::panicking() { diff --git a/library/std/src/path.rs b/library/std/src/path.rs index 3052587389a91..dbfc00b2c2b47 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -2933,7 +2933,7 @@ impl Path { #[stable(feature = "path_file_prefix", since = "1.91.0")] #[must_use] pub fn file_prefix(&self) -> Option<&OsStr> { - self.file_name().map(split_file_at_dot).and_then(|(before, _after)| Some(before)) + self.file_name().map(split_file_at_dot).map(|(before, _after)| before) } /// Extracts the extension (without the leading dot) of [`self.file_name`], if possible. diff --git a/library/std/src/sync/once.rs b/library/std/src/sync/once.rs index 62cac6afee751..9b555c32df99d 100644 --- a/library/std/src/sync/once.rs +++ b/library/std/src/sync/once.rs @@ -72,6 +72,7 @@ pub(crate) enum OnceExclusiveState { note = "the `Once::new()` function is now preferred", suggestion = "Once::new()" )] +#[expect(clippy::declare_interior_mutable_const, reason = "legacy Once initializer")] pub const ONCE_INIT: Once = Once::new(); impl Once { diff --git a/library/std/src/sys/args/windows.rs b/library/std/src/sys/args/windows.rs index bd26db7fea553..4a450a72cdccd 100644 --- a/library/std/src/sys/args/windows.rs +++ b/library/std/src/sys/args/windows.rs @@ -115,7 +115,7 @@ fn parse_lp_cmd_line<'a, F: Fn() -> OsString>( BACKSLASH => { let backslash_count = code_units.advance_while(|w| w == BACKSLASH) + 1; if code_units.peek() == Some(QUOTE) { - cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count / 2)); + cur.extend(iter::repeat_n(BACKSLASH.get(), backslash_count / 2)); // The quote is escaped if there are an odd number of backslashes. if backslash_count % 2 == 1 { code_units.next(); @@ -123,7 +123,7 @@ fn parse_lp_cmd_line<'a, F: Fn() -> OsString>( } } else { // If there is no quote on the end then there is no escaping. - cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count)); + cur.extend(iter::repeat_n(BACKSLASH.get(), backslash_count)); } } // If `in_quotes` and not backslash escaped (see above) then a quote either @@ -295,7 +295,7 @@ pub(crate) fn make_bat_command_line( force_quotes: bool, ) -> io::Result> { const INVALID_ARGUMENT_ERROR: io::Error = - io::const_error!(io::ErrorKind::InvalidInput, r#"batch file arguments are invalid"#); + io::const_error!(io::ErrorKind::InvalidInput, r"batch file arguments are invalid"); // Set the start of the command line to `cmd.exe /c "` // It is necessary to surround the command in an extra pair of quotes, // hence the trailing quote here. It will be closed after all arguments diff --git a/library/std/src/sys/fs/unix/dir.rs b/library/std/src/sys/fs/unix/dir.rs index aad309362127b..3fe952d942927 100644 --- a/library/std/src/sys/fs/unix/dir.rs +++ b/library/std/src/sys/fs/unix/dir.rs @@ -49,7 +49,7 @@ impl Dir { pub fn open_file(&self, path: &Path, opts: &OpenOptions) -> io::Result { run_path_with_cstr(path.as_ref(), &|path| self.open_file_c(path, opts, 0)) - .map(|fd| FileDesc::from_inner(fd)) + .map(FileDesc::from_inner) .map(File) } diff --git a/library/std/src/sys/fs/windows.rs b/library/std/src/sys/fs/windows.rs index c10b266ccb726..c99524375113a 100644 --- a/library/std/src/sys/fs/windows.rs +++ b/library/std/src/sys/fs/windows.rs @@ -784,9 +784,9 @@ impl File { pub fn set_times(&self, times: FileTimes) -> io::Result<()> { let is_zero = |t: c::FILETIME| t.dwLowDateTime == 0 && t.dwHighDateTime == 0; - if times.accessed.map_or(false, is_zero) - || times.modified.map_or(false, is_zero) - || times.created.map_or(false, is_zero) + if times.accessed.is_some_and(is_zero) + || times.modified.is_some_and(is_zero) + || times.created.is_some_and(is_zero) { return Err(io::const_error!( io::ErrorKind::InvalidInput, @@ -794,9 +794,9 @@ impl File { )); } let is_max = |t: c::FILETIME| t.dwLowDateTime == u32::MAX && t.dwHighDateTime == u32::MAX; - if times.accessed.map_or(false, is_max) - || times.modified.map_or(false, is_max) - || times.created.map_or(false, is_max) + if times.accessed.is_some_and(is_max) + || times.modified.is_some_and(is_max) + || times.created.is_some_and(is_max) { return Err(io::const_error!( io::ErrorKind::InvalidInput, @@ -1114,7 +1114,7 @@ impl FileAttr { } pub fn changed_u64(&self) -> Option { - self.change_time.as_ref().map(|c| to_u64(c)) + self.change_time.as_ref().map(to_u64) } pub fn volume_serial_number(&self) -> Option { diff --git a/library/std/src/sys/path/windows_prefix.rs b/library/std/src/sys/path/windows_prefix.rs index 5413269e9edee..37417b2bbc475 100644 --- a/library/std/src/sys/path/windows_prefix.rs +++ b/library/std/src/sys/path/windows_prefix.rs @@ -68,7 +68,7 @@ pub fn parse_prefix(path: &OsStr) -> Option> { // \\ // It's a POSIX path. - if cfg!(target_os = "cygwin") && !path.as_encoded_bytes().iter().any(|&x| x == b'\\') { + if cfg!(target_os = "cygwin") && !path.as_encoded_bytes().contains(&b'\\') { return None; } @@ -76,7 +76,7 @@ pub fn parse_prefix(path: &OsStr) -> Option> { // separator. if let Some(parser) = parser.strip_prefix(r"?\") // Cygwin allows `/` in verbatim paths. - && (cfg!(target_os = "cygwin") || !parser.prefix_bytes().iter().any(|&x| x == b'/')) + && (cfg!(target_os = "cygwin") || !parser.prefix_bytes().contains(&b'/')) { // \\?\ if let Some(parser) = parser.strip_prefix(r"UNC\") { diff --git a/library/std/src/sys/process/unix/unix.rs b/library/std/src/sys/process/unix/unix.rs index 6103fa3576f37..8729ab65b86db 100644 --- a/library/std/src/sys/process/unix/unix.rs +++ b/library/std/src/sys/process/unix/unix.rs @@ -928,9 +928,8 @@ impl Command { msg.msg_controllen = size_of::() as _; msg.msg_control = (&raw mut cmsg) as *mut _; - match cvt_r(|| libc::recvmsg(sock.as_raw(), &mut msg, libc::MSG_CMSG_CLOEXEC)) { - Err(_) => return -1, - Ok(_) => {} + if cvt_r(|| libc::recvmsg(sock.as_raw(), &mut msg, libc::MSG_CMSG_CLOEXEC)).is_err() { + return -1; } let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _); @@ -1317,7 +1316,7 @@ mod linux_child_ext { self.handle .pidfd .take() - .map(|fd| >::from_inner(fd)) + .map(>::from_inner) .ok_or_else(|| self) } } diff --git a/library/std/src/thread/spawnhook.rs b/library/std/src/thread/spawnhook.rs index 92fb586d39dcf..1bf22e0b0ea52 100644 --- a/library/std/src/thread/spawnhook.rs +++ b/library/std/src/thread/spawnhook.rs @@ -21,7 +21,7 @@ struct SpawnHooks { impl Drop for SpawnHooks { fn drop(&mut self) { let mut next = self.first.take(); - while let Some(SpawnHook { hook, next: n }) = next.and_then(|n| Arc::into_inner(n)) { + while let Some(SpawnHook { hook, next: n }) = next.and_then(Arc::into_inner) { drop(hook); next = n; } diff --git a/library/test/src/formatters/json.rs b/library/test/src/formatters/json.rs index 4a101f00d74b6..df62d0fd7f435 100644 --- a/library/test/src/formatters/json.rs +++ b/library/test/src/formatters/json.rs @@ -48,7 +48,7 @@ impl JsonFormatter { String::from("") }; let extra_json = - if let Some(extra) = extra { format!(r#", {extra}"#) } else { String::from("") }; + if let Some(extra) = extra { format!(r", {extra}") } else { String::from("") }; let newline = "\n"; self.writeln_message(&format!( diff --git a/library/test/src/term/terminfo/mod.rs b/library/test/src/term/terminfo/mod.rs index 75fa594908d56..6f712231e9888 100644 --- a/library/test/src/term/terminfo/mod.rs +++ b/library/test/src/term/terminfo/mod.rs @@ -67,7 +67,7 @@ impl TermInfo { Err(..) => return Err(Error::TermUnset), }; - if term.is_err() && env::var("MSYSCON").map_or(false, |s| "mintty.exe" == s) { + if term.is_err() && env::var("MSYSCON").is_ok_and(|s| "mintty.exe" == s) { // msys terminal Ok(msys_terminfo()) } else { diff --git a/library/test/src/term/terminfo/parm.rs b/library/test/src/term/terminfo/parm.rs index 529ec0c36e4a5..7426c1e009f55 100644 --- a/library/test/src/term/terminfo/parm.rs +++ b/library/test/src/term/terminfo/parm.rs @@ -1,6 +1,6 @@ //! Parameterized string expansion -use std::iter::repeat; +use std::iter::repeat_n; use self::Param::*; use self::States::*; @@ -520,10 +520,10 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result, String> { if flags.width > s.len() { let n = flags.width - s.len(); if flags.left { - s.extend(repeat(b' ').take(n)); + s.extend(repeat_n(b' ', n)); } else { let mut s_ = Vec::with_capacity(flags.width); - s_.extend(repeat(b' ').take(n)); + s_.extend(repeat_n(b' ', n)); s_.extend(s); s = s_; } diff --git a/library/test/src/test_result.rs b/library/test/src/test_result.rs index 4cb43fc45fd6c..b2457e031fd19 100644 --- a/library/test/src/test_result.rs +++ b/library/test/src/test_result.rs @@ -60,15 +60,15 @@ pub(crate) fn calc_result( TestResult::TrOk } else if let Some(panic_str) = maybe_panic_str { TestResult::TrFailedMsg(format!( - r#"panic did not contain expected string + r"panic did not contain expected string panic message: {panic_str:?} - expected substring: {msg:?}"# + expected substring: {msg:?}" )) } else { TestResult::TrFailedMsg(format!( - r#"expected panic with string value, + r"expected panic with string value, found non-string value: `{:?}` - expected substring: {msg:?}"#, + expected substring: {msg:?}", (*err).type_id() )) } diff --git a/src/bootstrap/src/core/build_steps/clippy.rs b/src/bootstrap/src/core/build_steps/clippy.rs index dc3e3efb80ee5..99648425a8987 100644 --- a/src/bootstrap/src/core/build_steps/clippy.rs +++ b/src/bootstrap/src/core/build_steps/clippy.rs @@ -38,7 +38,7 @@ const IGNORED_RULES_FOR_STD_AND_RUSTC: &[&str] = &[ "too_many_arguments", "needless_lifetimes", // people want to keep the lifetimes "wrong_self_convention", - "approx_constant", // libcore is what defines those + "redundant_pattern_matching", // can affect drop order ]; fn lint_args(builder: &Builder<'_>, config: &LintConfig, ignored_rules: &[&str]) -> Vec { @@ -572,29 +572,56 @@ impl CommandLineStep for CI { allow: vec!["clippy::all".into()], warn: vec![], deny: vec![ + // the entire correctness group should always be enforced. "clippy::correctness".into(), + // tidy-alphabetic-start + "clippy::approx_constant".into(), + "clippy::assign_op_pattern".into(), + "clippy::bind_instead_of_map".into(), + "clippy::borrow_deref_ref".into(), "clippy::char_lit_as_u8".into(), + "clippy::chunks_exact_to_as_chunks".into(), + "clippy::declare_interior_mutable_const".into(), + "clippy::default_constructed_unit_structs".into(), + "clippy::derivable_impls".into(), + "clippy::double_must_use".into(), + "clippy::excessive_precision".into(), + "clippy::explicit_auto_deref".into(), + "clippy::filter_map_next".into(), "clippy::four_forward_slashes".into(), + "clippy::int_plus_one".into(), + "clippy::legacy_numeric_constants".into(), + "clippy::let_and_return".into(), + "clippy::manual_repeat_n".into(), + "clippy::map_clone".into(), + "clippy::match_as_ref".into(), + "clippy::mem_replace_option_with_none".into(), + "clippy::mem_replace_option_with_some".into(), + "clippy::needless_as_bytes".into(), "clippy::needless_bool".into(), "clippy::needless_bool_assign".into(), + "clippy::needless_borrow".into(), + "clippy::needless_raw_string_hashes".into(), + "clippy::needless_return".into(), + "clippy::neg_cmp_op_on_partial_ord".into(), "clippy::non_minimal_cfg".into(), + "clippy::op_ref".into(), + "clippy::partialeq_ne_impl".into(), + "clippy::partialeq_to_none".into(), "clippy::print_literal".into(), + "clippy::ptr_offset_with_cast".into(), + "clippy::redundant_closure".into(), + "clippy::redundant_slicing".into(), "clippy::same_item_push".into(), + "clippy::seek_from_current".into(), "clippy::single_char_add_str".into(), + "clippy::single_match".into(), + "clippy::to_digit_is_some".into(), "clippy::to_string_in_format_args".into(), "clippy::unconditional_recursion".into(), - "clippy::int_plus_one".into(), - "clippy::legacy_numeric_constants".into(), + "clippy::unnecessary_map_or".into(), "clippy::zero_divided_by_zero".into(), - "clippy::len_zero".into(), - "clippy::needless_as_bytes".into(), - "clippy::ptr_offset_with_cast".into(), - "clippy::let_and_return".into(), - "clippy::needless_return".into(), - "clippy::needless_borrow".into(), - "clippy::op_ref".into(), - "clippy::borrow_deref_ref".into(), - "clippy::explicit_auto_deref".into(), + // tidy-alphabetic-end ], forbid: vec![], }; diff --git a/tests/codegen-llvm/issues/unreachable-disjunction-div-115026.rs b/tests/codegen-llvm/issues/unreachable-disjunction-div-115026.rs new file mode 100644 index 0000000000000..542cd0114c3f1 --- /dev/null +++ b/tests/codegen-llvm/issues/unreachable-disjunction-div-115026.rs @@ -0,0 +1,23 @@ +// Tests that a disjunction passed to `unreachable_unchecked` still rules out +// both division operands, so neither the division-by-zero check nor the +// overflow check survives. +// See . + +//@ compile-flags: -Copt-level=3 + +#![crate_type = "lib"] + +// CHECK-LABEL: @disjunction_div( +// CHECK-NOT: panic +// CHECK-NOT: br {{.*}} +// CHECK: sdiv i64 +// CHECK: ret i64 +#[no_mangle] +pub fn disjunction_div(num: i64, x: i64) -> i64 { + unsafe { + if x == -1 || x == 0 { + std::hint::unreachable_unchecked() + } + } + num / x +} diff --git a/tests/ui/higher-ranked/nested-binder-cmp-fn-sig-print.rs b/tests/ui/higher-ranked/nested-binder-cmp-fn-sig-print.rs new file mode 100644 index 0000000000000..65620812e3f8a --- /dev/null +++ b/tests/ui/higher-ranked/nested-binder-cmp-fn-sig-print.rs @@ -0,0 +1,26 @@ +//! Regression test for and +//! . +//! +//! The expected/found notes of "one type is more general than the other" errors +//! used to leak lifetimes bound by outer binders into nested `for<...>` lists, +//! printing invalid types such as `&mut for<'a> fn(for<'a> fn(&'a ()))` or +//! `for<'o> fn(for<'a, 'o> fn(&'a (), &'o ()))`. + +type F1 = fn(fn(&'static ())); +type F2 = for<'a> fn(fn(&'a ())); + +fn issue_134410(a: &mut F1) { + let _: &mut F2 = a; //~ ERROR mismatched types +} + +type One = fn(HelperOne); +type HelperOne = for<'a> fn(&'a (), &'a ()); + +type Two = for<'o> fn(HelperTwo<'o>); +type HelperTwo<'x> = for<'a> fn(&'a (), &'x ()); + +fn issue_111365(x: One) -> Two { + x //~ ERROR mismatched types +} + +fn main() {} diff --git a/tests/ui/higher-ranked/nested-binder-cmp-fn-sig-print.stderr b/tests/ui/higher-ranked/nested-binder-cmp-fn-sig-print.stderr new file mode 100644 index 0000000000000..c26b39ec5a567 --- /dev/null +++ b/tests/ui/higher-ranked/nested-binder-cmp-fn-sig-print.stderr @@ -0,0 +1,23 @@ +error[E0308]: mismatched types + --> $DIR/nested-binder-cmp-fn-sig-print.rs:23:5 + | +LL | fn issue_111365(x: One) -> Two { + | --- expected `for<'o> fn(for<'a> fn(&'a (), &'o ()))` because of return type +LL | x + | ^ one type is more general than the other + | + = note: expected fn pointer `for<'o> fn(for<'a> fn(&'a (), &'o ()))` + found fn pointer `fn(for<'a> fn(&'a (), &'a ()))` + +error[E0308]: mismatched types + --> $DIR/nested-binder-cmp-fn-sig-print.rs:13:22 + | +LL | let _: &mut F2 = a; + | ^ one type is more general than the other + | + = note: expected mutable reference `&mut for<'a> fn(fn(&'a ()))` + found mutable reference `&mut fn(fn(&()))` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/nll/relate_tys/placeholder-outlives-existential.stderr b/tests/ui/nll/relate_tys/placeholder-outlives-existential.stderr index 80ab5c8d6e9d8..05950c4d4f48a 100644 --- a/tests/ui/nll/relate_tys/placeholder-outlives-existential.stderr +++ b/tests/ui/nll/relate_tys/placeholder-outlives-existential.stderr @@ -5,7 +5,7 @@ LL | x | ^ one type is more general than the other | = note: expected fn pointer `fn(fn(fn(for<'unify> fn(Contra<'unify>, Co<'unify>))))` - found fn pointer `for<'e> fn(for<'e, 'p> fn(for<'e, 'p> fn(for<'e, 'p> fn(Contra<'e>, Co<'p>))))` + found fn pointer `for<'e> fn(for<'p> fn(fn(fn(Contra<'e>, Co<'p>))))` error: lifetime may not live long enough --> $DIR/placeholder-outlives-existential.rs:28:5