From 92c8317d2ae45a86b632b24996cd29a30d0dc3ce Mon Sep 17 00:00:00 2001
From: Scott McMurray <scottmcm@users.noreply.github.com>
Date: Thu, 2 Dec 2021 18:04:33 -0800
Subject: [PATCH 1/9] Add `[T]::as_simd(_mut)`

SIMD-style optimizations are the most common use for `[T]::align_to(_mut)`, but that's `unsafe`.  So these are *safe* wrappers around it, now that we have the `Simd` type available, to make it easier to use.

```rust
impl [T] {
    pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T]);
    pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T]);
}
```
---
 library/core/src/slice/mod.rs | 83 +++++++++++++++++++++++++++++++++++
 1 file changed, 83 insertions(+)

diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs
index a3f59d3075954..7797ae6d49ff2 100644
--- a/library/core/src/slice/mod.rs
+++ b/library/core/src/slice/mod.rs
@@ -16,6 +16,8 @@ use crate::option::Option::{None, Some};
 use crate::ptr;
 use crate::result::Result;
 use crate::result::Result::{Err, Ok};
+#[cfg(not(miri))] // Miri does not support all SIMD intrinsics
+use crate::simd::{self, Simd};
 use crate::slice;
 
 #[unstable(
@@ -3434,6 +3436,87 @@ impl<T> [T] {
         }
     }
 
+    /// Split a slice into a prefix, a middle of aligned simd types, and a suffix.
+    ///
+    /// This is a safe wrapper around [`slice::align_to`], so has the same weak
+    /// preconditions as that method.  Notably, you must not assume any particular
+    /// split between the three parts: it's legal for the middle slice to be
+    /// empty even if the input slice is longer than `3 * LANES`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(portable_simd)]
+    ///
+    /// let short = &[1, 2, 3];
+    /// let (prefix, middle, suffix) = short.as_simd::<4>();
+    /// assert_eq!(middle, []); // Not enough elements for anything in the middle
+    ///
+    /// // They might be split in any possible way between prefix and suffix
+    /// let it = prefix.iter().chain(suffix).copied();
+    /// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
+    ///
+    /// fn basic_simd_sum(x: &[f32]) -> f32 {
+    ///     use std::ops::Add;
+    ///     use std::simd::f32x4;
+    ///     let (prefix, middle, suffix) = x.as_simd();
+    ///     let sums = f32x4::from_array([
+    ///         prefix.iter().copied().sum(),
+    ///         0.0,
+    ///         0.0,
+    ///         suffix.iter().copied().sum(),
+    ///     ]);
+    ///     let sums = middle.iter().copied().fold(sums, f32x4::add);
+    ///     sums.horizontal_sum()
+    /// }
+    ///
+    /// let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
+    /// assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
+    /// ```
+    #[unstable(feature = "portable_simd", issue = "86656")]
+    #[cfg(not(miri))] // Miri does not support all SIMD intrinsics
+    pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
+    where
+        Simd<T, LANES>: AsRef<[T; LANES]>,
+        T: simd::SimdElement,
+        simd::LaneCount<LANES>: simd::SupportedLaneCount,
+    {
+        // These are expected to always match, as vector types are laid out like
+        // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
+        // might as well double-check since it'll optimize away anyhow.
+        assert_eq!(mem::size_of::<Simd<T, LANES>>(), mem::size_of::<[T; LANES]>());
+
+        // SAFETY: The simd types have the same layout as arrays, just with
+        // potentially-higher alignment, so the de-facto transmutes are sound.
+        unsafe { self.align_to() }
+    }
+
+    /// Split a slice into a prefix, a middle of aligned simd types, and a suffix.
+    ///
+    /// This is a safe wrapper around [`slice::align_to`], so has the same weak
+    /// preconditions as that method.  Notably, you must not assume any particular
+    /// split between the three parts: it's legal for the middle slice to be
+    /// empty even if the input slice is longer than `3 * LANES`.
+    ///
+    /// This is the mutable version of [`slice::as_simd`]; see that for more.
+    #[unstable(feature = "portable_simd", issue = "86656")]
+    #[cfg(not(miri))] // Miri does not support all SIMD intrinsics
+    pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
+    where
+        Simd<T, LANES>: AsMut<[T; LANES]>,
+        T: simd::SimdElement,
+        simd::LaneCount<LANES>: simd::SupportedLaneCount,
+    {
+        // These are expected to always match, as vector types are laid out like
+        // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
+        // might as well double-check since it'll optimize away anyhow.
+        assert_eq!(mem::size_of::<Simd<T, LANES>>(), mem::size_of::<[T; LANES]>());
+
+        // SAFETY: The simd types have the same layout as arrays, just with
+        // potentially-higher alignment, so the de-facto transmutes are sound.
+        unsafe { self.align_to_mut() }
+    }
+
     /// Checks if the elements of this slice are sorted.
     ///
     /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the

From 4e38807166dcf2bd1e76a93c0eb4b4eea1511385 Mon Sep 17 00:00:00 2001
From: Andy Russell <arussell123@gmail.com>
Date: Mon, 13 Dec 2021 22:23:55 -0500
Subject: [PATCH 2/9] core: minor `Option` doc correction

---
 library/core/src/option.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/library/core/src/option.rs b/library/core/src/option.rs
index 381e2d6eed3f6..015366ed490c7 100644
--- a/library/core/src/option.rs
+++ b/library/core/src/option.rs
@@ -512,11 +512,11 @@ use crate::{
 #[rustc_diagnostic_item = "Option"]
 #[stable(feature = "rust1", since = "1.0.0")]
 pub enum Option<T> {
-    /// No value
+    /// No value.
     #[lang = "None"]
     #[stable(feature = "rust1", since = "1.0.0")]
     None,
-    /// Some value `T`
+    /// Some value of type `T`.
     #[lang = "Some"]
     #[stable(feature = "rust1", since = "1.0.0")]
     Some(#[stable(feature = "rust1", since = "1.0.0")] T),

From 7175980ff51636f03824d67869e9a237c7d76ad5 Mon Sep 17 00:00:00 2001
From: Ellen <supbscripter@gmail.com>
Date: Mon, 13 Dec 2021 19:14:35 +0000
Subject: [PATCH 3/9] awdawdawd

---
 compiler/rustc_ast_lowering/src/lib.rs       |  3 +--
 compiler/rustc_hir/src/hir.rs                | 14 --------------
 compiler/rustc_resolve/src/late/lifetimes.rs |  9 ++++-----
 3 files changed, 5 insertions(+), 21 deletions(-)

diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs
index c04b0471cb72f..4f571cd87a2fe 100644
--- a/compiler/rustc_ast_lowering/src/lib.rs
+++ b/compiler/rustc_ast_lowering/src/lib.rs
@@ -53,7 +53,7 @@ use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
 use rustc_hir::def_id::{DefId, DefPathHash, LocalDefId, CRATE_DEF_ID};
 use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
 use rustc_hir::intravisit;
-use rustc_hir::{ConstArg, GenericArg, InferKind, ParamName};
+use rustc_hir::{ConstArg, GenericArg, ParamName};
 use rustc_index::vec::{Idx, IndexVec};
 use rustc_query_system::ich::StableHashingContext;
 use rustc_session::lint::builtin::BARE_TRAIT_OBJECTS;
@@ -1114,7 +1114,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
                         return GenericArg::Infer(hir::InferArg {
                             hir_id: self.lower_node_id(ty.id),
                             span: self.lower_span(ty.span),
-                            kind: InferKind::Type,
                         });
                     }
                     // We parse const arguments as path types as we cannot distinguish them during
diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs
index fdf7a8102a028..b8fe43ae10d92 100644
--- a/compiler/rustc_hir/src/hir.rs
+++ b/compiler/rustc_hir/src/hir.rs
@@ -255,23 +255,9 @@ pub struct ConstArg {
     pub span: Span,
 }
 
-#[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
-pub enum InferKind {
-    Const,
-    Type,
-}
-
-impl InferKind {
-    #[inline]
-    pub fn is_type(self) -> bool {
-        matches!(self, InferKind::Type)
-    }
-}
-
 #[derive(Encodable, Debug, HashStable_Generic)]
 pub struct InferArg {
     pub hir_id: HirId,
-    pub kind: InferKind,
     pub span: Span,
 }
 
diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs
index c94c56df75b78..05098defead38 100644
--- a/compiler/rustc_resolve/src/late/lifetimes.rs
+++ b/compiler/rustc_resolve/src/late/lifetimes.rs
@@ -2541,8 +2541,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
                                 GenericParamDefKind::Type { object_lifetime_default, .. } => {
                                     Some(object_lifetime_default)
                                 }
-                                GenericParamDefKind::Lifetime
-                                | GenericParamDefKind::Const { .. } => None,
+                                GenericParamDefKind::Const { .. } => Some(Set1::Empty),
+                                GenericParamDefKind::Lifetime => None,
                             })
                             .collect()
                     })
@@ -2569,12 +2569,11 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
                 }
                 GenericArg::Const(ct) => {
                     self.visit_anon_const(&ct.value);
+                    i += 1;
                 }
                 GenericArg::Infer(inf) => {
                     self.visit_id(inf.hir_id);
-                    if inf.kind.is_type() {
-                        i += 1;
-                    }
+                    i += 1;
                 }
             }
         }

From 0a0f01410d378fc9d1ca27fe5a42f01092e0cf3e Mon Sep 17 00:00:00 2001
From: Ellen <supbscripter@gmail.com>
Date: Mon, 13 Dec 2021 19:47:10 +0000
Subject: [PATCH 4/9] test

---
 .../auxiliary/trait_object_lt_defaults_lib.rs |  1 +
 .../defaults/trait_object_lt_defaults.rs      | 24 +++++++++++++++++++
 2 files changed, 25 insertions(+)
 create mode 100644 src/test/ui/const-generics/defaults/auxiliary/trait_object_lt_defaults_lib.rs
 create mode 100644 src/test/ui/const-generics/defaults/trait_object_lt_defaults.rs

diff --git a/src/test/ui/const-generics/defaults/auxiliary/trait_object_lt_defaults_lib.rs b/src/test/ui/const-generics/defaults/auxiliary/trait_object_lt_defaults_lib.rs
new file mode 100644
index 0000000000000..26a2c47ffb26d
--- /dev/null
+++ b/src/test/ui/const-generics/defaults/auxiliary/trait_object_lt_defaults_lib.rs
@@ -0,0 +1 @@
+pub struct Foo<'a, const N: usize, T: 'a + ?Sized>(pub &'a T, [(); N]);
diff --git a/src/test/ui/const-generics/defaults/trait_object_lt_defaults.rs b/src/test/ui/const-generics/defaults/trait_object_lt_defaults.rs
new file mode 100644
index 0000000000000..a1828727ecdbe
--- /dev/null
+++ b/src/test/ui/const-generics/defaults/trait_object_lt_defaults.rs
@@ -0,0 +1,24 @@
+// aux-build:trait_object_lt_defaults_lib.rs
+// run-pass
+#![allow(dead_code)]
+extern crate trait_object_lt_defaults_lib;
+
+// Tests that `A<'a, 3, dyn Test>` is short for `A<'a, 3, dyn Test + 'a>`
+// and `Foo<'a, 3, dyn Test>` is short for `Foo<'a, 3, dyn Test + 'a>`
+// Test is in `const-generics/defaults` because it relies on param ordering
+
+trait Test {}
+
+struct A<'a, const N: usize, T: ?Sized + 'a>(&'a T, [(); N]);
+fn blah<'a>(mut a: A<'a, 3, dyn Test>, arg: &'a (dyn Test + 'a)) {
+    a.0 = arg;
+}
+
+fn other_blah<'a>(
+    mut a: trait_object_lt_defaults_lib::Foo<'a, 3, dyn Test>,
+    arg: &'a (dyn Test + 'a),
+) {
+    a.0 = arg;
+}
+
+fn main() {}

From b682deca7e32c10876bd18c1344a0e4f4113d42d Mon Sep 17 00:00:00 2001
From: Sylvan Bowdler <sylvanbowdler81@gmail.com>
Date: Tue, 14 Dec 2021 08:01:32 +0000
Subject: [PATCH 5/9] Remove `in_band_lifetimes` from `rustc_symbol_mangling`

---
 compiler/rustc_symbol_mangling/src/legacy.rs | 6 +++---
 compiler/rustc_symbol_mangling/src/lib.rs    | 9 ++++-----
 compiler/rustc_symbol_mangling/src/test.rs   | 4 ++--
 compiler/rustc_symbol_mangling/src/v0.rs     | 8 ++++----
 4 files changed, 13 insertions(+), 14 deletions(-)

diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs
index de18614360ef5..cdea84a8d60f7 100644
--- a/compiler/rustc_symbol_mangling/src/legacy.rs
+++ b/compiler/rustc_symbol_mangling/src/legacy.rs
@@ -13,7 +13,7 @@ use tracing::debug;
 use std::fmt::{self, Write};
 use std::mem::{self, discriminant};
 
-pub(super) fn mangle(
+pub(super) fn mangle<'tcx>(
     tcx: TyCtxt<'tcx>,
     instance: Instance<'tcx>,
     instantiating_crate: Option<CrateNum>,
@@ -199,7 +199,7 @@ struct SymbolPrinter<'tcx> {
 // `PrettyPrinter` aka pretty printing of e.g. types in paths,
 // symbol names should have their own printing machinery.
 
-impl Printer<'tcx> for &mut SymbolPrinter<'tcx> {
+impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> {
     type Error = fmt::Error;
 
     type Path = Self;
@@ -345,7 +345,7 @@ impl Printer<'tcx> for &mut SymbolPrinter<'tcx> {
     }
 }
 
-impl PrettyPrinter<'tcx> for &mut SymbolPrinter<'tcx> {
+impl<'tcx> PrettyPrinter<'tcx> for &mut SymbolPrinter<'tcx> {
     fn region_should_not_be_omitted(&self, _region: ty::Region<'_>) -> bool {
         false
     }
diff --git a/compiler/rustc_symbol_mangling/src/lib.rs b/compiler/rustc_symbol_mangling/src/lib.rs
index bb7b452955609..d91f6d53409d5 100644
--- a/compiler/rustc_symbol_mangling/src/lib.rs
+++ b/compiler/rustc_symbol_mangling/src/lib.rs
@@ -90,7 +90,6 @@
 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
 #![feature(never_type)]
 #![feature(nll)]
-#![feature(in_band_lifetimes)]
 #![feature(iter_zip)]
 #![recursion_limit = "256"]
 
@@ -117,7 +116,7 @@ pub mod test;
 /// This function computes the symbol name for the given `instance` and the
 /// given instantiating crate. That is, if you know that instance X is
 /// instantiated in crate Y, this is the symbol name this instance would have.
-pub fn symbol_name_for_instance_in_crate(
+pub fn symbol_name_for_instance_in_crate<'tcx>(
     tcx: TyCtxt<'tcx>,
     instance: Instance<'tcx>,
     instantiating_crate: CrateNum,
@@ -132,7 +131,7 @@ pub fn provide(providers: &mut Providers) {
 // The `symbol_name` query provides the symbol name for calling a given
 // instance from the local crate. In particular, it will also look up the
 // correct symbol name of instances from upstream crates.
-fn symbol_name_provider(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> ty::SymbolName<'tcx> {
+fn symbol_name_provider<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> ty::SymbolName<'tcx> {
     let symbol_name = compute_symbol_name(tcx, instance, || {
         // This closure determines the instantiating crate for instances that
         // need an instantiating-crate-suffix for their symbol name, in order
@@ -152,14 +151,14 @@ fn symbol_name_provider(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> ty::Symb
 }
 
 /// This function computes the typeid for the given function ABI.
-pub fn typeid_for_fnabi(tcx: TyCtxt<'tcx>, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> String {
+pub fn typeid_for_fnabi<'tcx>(tcx: TyCtxt<'tcx>, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> String {
     v0::mangle_typeid_for_fnabi(tcx, fn_abi)
 }
 
 /// Computes the symbol name for the given instance. This function will call
 /// `compute_instantiating_crate` if it needs to factor the instantiating crate
 /// into the symbol name.
-fn compute_symbol_name(
+fn compute_symbol_name<'tcx>(
     tcx: TyCtxt<'tcx>,
     instance: Instance<'tcx>,
     compute_instantiating_crate: impl FnOnce() -> CrateNum,
diff --git a/compiler/rustc_symbol_mangling/src/test.rs b/compiler/rustc_symbol_mangling/src/test.rs
index f7d68b5cc7061..700765a351ce1 100644
--- a/compiler/rustc_symbol_mangling/src/test.rs
+++ b/compiler/rustc_symbol_mangling/src/test.rs
@@ -31,7 +31,7 @@ struct SymbolNamesTest<'tcx> {
     tcx: TyCtxt<'tcx>,
 }
 
-impl SymbolNamesTest<'tcx> {
+impl SymbolNamesTest<'_> {
     fn process_attrs(&mut self, def_id: LocalDefId) {
         let tcx = self.tcx;
         for attr in tcx.get_attrs(def_id.to_def_id()).iter() {
@@ -59,7 +59,7 @@ impl SymbolNamesTest<'tcx> {
     }
 }
 
-impl hir::itemlikevisit::ItemLikeVisitor<'tcx> for SymbolNamesTest<'tcx> {
+impl<'tcx> hir::itemlikevisit::ItemLikeVisitor<'tcx> for SymbolNamesTest<'tcx> {
     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
         self.process_attrs(item.def_id);
     }
diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs
index 0363ddb0e6eee..167ff758f3480 100644
--- a/compiler/rustc_symbol_mangling/src/v0.rs
+++ b/compiler/rustc_symbol_mangling/src/v0.rs
@@ -17,7 +17,7 @@ use std::fmt::Write;
 use std::iter;
 use std::ops::Range;
 
-pub(super) fn mangle(
+pub(super) fn mangle<'tcx>(
     tcx: TyCtxt<'tcx>,
     instance: Instance<'tcx>,
     instantiating_crate: Option<CrateNum>,
@@ -56,7 +56,7 @@ pub(super) fn mangle(
     std::mem::take(&mut cx.out)
 }
 
-pub(super) fn mangle_typeid_for_fnabi(
+pub(super) fn mangle_typeid_for_fnabi<'tcx>(
     _tcx: TyCtxt<'tcx>,
     fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
 ) -> String {
@@ -118,7 +118,7 @@ struct SymbolMangler<'tcx> {
     consts: FxHashMap<&'tcx ty::Const<'tcx>, usize>,
 }
 
-impl SymbolMangler<'tcx> {
+impl<'tcx> SymbolMangler<'tcx> {
     fn push(&mut self, s: &str) {
         self.out.push_str(s);
     }
@@ -250,7 +250,7 @@ impl SymbolMangler<'tcx> {
     }
 }
 
-impl Printer<'tcx> for &mut SymbolMangler<'tcx> {
+impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> {
     type Error = !;
 
     type Path = Self;

From 97e844a032c47d4b3e70d2043f809767e437ac24 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= <matthias.krueger@famsik.de>
Date: Mon, 13 Dec 2021 22:58:58 +0100
Subject: [PATCH 6/9] fix clippy::single_char_pattern perf findings

---
 compiler/rustc_codegen_ssa/src/back/link.rs          |  4 ++--
 compiler/rustc_driver/src/lib.rs                     | 10 +++++-----
 compiler/rustc_graphviz/src/lib.rs                   |  2 +-
 compiler/rustc_interface/src/passes.rs               |  2 +-
 compiler/rustc_middle/src/lint.rs                    |  4 ++--
 compiler/rustc_middle/src/mir/generic_graphviz.rs    |  4 ++--
 compiler/rustc_middle/src/mir/spanview.rs            | 12 ++++++------
 compiler/rustc_mir_transform/src/coverage/debug.rs   |  2 +-
 compiler/rustc_mir_transform/src/coverage/spans.rs   |  2 +-
 compiler/rustc_parse/src/parser/diagnostics.rs       |  2 +-
 compiler/rustc_save_analysis/src/lib.rs              |  2 +-
 compiler/rustc_session/src/config.rs                 |  2 +-
 compiler/rustc_session/src/options.rs                |  2 +-
 compiler/rustc_session/src/output.rs                 |  2 +-
 .../src/traits/error_reporting/suggestions.rs        |  2 +-
 src/librustdoc/html/render/cache.rs                  |  4 ++--
 src/librustdoc/html/render/mod.rs                    |  2 +-
 src/librustdoc/passes/collect_intra_doc_links.rs     |  2 +-
 src/librustdoc/theme.rs                              | 10 +++++-----
 19 files changed, 36 insertions(+), 36 deletions(-)

diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs
index bf45810de7708..e29c109f12d59 100644
--- a/compiler/rustc_codegen_ssa/src/back/link.rs
+++ b/compiler/rustc_codegen_ssa/src/back/link.rs
@@ -2226,8 +2226,8 @@ fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
                     continue;
                 }
 
-                let canonical = f.replace("-", "_");
-                let canonical_name = name.replace("-", "_");
+                let canonical = f.replace('-', "_");
+                let canonical_name = name.replace('-', "_");
 
                 let is_rust_object =
                     canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
diff --git a/compiler/rustc_driver/src/lib.rs b/compiler/rustc_driver/src/lib.rs
index 6ff94341142fd..12e0b7a4977e1 100644
--- a/compiler/rustc_driver/src/lib.rs
+++ b/compiler/rustc_driver/src/lib.rs
@@ -872,7 +872,7 @@ Available lint options:
 
     let print_lints = |lints: Vec<&Lint>| {
         for lint in lints {
-            let name = lint.name_lower().replace("_", "-");
+            let name = lint.name_lower().replace('_', "-");
             println!(
                 "    {}  {:7.7}  {}",
                 padded(&name),
@@ -908,10 +908,10 @@ Available lint options:
 
     let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| {
         for (name, to) in lints {
-            let name = name.to_lowercase().replace("_", "-");
+            let name = name.to_lowercase().replace('_', "-");
             let desc = to
                 .into_iter()
-                .map(|x| x.to_string().replace("_", "-"))
+                .map(|x| x.to_string().replace('_', "-"))
                 .collect::<Vec<String>>()
                 .join(", ");
             println!("    {}  {}", padded(&name), desc);
@@ -960,7 +960,7 @@ fn print_flag_list<T>(
         println!(
             "    {} {:>width$}=val -- {}",
             cmdline_opt,
-            name.replace("_", "-"),
+            name.replace('_', "-"),
             desc,
             width = max_len
         );
@@ -1015,7 +1015,7 @@ pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
                 .iter()
                 .map(|&(name, ..)| ('C', name))
                 .chain(DB_OPTIONS.iter().map(|&(name, ..)| ('Z', name)))
-                .find(|&(_, name)| *opt == name.replace("_", "-"))
+                .find(|&(_, name)| *opt == name.replace('_', "-"))
                 .map(|(flag, _)| format!("{}. Did you mean `-{} {}`?", e, flag, opt)),
             _ => None,
         };
diff --git a/compiler/rustc_graphviz/src/lib.rs b/compiler/rustc_graphviz/src/lib.rs
index edb8bd503e1d0..e318090ebe15a 100644
--- a/compiler/rustc_graphviz/src/lib.rs
+++ b/compiler/rustc_graphviz/src/lib.rs
@@ -472,7 +472,7 @@ pub trait Labeller<'a> {
 /// Escape tags in such a way that it is suitable for inclusion in a
 /// Graphviz HTML label.
 pub fn escape_html(s: &str) -> String {
-    s.replace("&", "&amp;").replace("\"", "&quot;").replace("<", "&lt;").replace(">", "&gt;")
+    s.replace('&', "&amp;").replace('\"', "&quot;").replace('<', "&lt;").replace('>', "&gt;")
 }
 
 impl<'a> LabelText<'a> {
diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs
index da76f221269fe..34865900495c7 100644
--- a/compiler/rustc_interface/src/passes.rs
+++ b/compiler/rustc_interface/src/passes.rs
@@ -584,7 +584,7 @@ fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
 fn escape_dep_filename(filename: &str) -> String {
     // Apparently clang and gcc *only* escape spaces:
     // https://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
-    filename.replace(" ", "\\ ")
+    filename.replace(' ', "\\ ")
 }
 
 // Makefile comments only need escaping newlines and `\`.
diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs
index 881b14278e99e..a6432b301743a 100644
--- a/compiler/rustc_middle/src/lint.rs
+++ b/compiler/rustc_middle/src/lint.rs
@@ -295,7 +295,7 @@ pub fn struct_lint_level<'s, 'd>(
                     Level::Allow => "-A",
                     Level::ForceWarn => "--force-warn",
                 };
-                let hyphen_case_lint_name = name.replace("_", "-");
+                let hyphen_case_lint_name = name.replace('_', "-");
                 if lint_flag_val.as_str() == name {
                     sess.diag_note_once(
                         &mut err,
@@ -306,7 +306,7 @@ pub fn struct_lint_level<'s, 'd>(
                         ),
                     );
                 } else {
-                    let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
+                    let hyphen_case_flag_val = lint_flag_val.as_str().replace('_', "-");
                     sess.diag_note_once(
                         &mut err,
                         DiagnosticMessageId::from(lint),
diff --git a/compiler/rustc_middle/src/mir/generic_graphviz.rs b/compiler/rustc_middle/src/mir/generic_graphviz.rs
index 21c18b28e258b..c907680bda14a 100644
--- a/compiler/rustc_middle/src/mir/generic_graphviz.rs
+++ b/compiler/rustc_middle/src/mir/generic_graphviz.rs
@@ -126,7 +126,7 @@ impl<
             write!(
                 w,
                 r#"<tr><td align="left" balign="left">{}</td></tr>"#,
-                dot::escape_html(&section).replace("\n", "<br/>")
+                dot::escape_html(&section).replace('\n', "<br/>")
             )?;
         }
 
@@ -147,7 +147,7 @@ impl<
             let src = self.node(source);
             let trg = self.node(target);
             let escaped_edge_label = if let Some(edge_label) = edge_labels.get(index) {
-                dot::escape_html(edge_label).replace("\n", r#"<br align="left"/>"#)
+                dot::escape_html(edge_label).replace('\n', r#"<br align="left"/>"#)
             } else {
                 "".to_owned()
             };
diff --git a/compiler/rustc_middle/src/mir/spanview.rs b/compiler/rustc_middle/src/mir/spanview.rs
index 1260c691e7844..507f9971981b0 100644
--- a/compiler/rustc_middle/src/mir/spanview.rs
+++ b/compiler/rustc_middle/src/mir/spanview.rs
@@ -681,13 +681,13 @@ fn hir_body<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<&'tcx rustc_hir::B
 }
 
 fn escape_html(s: &str) -> String {
-    s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
 }
 
 fn escape_attr(s: &str) -> String {
-    s.replace("&", "&amp;")
-        .replace("\"", "&quot;")
-        .replace("'", "&#39;")
-        .replace("<", "&lt;")
-        .replace(">", "&gt;")
+    s.replace('&', "&amp;")
+        .replace('\"', "&quot;")
+        .replace('\'', "&#39;")
+        .replace('<', "&lt;")
+        .replace('>', "&gt;")
 }
diff --git a/compiler/rustc_mir_transform/src/coverage/debug.rs b/compiler/rustc_mir_transform/src/coverage/debug.rs
index 588103ca43dd0..c61ee6f7e6cb7 100644
--- a/compiler/rustc_mir_transform/src/coverage/debug.rs
+++ b/compiler/rustc_mir_transform/src/coverage/debug.rs
@@ -148,7 +148,7 @@ impl DebugOptions {
         let mut counter_format = ExpressionFormat::default();
 
         if let Ok(env_debug_options) = std::env::var(RUSTC_COVERAGE_DEBUG_OPTIONS) {
-            for setting_str in env_debug_options.replace(" ", "").replace("-", "_").split(',') {
+            for setting_str in env_debug_options.replace(' ', "").replace('-', "_").split(',') {
                 let (option, value) = match setting_str.split_once('=') {
                     None => (setting_str, None),
                     Some((k, v)) => (k, Some(v)),
diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs
index 01e72a6c1588d..b5356a817f7ac 100644
--- a/compiler/rustc_mir_transform/src/coverage/spans.rs
+++ b/compiler/rustc_mir_transform/src/coverage/spans.rs
@@ -155,7 +155,7 @@ impl CoverageSpan {
         format!(
             "{}\n    {}",
             source_range_no_file(tcx, &self.span),
-            self.format_coverage_statements(tcx, mir_body).replace("\n", "\n    "),
+            self.format_coverage_statements(tcx, mir_body).replace('\n', "\n    "),
         )
     }
 
diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs
index 25beed1ecf9c7..9677e7642b88c 100644
--- a/compiler/rustc_parse/src/parser/diagnostics.rs
+++ b/compiler/rustc_parse/src/parser/diagnostics.rs
@@ -2236,7 +2236,7 @@ impl<'a> Parser<'a> {
             err.span_suggestion(
                 seq_span,
                 "...or a vertical bar to match on multiple alternatives",
-                seq_snippet.replace(",", " |"),
+                seq_snippet.replace(',', " |"),
                 Applicability::MachineApplicable,
             );
         }
diff --git a/compiler/rustc_save_analysis/src/lib.rs b/compiler/rustc_save_analysis/src/lib.rs
index c7f8fe3a88a64..6f86bafbe4581 100644
--- a/compiler/rustc_save_analysis/src/lib.rs
+++ b/compiler/rustc_save_analysis/src/lib.rs
@@ -1036,7 +1036,7 @@ fn find_config(supplied: Option<Config>) -> Config {
 
 // Helper function to escape quotes in a string
 fn escape(s: String) -> String {
-    s.replace("\"", "\"\"")
+    s.replace('\"', "\"\"")
 }
 
 // Helper function to determine if a span came from a
diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs
index 5df8a4103b74f..50a8f0336728e 100644
--- a/compiler/rustc_session/src/config.rs
+++ b/compiler/rustc_session/src/config.rs
@@ -1213,7 +1213,7 @@ pub fn get_cmd_lint_options(
             if lint_name == "help" {
                 describe_lints = true;
             } else {
-                lint_opts_with_position.push((arg_pos, lint_name.replace("-", "_"), level));
+                lint_opts_with_position.push((arg_pos, lint_name.replace('-', "_"), level));
             }
         }
     }
diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs
index bd7b1639613eb..dc5f4ee0ece0c 100644
--- a/compiler/rustc_session/src/options.rs
+++ b/compiler/rustc_session/src/options.rs
@@ -335,7 +335,7 @@ fn build_options<O: Default>(
             Some((k, v)) => (k.to_string(), Some(v)),
         };
 
-        let option_to_lookup = key.replace("-", "_");
+        let option_to_lookup = key.replace('-', "_");
         match descrs.iter().find(|(name, ..)| *name == option_to_lookup) {
             Some((_, setter, type_desc, _)) => {
                 if !setter(&mut op, value) {
diff --git a/compiler/rustc_session/src/output.rs b/compiler/rustc_session/src/output.rs
index cc1e4bb198a3b..5689b723ad610 100644
--- a/compiler/rustc_session/src/output.rs
+++ b/compiler/rustc_session/src/output.rs
@@ -85,7 +85,7 @@ pub fn find_crate_name(sess: &Session, attrs: &[ast::Attribute], input: &Input)
                 );
                 sess.err(&msg);
             } else {
-                return validate(s.replace("-", "_"), None);
+                return validate(s.replace('-', "_"), None);
             }
         }
     }
diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs
index 286c9c9900b95..1396d1e606af4 100644
--- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs
+++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs
@@ -741,7 +741,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
 
                     let msg = format!(
                         "the trait bound `{}: {}` is not satisfied",
-                        orig_ty.to_string(),
+                        orig_ty,
                         old_ref.print_only_trait_path(),
                     );
                     if has_custom_message {
diff --git a/src/librustdoc/html/render/cache.rs b/src/librustdoc/html/render/cache.rs
index 2f7214e958ea7..631eacc961828 100644
--- a/src/librustdoc/html/render/cache.rs
+++ b/src/librustdoc/html/render/cache.rs
@@ -184,8 +184,8 @@ crate fn build_index<'tcx>(krate: &clean::Crate, cache: &mut Cache, tcx: TyCtxt<
         })
         .expect("failed serde conversion")
         // All these `replace` calls are because we have to go through JS string for JSON content.
-        .replace(r"\", r"\\")
-        .replace("'", r"\'")
+        .replace(r#"\"#, r"\\")
+        .replace(r#"'"#, r"\'")
         // We need to escape double quotes for the JSON.
         .replace("\\\"", "\\\\\"")
     )
diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs
index 166e084012724..c67fe1fef40cd 100644
--- a/src/librustdoc/html/render/mod.rs
+++ b/src/librustdoc/html/render/mod.rs
@@ -989,7 +989,7 @@ fn attributes(it: &clean::Item) -> Vec<String> {
         .iter()
         .filter_map(|attr| {
             if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
-                Some(pprust::attribute_to_string(attr).replace("\n", "").replace("  ", " "))
+                Some(pprust::attribute_to_string(attr).replace('\n', "").replace("  ", " "))
             } else {
                 None
             }
diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs
index 4e5812d7f8429..2faf7781807d4 100644
--- a/src/librustdoc/passes/collect_intra_doc_links.rs
+++ b/src/librustdoc/passes/collect_intra_doc_links.rs
@@ -963,7 +963,7 @@ fn preprocess_link<'a>(
         return None;
     }
 
-    let stripped = ori_link.link.replace("`", "");
+    let stripped = ori_link.link.replace('`', "");
     let mut parts = stripped.split('#');
 
     let link = parts.next().unwrap();
diff --git a/src/librustdoc/theme.rs b/src/librustdoc/theme.rs
index b8b3f9634e582..1e9a65e1d2fc4 100644
--- a/src/librustdoc/theme.rs
+++ b/src/librustdoc/theme.rs
@@ -173,11 +173,11 @@ fn build_rule(v: &[u8], positions: &[usize]) -> String {
             .map(|x| ::std::str::from_utf8(&v[x[0]..x[1]]).unwrap_or(""))
             .collect::<String>()
             .trim()
-            .replace("\n", " ")
-            .replace("/", "")
-            .replace("\t", " ")
-            .replace("{", "")
-            .replace("}", "")
+            .replace('\n', " ")
+            .replace('/', "")
+            .replace('\t', " ")
+            .replace('{', "")
+            .replace('}', "")
             .split(' ')
             .filter(|s| !s.is_empty())
             .collect::<Vec<&str>>()

From a957cefda63c76c7a91a705f683be45c684d4303 Mon Sep 17 00:00:00 2001
From: Frank Steffahn <frank.steffahn@stu.uni-kiel.de>
Date: Tue, 14 Dec 2021 15:23:34 +0100
Subject: [PATCH 7/9] Fix a bunch of typos

---
 library/alloc/tests/boxed.rs                   |  2 +-
 library/alloc/tests/str.rs                     |  2 +-
 library/core/src/alloc/layout.rs               |  4 ++--
 library/core/src/cell.rs                       |  6 +++---
 library/core/src/iter/adapters/zip.rs          |  2 +-
 library/core/src/iter/range.rs                 |  4 ++--
 library/core/src/num/dec2flt/number.rs         |  2 +-
 library/core/src/num/fmt.rs                    |  2 +-
 library/core/src/slice/iter.rs                 |  2 +-
 library/core/src/slice/rotate.rs               |  6 +++---
 library/core/src/str/iter.rs                   | 18 +++++++++---------
 library/core/tests/array.rs                    |  2 +-
 library/panic_unwind/src/emcc.rs               |  2 +-
 library/std/src/fs/tests.rs                    |  2 +-
 library/std/src/io/mod.rs                      |  4 ++--
 library/std/src/io/stdio.rs                    |  2 +-
 library/std/src/net/ip/tests.rs                |  2 +-
 library/std/src/panicking.rs                   |  6 +++---
 library/std/src/sys/itron/thread.rs            |  4 ++--
 library/std/src/sys/unix/kernel_copy.rs        |  2 +-
 .../src/sys/unix/process/process_fuchsia.rs    |  2 +-
 library/std/src/sys/unix/weak.rs               |  2 +-
 library/std/src/sys/wasm/alloc.rs              |  8 ++++----
 library/std/src/sys/wasm/atomics/mutex.rs      |  6 +++---
 library/std/src/sys/windows/stdio.rs           |  2 +-
 library/std/src/sys/windows/thread_parker.rs   |  2 +-
 .../src/sys_common/thread_parker/generic.rs    |  6 +++---
 library/std/src/thread/local.rs                |  4 ++--
 library/std/src/time.rs                        |  2 +-
 29 files changed, 55 insertions(+), 55 deletions(-)

diff --git a/library/alloc/tests/boxed.rs b/library/alloc/tests/boxed.rs
index a38b5c471bf06..bfe66b2687ef4 100644
--- a/library/alloc/tests/boxed.rs
+++ b/library/alloc/tests/boxed.rs
@@ -3,7 +3,7 @@ use std::mem::MaybeUninit;
 use std::ptr::NonNull;
 
 #[test]
-fn unitialized_zero_size_box() {
+fn uninitialized_zero_size_box() {
     assert_eq!(
         &*Box::<()>::new_uninit() as *const _,
         NonNull::<MaybeUninit<()>>::dangling().as_ptr(),
diff --git a/library/alloc/tests/str.rs b/library/alloc/tests/str.rs
index 1b741f174fb12..7bd0abbad0192 100644
--- a/library/alloc/tests/str.rs
+++ b/library/alloc/tests/str.rs
@@ -162,7 +162,7 @@ fn test_join_for_different_lengths_with_long_separator() {
 }
 
 #[test]
-fn test_join_isue_80335() {
+fn test_join_issue_80335() {
     use core::{borrow::Borrow, cell::Cell};
 
     struct WeirdBorrow {
diff --git a/library/core/src/alloc/layout.rs b/library/core/src/alloc/layout.rs
index 9df0b5c551915..ea639268652c3 100644
--- a/library/core/src/alloc/layout.rs
+++ b/library/core/src/alloc/layout.rs
@@ -157,11 +157,11 @@ impl Layout {
     ///
     /// - If `T` is `Sized`, this function is always safe to call.
     /// - If the unsized tail of `T` is:
-    ///     - a [slice], then the length of the slice tail must be an intialized
+    ///     - a [slice], then the length of the slice tail must be an initialized
     ///       integer, and the size of the *entire value*
     ///       (dynamic tail length + statically sized prefix) must fit in `isize`.
     ///     - a [trait object], then the vtable part of the pointer must point
-    ///       to a valid vtable for the type `T` acquired by an unsizing coersion,
+    ///       to a valid vtable for the type `T` acquired by an unsizing coercion,
     ///       and the size of the *entire value*
     ///       (dynamic tail length + statically sized prefix) must fit in `isize`.
     ///     - an (unstable) [extern type], then this function is always safe to
diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs
index 06dc5ecf2ffa6..bc3f7167fac3a 100644
--- a/library/core/src/cell.rs
+++ b/library/core/src/cell.rs
@@ -898,7 +898,7 @@ impl<T: ?Sized> RefCell<T> {
                 Ok(Ref { value: unsafe { &*self.value.get() }, borrow: b })
             }
             None => Err(BorrowError {
-                // If a borrow occured, then we must already have an outstanding borrow,
+                // If a borrow occurred, then we must already have an outstanding borrow,
                 // so `borrowed_at` will be `Some`
                 #[cfg(feature = "debug_refcell")]
                 location: self.borrowed_at.get().unwrap(),
@@ -983,7 +983,7 @@ impl<T: ?Sized> RefCell<T> {
                 Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b })
             }
             None => Err(BorrowMutError {
-                // If a borrow occured, then we must already have an outstanding borrow,
+                // If a borrow occurred, then we must already have an outstanding borrow,
                 // so `borrowed_at` will be `Some`
                 #[cfg(feature = "debug_refcell")]
                 location: self.borrowed_at.get().unwrap(),
@@ -1104,7 +1104,7 @@ impl<T: ?Sized> RefCell<T> {
             Ok(unsafe { &*self.value.get() })
         } else {
             Err(BorrowError {
-                // If a borrow occured, then we must already have an outstanding borrow,
+                // If a borrow occurred, then we must already have an outstanding borrow,
                 // so `borrowed_at` will be `Some`
                 #[cfg(feature = "debug_refcell")]
                 location: self.borrowed_at.get().unwrap(),
diff --git a/library/core/src/iter/adapters/zip.rs b/library/core/src/iter/adapters/zip.rs
index 920fa59c8ad6e..b8c3cd847e454 100644
--- a/library/core/src/iter/adapters/zip.rs
+++ b/library/core/src/iter/adapters/zip.rs
@@ -517,7 +517,7 @@ impl<A: Debug + TrustedRandomAccessNoCoerce, B: Debug + TrustedRandomAccessNoCoe
 /// * It must also be safe to drop `self` after calling `self.__iterator_get_unchecked(idx)`.
 /// * If `T` is a subtype of `Self`, then it must be safe to coerce `self` to `T`.
 //
-// FIXME: Clarify interaction with SourceIter/InPlaceIterable. Calling `SouceIter::as_inner`
+// FIXME: Clarify interaction with SourceIter/InPlaceIterable. Calling `SourceIter::as_inner`
 // after `__iterator_get_unchecked` is supposed to be allowed.
 #[doc(hidden)]
 #[unstable(feature = "trusted_random_access", issue = "none")]
diff --git a/library/core/src/iter/range.rs b/library/core/src/iter/range.rs
index 06733a1b50b91..0ae94c05da658 100644
--- a/library/core/src/iter/range.rs
+++ b/library/core/src/iter/range.rs
@@ -777,7 +777,7 @@ range_exact_iter_impl! {
     usize u8 u16
     isize i8 i16
 
-    // These are incorect per the reasoning above,
+    // These are incorrect per the reasoning above,
     // but removing them would be a breaking change as they were stabilized in Rust 1.0.0.
     // So e.g. `(0..66_000_u32).len()` for example will compile without error or warnings
     // on 16-bit platforms, but continue to give a wrong result.
@@ -805,7 +805,7 @@ range_incl_exact_iter_impl! {
     u8
     i8
 
-    // These are incorect per the reasoning above,
+    // These are incorrect per the reasoning above,
     // but removing them would be a breaking change as they were stabilized in Rust 1.26.0.
     // So e.g. `(0..=u16::MAX).len()` for example will compile without error or warnings
     // on 16-bit platforms, but continue to give a wrong result.
diff --git a/library/core/src/num/dec2flt/number.rs b/library/core/src/num/dec2flt/number.rs
index 36432718af40e..405f7e7b6135d 100644
--- a/library/core/src/num/dec2flt/number.rs
+++ b/library/core/src/num/dec2flt/number.rs
@@ -40,7 +40,7 @@ impl Number {
             && !self.many_digits
     }
 
-    /// The fast path algorithmn using machine-sized integers and floats.
+    /// The fast path algorithm using machine-sized integers and floats.
     ///
     /// This is extracted into a separate function so that it can be attempted before constructing
     /// a Decimal. This only works if both the mantissa and the exponent
diff --git a/library/core/src/num/fmt.rs b/library/core/src/num/fmt.rs
index 578288bda2595..ed61197157bf5 100644
--- a/library/core/src/num/fmt.rs
+++ b/library/core/src/num/fmt.rs
@@ -1,4 +1,4 @@
-//! Shared utilties used by both float and integer formatting.
+//! Shared utilities used by both float and integer formatting.
 #![doc(hidden)]
 #![unstable(
     feature = "numfmt",
diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs
index ad1d6b8b846a0..a487238124f13 100644
--- a/library/core/src/slice/iter.rs
+++ b/library/core/src/slice/iter.rs
@@ -221,7 +221,7 @@ impl<'a, T> IterMut<'a, T> {
         // the length, to also allows for the fast `ptr == end` check.
         //
         // See the `next_unchecked!` and `is_empty!` macros as well as the
-        // `post_inc_start` method for more informations.
+        // `post_inc_start` method for more information.
         unsafe {
             assume(!ptr.is_null());
 
diff --git a/library/core/src/slice/rotate.rs b/library/core/src/slice/rotate.rs
index 7528927ef33b9..4589c6c0f04a5 100644
--- a/library/core/src/slice/rotate.rs
+++ b/library/core/src/slice/rotate.rs
@@ -104,7 +104,7 @@ pub unsafe fn ptr_rotate<T>(mut left: usize, mut mid: *mut T, mut right: usize)
                 // - overflows cannot happen for `i` since the function's safety contract ask for
                 //   `mid+right-1 = x+left+right` to be valid for writing
                 // - underflows cannot happen because `i` must be bigger or equal to `left` for
-                //   a substraction of `left` to happen.
+                //   a subtraction of `left` to happen.
                 //
                 // So `x+i` is valid for reading and writing if the caller respected the contract
                 tmp = unsafe { x.add(i).replace(tmp) };
@@ -202,7 +202,7 @@ pub unsafe fn ptr_rotate<T>(mut left: usize, mut mid: *mut T, mut right: usize)
             loop {
                 // SAFETY:
                 // `left >= right` so `[mid-right, mid+right)` is valid for reading and writing
-                // Substracting `right` from `mid` each turn is counterbalanced by the addition and
+                // Subtracting `right` from `mid` each turn is counterbalanced by the addition and
                 // check after it.
                 unsafe {
                     ptr::swap_nonoverlapping(mid.sub(right), mid, right);
@@ -218,7 +218,7 @@ pub unsafe fn ptr_rotate<T>(mut left: usize, mut mid: *mut T, mut right: usize)
             loop {
                 // SAFETY: `[mid-left, mid+left)` is valid for reading and writing because
                 // `left < right` so `mid+left < mid+right`.
-                // Adding `left` to `mid` each turn is counterbalanced by the substraction and check
+                // Adding `left` to `mid` each turn is counterbalanced by the subtraction and check
                 // after it.
                 unsafe {
                     ptr::swap_nonoverlapping(mid.sub(left), mid, left);
diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs
index 4841044671659..de6e6d52b3625 100644
--- a/library/core/src/str/iter.rs
+++ b/library/core/src/str/iter.rs
@@ -748,7 +748,7 @@ generate_pattern_iterators! {
 }
 
 impl<'a, P: Pattern<'a>> Split<'a, P> {
-    /// Returns remainder of the splitted string
+    /// Returns remainder of the split string
     ///
     /// # Examples
     ///
@@ -769,7 +769,7 @@ impl<'a, P: Pattern<'a>> Split<'a, P> {
 }
 
 impl<'a, P: Pattern<'a>> RSplit<'a, P> {
-    /// Returns remainder of the splitted string
+    /// Returns remainder of the split string
     ///
     /// # Examples
     ///
@@ -808,7 +808,7 @@ generate_pattern_iterators! {
 }
 
 impl<'a, P: Pattern<'a>> SplitTerminator<'a, P> {
-    /// Returns remainder of the splitted string
+    /// Returns remainder of the split string
     ///
     /// # Examples
     ///
@@ -829,7 +829,7 @@ impl<'a, P: Pattern<'a>> SplitTerminator<'a, P> {
 }
 
 impl<'a, P: Pattern<'a>> RSplitTerminator<'a, P> {
-    /// Returns remainder of the splitted string
+    /// Returns remainder of the split string
     ///
     /// # Examples
     ///
@@ -931,7 +931,7 @@ generate_pattern_iterators! {
 }
 
 impl<'a, P: Pattern<'a>> SplitN<'a, P> {
-    /// Returns remainder of the splitted string
+    /// Returns remainder of the split string
     ///
     /// # Examples
     ///
@@ -952,7 +952,7 @@ impl<'a, P: Pattern<'a>> SplitN<'a, P> {
 }
 
 impl<'a, P: Pattern<'a>> RSplitN<'a, P> {
-    /// Returns remainder of the splitted string
+    /// Returns remainder of the split string
     ///
     /// # Examples
     ///
@@ -1236,7 +1236,7 @@ impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
 impl FusedIterator for SplitWhitespace<'_> {}
 
 impl<'a> SplitWhitespace<'a> {
-    /// Returns remainder of the splitted string
+    /// Returns remainder of the split string
     ///
     /// # Examples
     ///
@@ -1292,7 +1292,7 @@ impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
 impl FusedIterator for SplitAsciiWhitespace<'_> {}
 
 impl<'a> SplitAsciiWhitespace<'a> {
-    /// Returns remainder of the splitted string
+    /// Returns remainder of the split string
     ///
     /// # Examples
     ///
@@ -1360,7 +1360,7 @@ impl<'a, P: Pattern<'a, Searcher: ReverseSearcher<'a>>> DoubleEndedIterator
 impl<'a, P: Pattern<'a>> FusedIterator for SplitInclusive<'a, P> {}
 
 impl<'a, P: Pattern<'a>> SplitInclusive<'a, P> {
-    /// Returns remainder of the splitted string
+    /// Returns remainder of the split string
     ///
     /// # Examples
     ///
diff --git a/library/core/tests/array.rs b/library/core/tests/array.rs
index ceb6720079665..fe4fef749904e 100644
--- a/library/core/tests/array.rs
+++ b/library/core/tests/array.rs
@@ -259,7 +259,7 @@ fn iterator_drops() {
 // This test does not work on targets without panic=unwind support.
 // To work around this problem, test is marked is should_panic, so it will
 // be automagically skipped on unsuitable targets, such as
-// wasm32-unknown-unkown.
+// wasm32-unknown-unknown.
 //
 // It means that we use panic for indicating success.
 #[test]
diff --git a/library/panic_unwind/src/emcc.rs b/library/panic_unwind/src/emcc.rs
index e428f2fdaaa39..12f0fe9c3c3a9 100644
--- a/library/panic_unwind/src/emcc.rs
+++ b/library/panic_unwind/src/emcc.rs
@@ -49,7 +49,7 @@ static EXCEPTION_TYPE_INFO: TypeInfo = TypeInfo {
 };
 
 struct Exception {
-    // This is necessary because C++ code can capture our execption with
+    // This is necessary because C++ code can capture our exception with
     // std::exception_ptr and rethrow it multiple times, possibly even in
     // another thread.
     caught: AtomicBool,
diff --git a/library/std/src/fs/tests.rs b/library/std/src/fs/tests.rs
index 9a8f1e44f1f1c..2293fb6b55812 100644
--- a/library/std/src/fs/tests.rs
+++ b/library/std/src/fs/tests.rs
@@ -1369,7 +1369,7 @@ fn symlink_hard_link() {
     // "hard_link" should appear as a symlink.
     assert!(check!(fs::symlink_metadata(tmpdir.join("hard_link"))).file_type().is_symlink());
 
-    // We sould be able to open "file" via any of the above names.
+    // We should be able to open "file" via any of the above names.
     let _ = check!(fs::File::open(tmpdir.join("file")));
     assert!(fs::File::open(tmpdir.join("file.renamed")).is_err());
     let _ = check!(fs::File::open(tmpdir.join("symlink")));
diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs
index dd182c059b9cb..ecc9e91b6bdb2 100644
--- a/library/std/src/io/mod.rs
+++ b/library/std/src/io/mod.rs
@@ -362,7 +362,7 @@ pub(crate) fn default_read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>
     let start_len = buf.len();
     let start_cap = buf.capacity();
 
-    let mut initialized = 0; // Extra initalized bytes from previous loop iteration
+    let mut initialized = 0; // Extra initialized bytes from previous loop iteration
     loop {
         if buf.len() == buf.capacity() {
             buf.reserve(32); // buf is full, need more space
@@ -370,7 +370,7 @@ pub(crate) fn default_read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>
 
         let mut read_buf = ReadBuf::uninit(buf.spare_capacity_mut());
 
-        // SAFETY: These bytes were initalized but not filled in the previous loop
+        // SAFETY: These bytes were initialized but not filled in the previous loop
         unsafe {
             read_buf.assume_init(initialized);
         }
diff --git a/library/std/src/io/stdio.rs b/library/std/src/io/stdio.rs
index 9888d3a09c48d..c072f0cafe47b 100644
--- a/library/std/src/io/stdio.rs
+++ b/library/std/src/io/stdio.rs
@@ -1179,7 +1179,7 @@ where
             })
         }) == Ok(Some(()))
     {
-        // Succesfully wrote to capture buffer.
+        // Successfully wrote to capture buffer.
         return;
     }
 
diff --git a/library/std/src/net/ip/tests.rs b/library/std/src/net/ip/tests.rs
index 17581f330266d..632d4683b4159 100644
--- a/library/std/src/net/ip/tests.rs
+++ b/library/std/src/net/ip/tests.rs
@@ -749,7 +749,7 @@ fn ipv4_from_constructors() {
 }
 
 #[test]
-fn ipv6_from_contructors() {
+fn ipv6_from_constructors() {
     assert_eq!(Ipv6Addr::LOCALHOST, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
     assert!(Ipv6Addr::LOCALHOST.is_loopback());
     assert_eq!(Ipv6Addr::UNSPECIFIED, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs
index 6fc6b8daec0a6..87854fe4f2970 100644
--- a/library/std/src/panicking.rs
+++ b/library/std/src/panicking.rs
@@ -365,7 +365,7 @@ pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>>
     // The call to `intrinsics::r#try` is made safe by:
     // - `do_call`, the first argument, can be called with the initial `data_ptr`.
     // - `do_catch`, the second argument, can be called with the `data_ptr` as well.
-    // See their safety preconditions for more informations
+    // See their safety preconditions for more information
     unsafe {
         return if intrinsics::r#try(do_call::<F, R>, data_ptr, do_catch::<F, R>) == 0 {
             Ok(ManuallyDrop::into_inner(data.r))
@@ -398,7 +398,7 @@ pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>>
     // expects normal function pointers.
     #[inline]
     fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
-        // SAFETY: this is the responsibilty of the caller, see above.
+        // SAFETY: this is the responsibility of the caller, see above.
         unsafe {
             let data = data as *mut Data<F, R>;
             let data = &mut (*data);
@@ -420,7 +420,7 @@ pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>>
     // expects normal function pointers.
     #[inline]
     fn do_catch<F: FnOnce() -> R, R>(data: *mut u8, payload: *mut u8) {
-        // SAFETY: this is the responsibilty of the caller, see above.
+        // SAFETY: this is the responsibility of the caller, see above.
         //
         // When `__rustc_panic_cleaner` is correctly implemented we can rely
         // on `obj` being the correct thing to pass to `data.p` (after wrapping
diff --git a/library/std/src/sys/itron/thread.rs b/library/std/src/sys/itron/thread.rs
index bb9fa54d02ea4..ebcc9ab26e088 100644
--- a/library/std/src/sys/itron/thread.rs
+++ b/library/std/src/sys/itron/thread.rs
@@ -126,7 +126,7 @@ impl Thread {
                     // In this case, `inner`'s ownership has been moved to us,
                     // And we are responsible for dropping it. The acquire
                     // ordering is not necessary because the parent thread made
-                    // no memory acccess needing synchronization since the call
+                    // no memory access needing synchronization since the call
                     // to `acre_tsk`.
                     // Safety: See above.
                     let _ = unsafe { Box::from_raw(inner as *const _ as *mut ThreadInner) };
@@ -264,7 +264,7 @@ impl Drop for Thread {
                 // one will ever join it.
                 // The ownership of `self.inner` is moved to the child thread.
                 // However, the release ordering is not necessary because we
-                // made no memory acccess needing synchronization since the call
+                // made no memory access needing synchronization since the call
                 // to `acre_tsk`.
             }
             LIFECYCLE_FINISHED => {
diff --git a/library/std/src/sys/unix/kernel_copy.rs b/library/std/src/sys/unix/kernel_copy.rs
index 241cf89d3145c..e85e4c5d618ce 100644
--- a/library/std/src/sys/unix/kernel_copy.rs
+++ b/library/std/src/sys/unix/kernel_copy.rs
@@ -104,7 +104,7 @@ impl FdMeta {
 
     fn potential_sendfile_source(&self) -> bool {
         match self {
-            // procfs erronously shows 0 length on non-empty readable files.
+            // procfs erroneously shows 0 length on non-empty readable files.
             // and if a file is truly empty then a `read` syscall will determine that and skip the write syscall
             // thus there would be benefit from attempting sendfile
             FdMeta::Metadata(meta)
diff --git a/library/std/src/sys/unix/process/process_fuchsia.rs b/library/std/src/sys/unix/process/process_fuchsia.rs
index 507abb27871bf..ce77c210a6220 100644
--- a/library/std/src/sys/unix/process/process_fuchsia.rs
+++ b/library/std/src/sys/unix/process/process_fuchsia.rs
@@ -284,7 +284,7 @@ impl ExitStatus {
         //
         // The other view would be to say that the caller on Fuchsia ought to know that `into_raw`
         // will give a raw Fuchsia status (whatever that is - I don't know, personally).  That is
-        // not possible here becaause we must return a c_int because that's what Unix (including
+        // not possible here because we must return a c_int because that's what Unix (including
         // SuS and POSIX) say a wait status is, but Fuchsia apparently uses a u64, so it won't
         // necessarily fit.
         //
diff --git a/library/std/src/sys/unix/weak.rs b/library/std/src/sys/unix/weak.rs
index 32072affe8af4..55719b87c7e06 100644
--- a/library/std/src/sys/unix/weak.rs
+++ b/library/std/src/sys/unix/weak.rs
@@ -124,7 +124,7 @@ impl<F> DlsymWeak<F> {
         }
     }
 
-    // Cold because it should only happen during first-time initalization.
+    // Cold because it should only happen during first-time initialization.
     #[cold]
     unsafe fn initialize(&self) -> Option<F> {
         assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());
diff --git a/library/std/src/sys/wasm/alloc.rs b/library/std/src/sys/wasm/alloc.rs
index 3223e8941024c..6dceb1689a8b7 100644
--- a/library/std/src/sys/wasm/alloc.rs
+++ b/library/std/src/sys/wasm/alloc.rs
@@ -24,7 +24,7 @@ static mut DLMALLOC: dlmalloc::Dlmalloc = dlmalloc::Dlmalloc::new();
 unsafe impl GlobalAlloc for System {
     #[inline]
     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
-        // SAFETY: DLMALLOC access is guranteed to be safe because the lock gives us unique and non-reentrant access.
+        // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
         // Calling malloc() is safe because preconditions on this function match the trait method preconditions.
         let _lock = lock::lock();
         unsafe { DLMALLOC.malloc(layout.size(), layout.align()) }
@@ -32,7 +32,7 @@ unsafe impl GlobalAlloc for System {
 
     #[inline]
     unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
-        // SAFETY: DLMALLOC access is guranteed to be safe because the lock gives us unique and non-reentrant access.
+        // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
         // Calling calloc() is safe because preconditions on this function match the trait method preconditions.
         let _lock = lock::lock();
         unsafe { DLMALLOC.calloc(layout.size(), layout.align()) }
@@ -40,7 +40,7 @@ unsafe impl GlobalAlloc for System {
 
     #[inline]
     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
-        // SAFETY: DLMALLOC access is guranteed to be safe because the lock gives us unique and non-reentrant access.
+        // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
         // Calling free() is safe because preconditions on this function match the trait method preconditions.
         let _lock = lock::lock();
         unsafe { DLMALLOC.free(ptr, layout.size(), layout.align()) }
@@ -48,7 +48,7 @@ unsafe impl GlobalAlloc for System {
 
     #[inline]
     unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
-        // SAFETY: DLMALLOC access is guranteed to be safe because the lock gives us unique and non-reentrant access.
+        // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
         // Calling realloc() is safe because preconditions on this function match the trait method preconditions.
         let _lock = lock::lock();
         unsafe { DLMALLOC.realloc(ptr, layout.size(), layout.align(), new_size) }
diff --git a/library/std/src/sys/wasm/atomics/mutex.rs b/library/std/src/sys/wasm/atomics/mutex.rs
index 5ff0ec052b6f4..3a09f0bf9bb4c 100644
--- a/library/std/src/sys/wasm/atomics/mutex.rs
+++ b/library/std/src/sys/wasm/atomics/mutex.rs
@@ -73,7 +73,7 @@ pub struct ReentrantMutex {
 unsafe impl Send for ReentrantMutex {}
 unsafe impl Sync for ReentrantMutex {}
 
-// Reentrant mutexes are similarly implemented to mutexs above except that
+// Reentrant mutexes are similarly implemented to mutexes above except that
 // instead of "1" meaning unlocked we use the id of a thread to represent
 // whether it has locked a mutex. That way we have an atomic counter which
 // always holds the id of the thread that currently holds the lock (or 0 if the
@@ -96,7 +96,7 @@ impl ReentrantMutex {
     pub unsafe fn lock(&self) {
         let me = thread::my_id();
         while let Err(owner) = self._try_lock(me) {
-            // SAFETY: the caller must gurantee that `self.ptr()` and `owner` are valid i32.
+            // SAFETY: the caller must guarantee that `self.ptr()` and `owner` are valid i32.
             let val = unsafe { wasm32::memory_atomic_wait32(self.ptr(), owner as i32, -1) };
             debug_assert!(val == 0 || val == 1);
         }
@@ -136,7 +136,7 @@ impl ReentrantMutex {
         match *self.recursions.get() {
             0 => {
                 self.owner.swap(0, SeqCst);
-                // SAFETY: the caller must gurantee that `self.ptr()` is valid i32.
+                // SAFETY: the caller must guarantee that `self.ptr()` is valid i32.
                 unsafe {
                     wasm32::memory_atomic_notify(self.ptr() as *mut i32, 1);
                 } // wake up one waiter, if any
diff --git a/library/std/src/sys/windows/stdio.rs b/library/std/src/sys/windows/stdio.rs
index a4fe5f67f699a..eb0925b3fda7d 100644
--- a/library/std/src/sys/windows/stdio.rs
+++ b/library/std/src/sys/windows/stdio.rs
@@ -124,7 +124,7 @@ fn write(
     //
     // If the data is not valid UTF-8 we write out as many bytes as are valid.
     // If the first byte is invalid it is either first byte of a multi-byte sequence but the
-    // provided byte slice is too short or it is the first byte of an invalide multi-byte sequence.
+    // provided byte slice is too short or it is the first byte of an invalid multi-byte sequence.
     let len = cmp::min(data.len(), MAX_BUFFER_SIZE / 2);
     let utf8 = match str::from_utf8(&data[..len]) {
         Ok(s) => s,
diff --git a/library/std/src/sys/windows/thread_parker.rs b/library/std/src/sys/windows/thread_parker.rs
index 4f59d4dd452be..5a8011a958808 100644
--- a/library/std/src/sys/windows/thread_parker.rs
+++ b/library/std/src/sys/windows/thread_parker.rs
@@ -22,7 +22,7 @@
 //
 // Unlike WaitOnAddress, NtWaitForKeyedEvent/NtReleaseKeyedEvent operate on a
 // HANDLE (created with NtCreateKeyedEvent). This means that we can be sure
-// a succesfully awoken park() was awoken by unpark() and not a
+// a successfully awoken park() was awoken by unpark() and not a
 // NtReleaseKeyedEvent call from some other code, as these events are not only
 // matched by the key (address of the parker (state)), but also by this HANDLE.
 // We lazily allocate this handle the first time it is needed.
diff --git a/library/std/src/sys_common/thread_parker/generic.rs b/library/std/src/sys_common/thread_parker/generic.rs
index 14cfa958e5e53..d99e901bb5f83 100644
--- a/library/std/src/sys_common/thread_parker/generic.rs
+++ b/library/std/src/sys_common/thread_parker/generic.rs
@@ -1,4 +1,4 @@
-//! Parker implementaiton based on a Mutex and Condvar.
+//! Parker implementation based on a Mutex and Condvar.
 
 use crate::sync::atomic::AtomicUsize;
 use crate::sync::atomic::Ordering::SeqCst;
@@ -20,7 +20,7 @@ impl Parker {
         Parker { state: AtomicUsize::new(EMPTY), lock: Mutex::new(()), cvar: Condvar::new() }
     }
 
-    // This implementaiton doesn't require `unsafe`, but other implementations
+    // This implementation doesn't require `unsafe`, but other implementations
     // may assume this is only called by the thread that owns the Parker.
     pub unsafe fn park(&self) {
         // If we were previously notified then we consume this notification and
@@ -55,7 +55,7 @@ impl Parker {
         }
     }
 
-    // This implementaiton doesn't require `unsafe`, but other implementations
+    // This implementation doesn't require `unsafe`, but other implementations
     // may assume this is only called by the thread that owns the Parker.
     pub unsafe fn park_timeout(&self, dur: Duration) {
         // Like `park` above we have a fast path for an already-notified thread, and
diff --git a/library/std/src/thread/local.rs b/library/std/src/thread/local.rs
index c03fe116320aa..1d2f6e976800b 100644
--- a/library/std/src/thread/local.rs
+++ b/library/std/src/thread/local.rs
@@ -582,7 +582,7 @@ pub mod fast {
             Key { inner: LazyKeyInner::new(), dtor_state: Cell::new(DtorState::Unregistered) }
         }
 
-        // note that this is just a publically-callable function only for the
+        // note that this is just a publicly-callable function only for the
         // const-initialized form of thread locals, basically a way to call the
         // free `register_dtor` function defined elsewhere in libstd.
         pub unsafe fn register_dtor(a: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
@@ -593,7 +593,7 @@ pub mod fast {
 
         pub unsafe fn get<F: FnOnce() -> T>(&self, init: F) -> Option<&'static T> {
             // SAFETY: See the definitions of `LazyKeyInner::get` and
-            // `try_initialize` for more informations.
+            // `try_initialize` for more information.
             //
             // The caller must ensure no mutable references are ever active to
             // the inner cell or the inner T when this is called.
diff --git a/library/std/src/time.rs b/library/std/src/time.rs
index a5e3bd0c29030..86cc93c445376 100644
--- a/library/std/src/time.rs
+++ b/library/std/src/time.rs
@@ -273,7 +273,7 @@ impl Instant {
         // While issues have been seen on arm64 platforms the Arm architecture
         // requires that the counter monotonically increases and that it must
         // provide a uniform view of system time (e.g. it must not be possible
-        // for a core to recieve a message from another core with a time stamp
+        // for a core to receive a message from another core with a time stamp
         // and observe time going backwards (ARM DDI 0487G.b D11.1.2). While
         // there have been a few 64bit SoCs that have bugs which cause time to
         // not monoticially increase, these have been fixed in the Linux kernel

From 4f4b2c7271d3090b6b63bf1ce8373a47b5b30d86 Mon Sep 17 00:00:00 2001
From: Deadbeef <ent3rm4n@gmail.com>
Date: Wed, 15 Dec 2021 00:11:23 +0800
Subject: [PATCH 8/9] Constify `bool::then{,_some}`

---
 library/core/src/bool.rs   | 13 +++++++++++--
 library/core/tests/bool.rs | 14 ++++++++++++++
 library/core/tests/lib.rs  |  1 +
 3 files changed, 26 insertions(+), 2 deletions(-)

diff --git a/library/core/src/bool.rs b/library/core/src/bool.rs
index f14c2a4641627..d5119d0b7c328 100644
--- a/library/core/src/bool.rs
+++ b/library/core/src/bool.rs
@@ -14,8 +14,12 @@ impl bool {
     /// assert_eq!(true.then_some(0), Some(0));
     /// ```
     #[unstable(feature = "bool_to_option", issue = "80967")]
+    #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
     #[inline]
-    pub fn then_some<T>(self, t: T) -> Option<T> {
+    pub const fn then_some<T>(self, t: T) -> Option<T>
+    where
+        T: ~const Drop,
+    {
         if self { Some(t) } else { None }
     }
 
@@ -29,8 +33,13 @@ impl bool {
     /// assert_eq!(true.then(|| 0), Some(0));
     /// ```
     #[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
+    #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
     #[inline]
-    pub fn then<T, F: FnOnce() -> T>(self, f: F) -> Option<T> {
+    pub const fn then<T, F>(self, f: F) -> Option<T>
+    where
+        F: ~const FnOnce() -> T,
+        F: ~const Drop,
+    {
         if self { Some(f()) } else { None }
     }
 }
diff --git a/library/core/tests/bool.rs b/library/core/tests/bool.rs
index e40f0482aee3e..4819ce911d618 100644
--- a/library/core/tests/bool.rs
+++ b/library/core/tests/bool.rs
@@ -88,4 +88,18 @@ fn test_bool_to_option() {
     assert_eq!(true.then_some(0), Some(0));
     assert_eq!(false.then(|| 0), None);
     assert_eq!(true.then(|| 0), Some(0));
+
+    const fn zero() -> i32 {
+        0
+    }
+
+    const A: Option<i32> = false.then_some(0);
+    const B: Option<i32> = true.then_some(0);
+    const C: Option<i32> = false.then(zero);
+    const D: Option<i32> = true.then(zero);
+
+    assert_eq!(A, None);
+    assert_eq!(B, Some(0));
+    assert_eq!(C, None);
+    assert_eq!(D, Some(0));
 }
diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs
index b41d3e09df876..dacb33619f8c3 100644
--- a/library/core/tests/lib.rs
+++ b/library/core/tests/lib.rs
@@ -8,6 +8,7 @@
 #![feature(cfg_panic)]
 #![feature(cfg_target_has_atomic)]
 #![feature(const_assume)]
+#![feature(const_bool_to_option)]
 #![feature(const_cell_into_inner)]
 #![feature(const_convert)]
 #![feature(const_maybe_uninit_as_mut_ptr)]

From e4c44c5df707bb0b3de00d24e8b7735ab945362b Mon Sep 17 00:00:00 2001
From: Scott McMurray <scottmcm@users.noreply.github.com>
Date: Tue, 14 Dec 2021 15:48:46 -0800
Subject: [PATCH 9/9] Update comments per review feedback

---
 library/core/src/slice/mod.rs | 56 ++++++++++++++++++++++++++++-------
 1 file changed, 46 insertions(+), 10 deletions(-)

diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs
index 7797ae6d49ff2..59ac0e86943ee 100644
--- a/library/core/src/slice/mod.rs
+++ b/library/core/src/slice/mod.rs
@@ -3436,12 +3436,30 @@ impl<T> [T] {
         }
     }
 
-    /// Split a slice into a prefix, a middle of aligned simd types, and a suffix.
+    /// Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.
     ///
     /// This is a safe wrapper around [`slice::align_to`], so has the same weak
-    /// preconditions as that method.  Notably, you must not assume any particular
-    /// split between the three parts: it's legal for the middle slice to be
-    /// empty even if the input slice is longer than `3 * LANES`.
+    /// postconditions as that method.  You're only assured that
+    /// `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.
+    ///
+    /// Notably, all of the following are possible:
+    /// - `prefix.len() >= LANES`.
+    /// - `middle.is_empty()` despite `self.len() >= 3 * LANES`.
+    /// - `suffix.len() >= LANES`.
+    ///
+    /// That said, this is a safe method, so if you're only writing safe code,
+    /// then this can at most cause incorrect logic, not unsoundness.
+    ///
+    /// # Panics
+    ///
+    /// This will panic if the size of the SIMD type is different from
+    /// `LANES` times that of the scalar.
+    ///
+    /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
+    /// that from ever happening, as only power-of-two numbers of lanes are
+    /// supported.  It's possible that, in the future, those restrictions might
+    /// be lifted in a way that would make it possible to see panics from this
+    /// method for something like `LANES == 3`.
     ///
     /// # Examples
     ///
@@ -3491,14 +3509,32 @@ impl<T> [T] {
         unsafe { self.align_to() }
     }
 
-    /// Split a slice into a prefix, a middle of aligned simd types, and a suffix.
+    /// Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.
     ///
-    /// This is a safe wrapper around [`slice::align_to`], so has the same weak
-    /// preconditions as that method.  Notably, you must not assume any particular
-    /// split between the three parts: it's legal for the middle slice to be
-    /// empty even if the input slice is longer than `3 * LANES`.
+    /// This is a safe wrapper around [`slice::align_to_mut`], so has the same weak
+    /// postconditions as that method.  You're only assured that
+    /// `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.
+    ///
+    /// Notably, all of the following are possible:
+    /// - `prefix.len() >= LANES`.
+    /// - `middle.is_empty()` despite `self.len() >= 3 * LANES`.
+    /// - `suffix.len() >= LANES`.
+    ///
+    /// That said, this is a safe method, so if you're only writing safe code,
+    /// then this can at most cause incorrect logic, not unsoundness.
+    ///
+    /// This is the mutable version of [`slice::as_simd`]; see that for examples.
+    ///
+    /// # Panics
+    ///
+    /// This will panic if the size of the SIMD type is different from
+    /// `LANES` times that of the scalar.
     ///
-    /// This is the mutable version of [`slice::as_simd`]; see that for more.
+    /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
+    /// that from ever happening, as only power-of-two numbers of lanes are
+    /// supported.  It's possible that, in the future, those restrictions might
+    /// be lifted in a way that would make it possible to see panics from this
+    /// method for something like `LANES == 3`.
     #[unstable(feature = "portable_simd", issue = "86656")]
     #[cfg(not(miri))] // Miri does not support all SIMD intrinsics
     pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])