Use generic NonZero internally.

This commit is contained in:
Markus Reiter 2024-01-29 23:59:09 +01:00
parent ee9c7c940c
commit 746a58d435
No known key found for this signature in database
GPG Key ID: 245293B51702655B
144 changed files with 653 additions and 604 deletions

View File

@ -13,7 +13,7 @@ use rustc_session::parse::feature_err;
use rustc_session::{RustcVersion, Session}; use rustc_session::{RustcVersion, Session};
use rustc_span::hygiene::Transparency; use rustc_span::hygiene::Transparency;
use rustc_span::{symbol::sym, symbol::Symbol, Span}; use rustc_span::{symbol::sym, symbol::Symbol, Span};
use std::num::NonZeroU32; use std::num::NonZero;
use crate::session_diagnostics::{self, IncorrectReprFormatGenericCause}; use crate::session_diagnostics::{self, IncorrectReprFormatGenericCause};
@ -113,7 +113,7 @@ pub enum StabilityLevel {
/// Reason for the current stability level. /// Reason for the current stability level.
reason: UnstableReason, reason: UnstableReason,
/// Relevant `rust-lang/rust` issue. /// Relevant `rust-lang/rust` issue.
issue: Option<NonZeroU32>, issue: Option<NonZero<u32>>,
is_soft: bool, is_soft: bool,
/// If part of a feature is stabilized and a new feature is added for the remaining parts, /// If part of a feature is stabilized and a new feature is added for the remaining parts,
/// then the `implied_by` attribute is used to indicate which now-stable feature previously /// then the `implied_by` attribute is used to indicate which now-stable feature previously
@ -442,7 +442,7 @@ fn parse_unstability(sess: &Session, attr: &Attribute) -> Option<(Symbol, Stabil
// is a name/value pair string literal. // is a name/value pair string literal.
issue_num = match issue.unwrap().as_str() { issue_num = match issue.unwrap().as_str() {
"none" => None, "none" => None,
issue => match issue.parse::<NonZeroU32>() { issue => match issue.parse::<NonZero<u32>>() {
Ok(num) => Some(num), Ok(num) => Some(num),
Err(err) => { Err(err) => {
sess.dcx().emit_err( sess.dcx().emit_err(

View File

@ -7,6 +7,7 @@
#![allow(internal_features)] #![allow(internal_features)]
#![feature(rustdoc_internals)] #![feature(rustdoc_internals)]
#![doc(rust_logo)] #![doc(rust_logo)]
#![feature(generic_nonzero)]
#![feature(let_chains)] #![feature(let_chains)]
#[macro_use] #[macro_use]

View File

@ -5,7 +5,7 @@
//! to be const-safe. //! to be const-safe.
use std::fmt::Write; use std::fmt::Write;
use std::num::NonZeroUsize; use std::num::NonZero;
use either::{Left, Right}; use either::{Left, Right};
@ -782,7 +782,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
fn visit_union( fn visit_union(
&mut self, &mut self,
op: &OpTy<'tcx, M::Provenance>, op: &OpTy<'tcx, M::Provenance>,
_fields: NonZeroUsize, _fields: NonZero<usize>,
) -> InterpResult<'tcx> { ) -> InterpResult<'tcx> {
// Special check for CTFE validation, preventing `UnsafeCell` inside unions in immutable memory. // Special check for CTFE validation, preventing `UnsafeCell` inside unions in immutable memory.
if self.ctfe_mode.is_some_and(|c| !c.allow_immutable_unsafe_cell()) { if self.ctfe_mode.is_some_and(|c| !c.allow_immutable_unsafe_cell()) {

View File

@ -7,7 +7,7 @@ use rustc_middle::ty;
use rustc_target::abi::FieldIdx; use rustc_target::abi::FieldIdx;
use rustc_target::abi::{FieldsShape, VariantIdx, Variants}; use rustc_target::abi::{FieldsShape, VariantIdx, Variants};
use std::num::NonZeroUsize; use std::num::NonZero;
use super::{InterpCx, MPlaceTy, Machine, Projectable}; use super::{InterpCx, MPlaceTy, Machine, Projectable};
@ -43,7 +43,7 @@ pub trait ValueVisitor<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>>: Sized {
} }
/// Visits the given value as a union. No automatic recursion can happen here. /// Visits the given value as a union. No automatic recursion can happen here.
#[inline(always)] #[inline(always)]
fn visit_union(&mut self, _v: &Self::V, _fields: NonZeroUsize) -> InterpResult<'tcx> { fn visit_union(&mut self, _v: &Self::V, _fields: NonZero<usize>) -> InterpResult<'tcx> {
Ok(()) Ok(())
} }
/// Visits the given value as the pointer of a `Box`. There is nothing to recurse into. /// Visits the given value as the pointer of a `Box`. There is nothing to recurse into.

View File

@ -11,6 +11,7 @@ Rust MIR: a lowered representation of Rust.
#![feature(assert_matches)] #![feature(assert_matches)]
#![feature(box_patterns)] #![feature(box_patterns)]
#![feature(decl_macro)] #![feature(decl_macro)]
#![feature(generic_nonzero)]
#![feature(let_chains)] #![feature(let_chains)]
#![feature(slice_ptr_get)] #![feature(slice_ptr_get)]
#![feature(never_type)] #![feature(never_type)]

View File

@ -20,6 +20,7 @@
#![feature(cfg_match)] #![feature(cfg_match)]
#![feature(core_intrinsics)] #![feature(core_intrinsics)]
#![feature(extend_one)] #![feature(extend_one)]
#![feature(generic_nonzero)]
#![feature(hash_raw_entry)] #![feature(hash_raw_entry)]
#![feature(hasher_prefixfree_extras)] #![feature(hasher_prefixfree_extras)]
#![feature(lazy_cell)] #![feature(lazy_cell)]

View File

@ -6,6 +6,7 @@ use std::fmt;
use std::hash::{BuildHasher, Hash, Hasher}; use std::hash::{BuildHasher, Hash, Hasher};
use std::marker::PhantomData; use std::marker::PhantomData;
use std::mem; use std::mem;
use std::num::NonZero;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
@ -338,14 +339,14 @@ impl<CTX, T> HashStable<CTX> for PhantomData<T> {
fn hash_stable(&self, _ctx: &mut CTX, _hasher: &mut StableHasher) {} fn hash_stable(&self, _ctx: &mut CTX, _hasher: &mut StableHasher) {}
} }
impl<CTX> HashStable<CTX> for ::std::num::NonZeroU32 { impl<CTX> HashStable<CTX> for NonZero<u32> {
#[inline] #[inline]
fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
self.get().hash_stable(ctx, hasher) self.get().hash_stable(ctx, hasher)
} }
} }
impl<CTX> HashStable<CTX> for ::std::num::NonZeroUsize { impl<CTX> HashStable<CTX> for NonZero<usize> {
#[inline] #[inline]
fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
self.get().hash_stable(ctx, hasher) self.get().hash_stable(ctx, hasher)

View File

@ -1,7 +1,7 @@
use parking_lot::Mutex; use parking_lot::Mutex;
use std::cell::Cell; use std::cell::Cell;
use std::cell::OnceCell; use std::cell::OnceCell;
use std::num::NonZeroUsize; use std::num::NonZero;
use std::ops::Deref; use std::ops::Deref;
use std::ptr; use std::ptr;
use std::sync::Arc; use std::sync::Arc;
@ -31,7 +31,7 @@ impl RegistryId {
} }
struct RegistryData { struct RegistryData {
thread_limit: NonZeroUsize, thread_limit: NonZero<usize>,
threads: Mutex<usize>, threads: Mutex<usize>,
} }
@ -61,7 +61,7 @@ thread_local! {
impl Registry { impl Registry {
/// Creates a registry which can hold up to `thread_limit` threads. /// Creates a registry which can hold up to `thread_limit` threads.
pub fn new(thread_limit: NonZeroUsize) -> Self { pub fn new(thread_limit: NonZero<usize>) -> Self {
Registry(Arc::new(RegistryData { thread_limit, threads: Mutex::new(0) })) Registry(Arc::new(RegistryData { thread_limit, threads: Mutex::new(0) }))
} }

View File

@ -4,7 +4,7 @@ use std::fmt;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::marker::PhantomData; use std::marker::PhantomData;
use std::mem::ManuallyDrop; use std::mem::ManuallyDrop;
use std::num::NonZeroUsize; use std::num::NonZero;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::ptr::NonNull; use std::ptr::NonNull;
@ -134,7 +134,7 @@ where
ptr.map_addr(|addr| { ptr.map_addr(|addr| {
// Safety: // Safety:
// - The pointer is `NonNull` => it's address is `NonZeroUsize` // - The pointer is `NonNull` => it's address is `NonZero<usize>`
// - `P::BITS` least significant bits are always zero (`Pointer` contract) // - `P::BITS` least significant bits are always zero (`Pointer` contract)
// - `T::BITS <= P::BITS` (from `Self::ASSERTION`) // - `T::BITS <= P::BITS` (from `Self::ASSERTION`)
// //
@ -143,14 +143,15 @@ where
// `{non_zero} | packed_tag` can't make the value zero. // `{non_zero} | packed_tag` can't make the value zero.
let packed = (addr.get() >> T::BITS) | packed_tag; let packed = (addr.get() >> T::BITS) | packed_tag;
unsafe { NonZeroUsize::new_unchecked(packed) } unsafe { NonZero::<usize>::new_unchecked(packed) }
}) })
} }
/// Retrieves the original raw pointer from `self.packed`. /// Retrieves the original raw pointer from `self.packed`.
#[inline] #[inline]
pub(super) fn pointer_raw(&self) -> NonNull<P::Target> { pub(super) fn pointer_raw(&self) -> NonNull<P::Target> {
self.packed.map_addr(|addr| unsafe { NonZeroUsize::new_unchecked(addr.get() << T::BITS) }) self.packed
.map_addr(|addr| unsafe { NonZero::<usize>::new_unchecked(addr.get() << T::BITS) })
} }
/// This provides a reference to the `P` pointer itself, rather than the /// This provides a reference to the `P` pointer itself, rather than the

View File

@ -79,7 +79,7 @@ into_diagnostic_arg_using_display!(
ast::ParamKindOrd, ast::ParamKindOrd,
std::io::Error, std::io::Error,
Box<dyn std::error::Error>, Box<dyn std::error::Error>,
std::num::NonZeroU32, std::num::NonZero<u32>,
hir::Target, hir::Target,
Edition, Edition,
Ident, Ident,

View File

@ -16,6 +16,7 @@
#![feature(box_patterns)] #![feature(box_patterns)]
#![feature(error_reporter)] #![feature(error_reporter)]
#![feature(extract_if)] #![feature(extract_if)]
#![feature(generic_nonzero)]
#![feature(let_chains)] #![feature(let_chains)]
#![feature(negative_impls)] #![feature(negative_impls)]
#![feature(never_type)] #![feature(never_type)]
@ -77,7 +78,7 @@ use std::error::Report;
use std::fmt; use std::fmt;
use std::hash::Hash; use std::hash::Hash;
use std::io::Write; use std::io::Write;
use std::num::NonZeroUsize; use std::num::NonZero;
use std::ops::DerefMut; use std::ops::DerefMut;
use std::panic; use std::panic;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -545,7 +546,7 @@ pub struct DiagCtxtFlags {
pub can_emit_warnings: bool, pub can_emit_warnings: bool,
/// If Some, the Nth error-level diagnostic is upgraded to bug-level. /// If Some, the Nth error-level diagnostic is upgraded to bug-level.
/// (rustc: see `-Z treat-err-as-bug`) /// (rustc: see `-Z treat-err-as-bug`)
pub treat_err_as_bug: Option<NonZeroUsize>, pub treat_err_as_bug: Option<NonZero<usize>>,
/// Eagerly emit delayed bugs as errors, so that the compiler debugger may /// Eagerly emit delayed bugs as errors, so that the compiler debugger may
/// see all of the errors being emitted at once. /// see all of the errors being emitted at once.
pub eagerly_emit_delayed_bugs: bool, pub eagerly_emit_delayed_bugs: bool,

View File

@ -12,6 +12,7 @@
//! symbol to the `accepted` or `removed` modules respectively. //! symbol to the `accepted` or `removed` modules respectively.
#![allow(internal_features)] #![allow(internal_features)]
#![feature(generic_nonzero)]
#![feature(rustdoc_internals)] #![feature(rustdoc_internals)]
#![doc(rust_logo)] #![doc(rust_logo)]
#![feature(lazy_cell)] #![feature(lazy_cell)]
@ -25,13 +26,13 @@ mod unstable;
mod tests; mod tests;
use rustc_span::symbol::Symbol; use rustc_span::symbol::Symbol;
use std::num::NonZeroU32; use std::num::NonZero;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Feature { pub struct Feature {
pub name: Symbol, pub name: Symbol,
pub since: &'static str, pub since: &'static str,
issue: Option<NonZeroU32>, issue: Option<NonZero<u32>>,
} }
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
@ -85,7 +86,7 @@ impl UnstableFeatures {
} }
} }
fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> { fn find_lang_feature_issue(feature: Symbol) -> Option<NonZero<u32>> {
// Search in all the feature lists. // Search in all the feature lists.
if let Some(f) = UNSTABLE_FEATURES.iter().find(|f| f.feature.name == feature) { if let Some(f) = UNSTABLE_FEATURES.iter().find(|f| f.feature.name == feature) {
return f.feature.issue; return f.feature.issue;
@ -99,21 +100,21 @@ fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
panic!("feature `{feature}` is not declared anywhere"); panic!("feature `{feature}` is not declared anywhere");
} }
const fn to_nonzero(n: Option<u32>) -> Option<NonZeroU32> { const fn to_nonzero(n: Option<u32>) -> Option<NonZero<u32>> {
// Can be replaced with `n.and_then(NonZeroU32::new)` if that is ever usable // Can be replaced with `n.and_then(NonZero::new)` if that is ever usable
// in const context. Requires https://github.com/rust-lang/rfcs/pull/2632. // in const context. Requires https://github.com/rust-lang/rfcs/pull/2632.
match n { match n {
None => None, None => None,
Some(n) => NonZeroU32::new(n), Some(n) => NonZero::<u32>::new(n),
} }
} }
pub enum GateIssue { pub enum GateIssue {
Language, Language,
Library(Option<NonZeroU32>), Library(Option<NonZero<u32>>),
} }
pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZeroU32> { pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u32>> {
match issue { match issue {
GateIssue::Language => find_lang_feature_issue(feature), GateIssue::Language => find_lang_feature_issue(feature),
GateIssue::Library(lib) => lib, GateIssue::Library(lib) => lib,

View File

@ -74,7 +74,7 @@ pub mod wfcheck;
pub use check::check_abi; pub use check::check_abi;
use std::num::NonZeroU32; use std::num::NonZero;
use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::ErrorGuaranteed; use rustc_errors::ErrorGuaranteed;
@ -270,7 +270,7 @@ fn default_body_is_unstable(
item_did: DefId, item_did: DefId,
feature: Symbol, feature: Symbol,
reason: Option<Symbol>, reason: Option<Symbol>,
issue: Option<NonZeroU32>, issue: Option<NonZero<u32>>,
) { ) {
let missing_item_name = tcx.associated_item(item_did).name; let missing_item_name = tcx.associated_item(item_did).name;
let (mut some_note, mut none_note, mut reason_str) = (false, false, String::new()); let (mut some_note, mut none_note, mut reason_str) = (false, false, String::new());

View File

@ -63,6 +63,7 @@ This API is completely unstable and subject to change.
#![feature(rustdoc_internals)] #![feature(rustdoc_internals)]
#![allow(internal_features)] #![allow(internal_features)]
#![feature(control_flow_enum)] #![feature(control_flow_enum)]
#![feature(generic_nonzero)]
#![feature(if_let_guard)] #![feature(if_let_guard)]
#![feature(is_sorted)] #![feature(is_sorted)]
#![feature(iter_intersperse)] #![feature(iter_intersperse)]

View File

@ -1,5 +1,6 @@
#![feature(decl_macro)] #![feature(decl_macro)]
#![feature(error_iter)] #![feature(error_iter)]
#![feature(generic_nonzero)]
#![feature(lazy_cell)] #![feature(lazy_cell)]
#![feature(let_chains)] #![feature(let_chains)]
#![feature(thread_spawn_unchecked)] #![feature(thread_spawn_unchecked)]

View File

@ -20,7 +20,7 @@ use rustc_span::{FileName, SourceFileHashAlgorithm};
use rustc_target::spec::{CodeModel, LinkerFlavorCli, MergeFunctions, PanicStrategy, RelocModel}; use rustc_target::spec::{CodeModel, LinkerFlavorCli, MergeFunctions, PanicStrategy, RelocModel};
use rustc_target::spec::{RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, TlsModel}; use rustc_target::spec::{RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, TlsModel};
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
use std::num::NonZeroUsize; use std::num::NonZero;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
@ -827,7 +827,7 @@ fn test_unstable_options_tracking_hash() {
tracked!(tls_model, Some(TlsModel::GeneralDynamic)); tracked!(tls_model, Some(TlsModel::GeneralDynamic));
tracked!(translate_remapped_path_to_local_path, false); tracked!(translate_remapped_path_to_local_path, false);
tracked!(trap_unreachable, Some(false)); tracked!(trap_unreachable, Some(false));
tracked!(treat_err_as_bug, NonZeroUsize::new(1)); tracked!(treat_err_as_bug, NonZero::<usize>::new(1));
tracked!(tune_cpu, Some(String::from("abc"))); tracked!(tune_cpu, Some(String::from("abc")));
tracked!(uninit_const_chunk_threshold, 123); tracked!(uninit_const_chunk_threshold, 123);
tracked!(unleash_the_miri_inside_of_you, true); tracked!(unleash_the_miri_inside_of_you, true);

View File

@ -107,7 +107,7 @@ pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
use rustc_query_impl::QueryCtxt; use rustc_query_impl::QueryCtxt;
use rustc_query_system::query::{deadlock, QueryContext}; use rustc_query_system::query::{deadlock, QueryContext};
let registry = sync::Registry::new(std::num::NonZeroUsize::new(threads).unwrap()); let registry = sync::Registry::new(std::num::NonZero::<usize>::new(threads).unwrap());
if !sync::is_dyn_thread_safe() { if !sync::is_dyn_thread_safe() {
return run_in_thread_with_globals(edition, || { return run_in_thread_with_globals(edition, || {

View File

@ -31,6 +31,7 @@
#![feature(array_windows)] #![feature(array_windows)]
#![feature(box_patterns)] #![feature(box_patterns)]
#![feature(control_flow_enum)] #![feature(control_flow_enum)]
#![feature(generic_nonzero)]
#![feature(if_let_guard)] #![feature(if_let_guard)]
#![feature(iter_order_by)] #![feature(iter_order_by)]
#![feature(let_chains)] #![feature(let_chains)]

View File

@ -1,7 +1,6 @@
#![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)] #![allow(rustc::untranslatable_diagnostic)]
use std::num::NonZero;
use std::num::NonZeroU32;
use crate::errors::RequestedLevel; use crate::errors::RequestedLevel;
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
@ -402,7 +401,7 @@ pub struct BuiltinIncompleteFeaturesHelp;
#[derive(Subdiagnostic)] #[derive(Subdiagnostic)]
#[note(lint_note)] #[note(lint_note)]
pub struct BuiltinFeatureIssueNote { pub struct BuiltinFeatureIssueNote {
pub n: NonZeroU32, pub n: NonZero<u32>,
} }
pub struct BuiltinUnpermittedTypeInit<'a> { pub struct BuiltinUnpermittedTypeInit<'a> {

View File

@ -5,6 +5,7 @@
#![feature(decl_macro)] #![feature(decl_macro)]
#![feature(extract_if)] #![feature(extract_if)]
#![feature(coroutines)] #![feature(coroutines)]
#![feature(generic_nonzero)]
#![feature(iter_from_coroutine)] #![feature(iter_from_coroutine)]
#![feature(let_chains)] #![feature(let_chains)]
#![feature(if_let_guard)] #![feature(if_let_guard)]

View File

@ -327,7 +327,7 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
} }
#[inline] #[inline]
fn read_lazy_offset_then<T>(&mut self, f: impl Fn(NonZeroUsize) -> T) -> T { fn read_lazy_offset_then<T>(&mut self, f: impl Fn(NonZero<usize>) -> T) -> T {
let distance = self.read_usize(); let distance = self.read_usize();
let position = match self.lazy_state { let position = match self.lazy_state {
LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"), LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
@ -338,7 +338,7 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
} }
LazyState::Previous(last_pos) => last_pos.get() + distance, LazyState::Previous(last_pos) => last_pos.get() + distance,
}; };
let position = NonZeroUsize::new(position).unwrap(); let position = NonZero::<usize>::new(position).unwrap();
self.lazy_state = LazyState::Previous(position); self.lazy_state = LazyState::Previous(position);
f(position) f(position)
} }
@ -685,15 +685,17 @@ impl MetadataBlob {
} }
pub(crate) fn get_rustc_version(&self) -> String { pub(crate) fn get_rustc_version(&self) -> String {
LazyValue::<String>::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 8).unwrap()) LazyValue::<String>::from_position(
NonZero::<usize>::new(METADATA_HEADER.len() + 8).unwrap(),
)
.decode(self) .decode(self)
} }
fn root_pos(&self) -> NonZeroUsize { fn root_pos(&self) -> NonZero<usize> {
let offset = METADATA_HEADER.len(); let offset = METADATA_HEADER.len();
let pos_bytes = self.blob()[offset..][..8].try_into().unwrap(); let pos_bytes = self.blob()[offset..][..8].try_into().unwrap();
let pos = u64::from_le_bytes(pos_bytes); let pos = u64::from_le_bytes(pos_bytes);
NonZeroUsize::new(pos as usize).unwrap() NonZero::<usize>::new(pos as usize).unwrap()
} }
pub(crate) fn get_header(&self) -> CrateHeader { pub(crate) fn get_header(&self) -> CrateHeader {

View File

@ -421,7 +421,7 @@ macro_rules! record_defaulted_array {
} }
impl<'a, 'tcx> EncodeContext<'a, 'tcx> { impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
fn emit_lazy_distance(&mut self, position: NonZeroUsize) { fn emit_lazy_distance(&mut self, position: NonZero<usize>) {
let pos = position.get(); let pos = position.get();
let distance = match self.lazy_state { let distance = match self.lazy_state {
LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
@ -439,7 +439,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
position.get() - last_pos.get() position.get() - last_pos.get()
} }
}; };
self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap()); self.lazy_state = LazyState::Previous(NonZero::<usize>::new(pos).unwrap());
self.emit_usize(distance); self.emit_usize(distance);
} }
@ -447,7 +447,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
where where
T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>, T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
{ {
let pos = NonZeroUsize::new(self.position()).unwrap(); let pos = NonZero::<usize>::new(self.position()).unwrap();
assert_eq!(self.lazy_state, LazyState::NoNode); assert_eq!(self.lazy_state, LazyState::NoNode);
self.lazy_state = LazyState::NodeStart(pos); self.lazy_state = LazyState::NodeStart(pos);
@ -466,7 +466,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
where where
T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>, T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
{ {
let pos = NonZeroUsize::new(self.position()).unwrap(); let pos = NonZero::<usize>::new(self.position()).unwrap();
assert_eq!(self.lazy_state, LazyState::NoNode); assert_eq!(self.lazy_state, LazyState::NoNode);
self.lazy_state = LazyState::NodeStart(pos); self.lazy_state = LazyState::NodeStart(pos);

View File

@ -37,7 +37,7 @@ use rustc_target::abi::{FieldIdx, VariantIdx};
use rustc_target::spec::{PanicStrategy, TargetTriple}; use rustc_target::spec::{PanicStrategy, TargetTriple};
use std::marker::PhantomData; use std::marker::PhantomData;
use std::num::NonZeroUsize; use std::num::NonZero;
use decoder::DecodeContext; use decoder::DecodeContext;
pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob}; pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob};
@ -83,7 +83,7 @@ pub const METADATA_HEADER: &[u8] = &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_V
/// order than they were encoded in. /// order than they were encoded in.
#[must_use] #[must_use]
struct LazyValue<T> { struct LazyValue<T> {
position: NonZeroUsize, position: NonZero<usize>,
_marker: PhantomData<fn() -> T>, _marker: PhantomData<fn() -> T>,
} }
@ -92,7 +92,7 @@ impl<T: ParameterizedOverTcx> ParameterizedOverTcx for LazyValue<T> {
} }
impl<T> LazyValue<T> { impl<T> LazyValue<T> {
fn from_position(position: NonZeroUsize) -> LazyValue<T> { fn from_position(position: NonZero<usize>) -> LazyValue<T> {
LazyValue { position, _marker: PhantomData } LazyValue { position, _marker: PhantomData }
} }
} }
@ -108,7 +108,7 @@ impl<T> LazyValue<T> {
/// the minimal distance the length of the sequence, i.e. /// the minimal distance the length of the sequence, i.e.
/// it's assumed there's no 0-byte element in the sequence. /// it's assumed there's no 0-byte element in the sequence.
struct LazyArray<T> { struct LazyArray<T> {
position: NonZeroUsize, position: NonZero<usize>,
num_elems: usize, num_elems: usize,
_marker: PhantomData<fn() -> T>, _marker: PhantomData<fn() -> T>,
} }
@ -119,12 +119,12 @@ impl<T: ParameterizedOverTcx> ParameterizedOverTcx for LazyArray<T> {
impl<T> Default for LazyArray<T> { impl<T> Default for LazyArray<T> {
fn default() -> LazyArray<T> { fn default() -> LazyArray<T> {
LazyArray::from_position_and_num_elems(NonZeroUsize::new(1).unwrap(), 0) LazyArray::from_position_and_num_elems(NonZero::<usize>::new(1).unwrap(), 0)
} }
} }
impl<T> LazyArray<T> { impl<T> LazyArray<T> {
fn from_position_and_num_elems(position: NonZeroUsize, num_elems: usize) -> LazyArray<T> { fn from_position_and_num_elems(position: NonZero<usize>, num_elems: usize) -> LazyArray<T> {
LazyArray { position, num_elems, _marker: PhantomData } LazyArray { position, num_elems, _marker: PhantomData }
} }
} }
@ -135,7 +135,7 @@ impl<T> LazyArray<T> {
/// `LazyArray<T>`, but without requiring encoding or decoding all the values /// `LazyArray<T>`, but without requiring encoding or decoding all the values
/// eagerly and in-order. /// eagerly and in-order.
struct LazyTable<I, T> { struct LazyTable<I, T> {
position: NonZeroUsize, position: NonZero<usize>,
/// The encoded size of the elements of a table is selected at runtime to drop /// The encoded size of the elements of a table is selected at runtime to drop
/// trailing zeroes. This is the number of bytes used for each table element. /// trailing zeroes. This is the number of bytes used for each table element.
width: usize, width: usize,
@ -150,7 +150,7 @@ impl<I: 'static, T: ParameterizedOverTcx> ParameterizedOverTcx for LazyTable<I,
impl<I, T> LazyTable<I, T> { impl<I, T> LazyTable<I, T> {
fn from_position_and_encoded_size( fn from_position_and_encoded_size(
position: NonZeroUsize, position: NonZero<usize>,
width: usize, width: usize,
len: usize, len: usize,
) -> LazyTable<I, T> { ) -> LazyTable<I, T> {
@ -187,11 +187,11 @@ enum LazyState {
/// Inside a metadata node, and before any `Lazy`s. /// Inside a metadata node, and before any `Lazy`s.
/// The position is that of the node itself. /// The position is that of the node itself.
NodeStart(NonZeroUsize), NodeStart(NonZero<usize>),
/// Inside a metadata node, with a previous `Lazy`s. /// Inside a metadata node, with a previous `Lazy`s.
/// The position is where that previous `Lazy` would start. /// The position is where that previous `Lazy` would start.
Previous(NonZeroUsize), Previous(NonZero<usize>),
} }
type SyntaxContextTable = LazyTable<u32, Option<LazyValue<SyntaxContextData>>>; type SyntaxContextTable = LazyTable<u32, Option<LazyValue<SyntaxContextData>>>;

View File

@ -339,7 +339,7 @@ impl<T> FixedSizeEncoding for Option<LazyValue<T>> {
#[inline] #[inline]
fn from_bytes(b: &[u8; 8]) -> Self { fn from_bytes(b: &[u8; 8]) -> Self {
let position = NonZeroUsize::new(u64::from_bytes(b) as usize)?; let position = NonZero::<usize>::new(u64::from_bytes(b) as usize)?;
Some(LazyValue::from_position(position)) Some(LazyValue::from_position(position))
} }
@ -366,7 +366,7 @@ impl<T> LazyArray<T> {
} }
fn from_bytes_impl(position: &[u8; 8], meta: &[u8; 8]) -> Option<LazyArray<T>> { fn from_bytes_impl(position: &[u8; 8], meta: &[u8; 8]) -> Option<LazyArray<T>> {
let position = NonZeroUsize::new(u64::from_bytes(position) as usize)?; let position = NonZero::<usize>::new(u64::from_bytes(position) as usize)?;
let len = u64::from_bytes(meta) as usize; let len = u64::from_bytes(meta) as usize;
Some(LazyArray::from_position_and_num_elems(position, len)) Some(LazyArray::from_position_and_num_elems(position, len))
} }
@ -497,7 +497,7 @@ impl<I: Idx, const N: usize, T: FixedSizeEncoding<ByteArray = [u8; N]>> TableBui
} }
LazyTable::from_position_and_encoded_size( LazyTable::from_position_and_encoded_size(
NonZeroUsize::new(pos).unwrap(), NonZero::<usize>::new(pos).unwrap(),
width, width,
self.blocks.len(), self.blocks.len(),
) )

View File

@ -34,6 +34,7 @@
#![feature(discriminant_kind)] #![feature(discriminant_kind)]
#![feature(exhaustive_patterns)] #![feature(exhaustive_patterns)]
#![feature(coroutines)] #![feature(coroutines)]
#![feature(generic_nonzero)]
#![feature(if_let_guard)] #![feature(if_let_guard)]
#![feature(inline_const)] #![feature(inline_const)]
#![feature(iter_from_coroutine)] #![feature(iter_from_coroutine)]

View File

@ -21,7 +21,7 @@ use rustc_session::parse::feature_err_issue;
use rustc_session::Session; use rustc_session::Session;
use rustc_span::symbol::{sym, Symbol}; use rustc_span::symbol::{sym, Symbol};
use rustc_span::Span; use rustc_span::Span;
use std::num::NonZeroU32; use std::num::NonZero;
#[derive(PartialEq, Clone, Copy, Debug)] #[derive(PartialEq, Clone, Copy, Debug)]
pub enum StabilityLevel { pub enum StabilityLevel {
@ -102,7 +102,7 @@ pub fn report_unstable(
sess: &Session, sess: &Session,
feature: Symbol, feature: Symbol,
reason: Option<Symbol>, reason: Option<Symbol>,
issue: Option<NonZeroU32>, issue: Option<NonZero<u32>>,
suggestion: Option<(Span, String, String, Applicability)>, suggestion: Option<(Span, String, String, Applicability)>,
is_soft: bool, is_soft: bool,
span: Span, span: Span,
@ -235,7 +235,7 @@ pub enum EvalResult {
Deny { Deny {
feature: Symbol, feature: Symbol,
reason: Option<Symbol>, reason: Option<Symbol>,
issue: Option<NonZeroU32>, issue: Option<NonZero<u32>>,
suggestion: Option<(Span, String, String, Applicability)>, suggestion: Option<(Span, String, String, Applicability)>,
is_soft: bool, is_soft: bool,
}, },
@ -433,7 +433,7 @@ impl<'tcx> TyCtxt<'tcx> {
// the `-Z force-unstable-if-unmarked` flag present (we're // the `-Z force-unstable-if-unmarked` flag present (we're
// compiling a compiler crate), then let this missing feature // compiling a compiler crate), then let this missing feature
// annotation slide. // annotation slide.
if feature == sym::rustc_private && issue == NonZeroU32::new(27812) { if feature == sym::rustc_private && issue == NonZero::<u32>::new(27812) {
if self.sess.opts.unstable_opts.force_unstable_if_unmarked { if self.sess.opts.unstable_opts.force_unstable_if_unmarked {
return EvalResult::Allow; return EvalResult::Allow;
} }

View File

@ -122,7 +122,7 @@ mod value;
use std::fmt; use std::fmt;
use std::io; use std::io;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::num::{NonZeroU32, NonZeroU64}; use std::num::NonZero;
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
use rustc_ast::LitKind; use rustc_ast::LitKind;
@ -205,7 +205,7 @@ pub enum LitToConstError {
} }
#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)] #[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AllocId(pub NonZeroU64); pub struct AllocId(pub NonZero<u64>);
// We want the `Debug` output to be readable as it is used by `derive(Debug)` for // We want the `Debug` output to be readable as it is used by `derive(Debug)` for
// all the Miri types. // all the Miri types.
@ -260,7 +260,7 @@ pub fn specialized_encode_alloc_id<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>>(
} }
// Used to avoid infinite recursion when decoding cyclic allocations. // Used to avoid infinite recursion when decoding cyclic allocations.
type DecodingSessionId = NonZeroU32; type DecodingSessionId = NonZero<u32>;
#[derive(Clone)] #[derive(Clone)]
enum State { enum State {
@ -500,7 +500,7 @@ impl<'tcx> AllocMap<'tcx> {
AllocMap { AllocMap {
alloc_map: Default::default(), alloc_map: Default::default(),
dedup: Default::default(), dedup: Default::default(),
next_id: AllocId(NonZeroU64::new(1).unwrap()), next_id: AllocId(NonZero::<u64>::new(1).unwrap()),
} }
} }
fn reserve(&mut self) -> AllocId { fn reserve(&mut self) -> AllocId {

View File

@ -3,7 +3,7 @@ use super::{AllocId, InterpResult};
use rustc_macros::HashStable; use rustc_macros::HashStable;
use rustc_target::abi::{HasDataLayout, Size}; use rustc_target::abi::{HasDataLayout, Size};
use std::{fmt, num::NonZeroU64}; use std::{fmt, num::NonZero};
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// Pointer arithmetic // Pointer arithmetic
@ -129,7 +129,7 @@ pub trait Provenance: Copy + fmt::Debug + 'static {
/// The type of provenance in the compile-time interpreter. /// The type of provenance in the compile-time interpreter.
/// This is a packed representation of an `AllocId` and an `immutable: bool`. /// This is a packed representation of an `AllocId` and an `immutable: bool`.
#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)] #[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct CtfeProvenance(NonZeroU64); pub struct CtfeProvenance(NonZero<u64>);
impl From<AllocId> for CtfeProvenance { impl From<AllocId> for CtfeProvenance {
fn from(value: AllocId) -> Self { fn from(value: AllocId) -> Self {
@ -155,7 +155,7 @@ impl CtfeProvenance {
/// Returns the `AllocId` of this provenance. /// Returns the `AllocId` of this provenance.
#[inline(always)] #[inline(always)]
pub fn alloc_id(self) -> AllocId { pub fn alloc_id(self) -> AllocId {
AllocId(NonZeroU64::new(self.0.get() & !IMMUTABLE_MASK).unwrap()) AllocId(NonZero::<u64>::new(self.0.get() & !IMMUTABLE_MASK).unwrap())
} }
/// Returns whether this provenance is immutable. /// Returns whether this provenance is immutable.

View File

@ -4,7 +4,7 @@ use rustc_errors::{DiagnosticArgValue, IntoDiagnosticArg};
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use rustc_target::abi::Size; use rustc_target::abi::Size;
use std::fmt; use std::fmt;
use std::num::NonZeroU8; use std::num::NonZero;
use crate::ty::TyCtxt; use crate::ty::TyCtxt;
@ -132,7 +132,7 @@ pub struct ScalarInt {
/// The first `size` bytes of `data` are the value. /// The first `size` bytes of `data` are the value.
/// Do not try to read less or more bytes than that. The remaining bytes must be 0. /// Do not try to read less or more bytes than that. The remaining bytes must be 0.
data: u128, data: u128,
size: NonZeroU8, size: NonZero<u8>,
} }
// Cannot derive these, as the derives take references to the fields, and we // Cannot derive these, as the derives take references to the fields, and we
@ -161,14 +161,14 @@ impl<D: Decoder> Decodable<D> for ScalarInt {
let mut data = [0u8; 16]; let mut data = [0u8; 16];
let size = d.read_u8(); let size = d.read_u8();
data[..size as usize].copy_from_slice(d.read_raw_bytes(size as usize)); data[..size as usize].copy_from_slice(d.read_raw_bytes(size as usize));
ScalarInt { data: u128::from_le_bytes(data), size: NonZeroU8::new(size).unwrap() } ScalarInt { data: u128::from_le_bytes(data), size: NonZero::<u8>::new(size).unwrap() }
} }
} }
impl ScalarInt { impl ScalarInt {
pub const TRUE: ScalarInt = ScalarInt { data: 1_u128, size: NonZeroU8::new(1).unwrap() }; pub const TRUE: ScalarInt = ScalarInt { data: 1_u128, size: NonZero::<u8>::new(1).unwrap() };
pub const FALSE: ScalarInt = ScalarInt { data: 0_u128, size: NonZeroU8::new(1).unwrap() }; pub const FALSE: ScalarInt = ScalarInt { data: 0_u128, size: NonZero::<u8>::new(1).unwrap() };
#[inline] #[inline]
pub fn size(self) -> Size { pub fn size(self) -> Size {
@ -196,7 +196,7 @@ impl ScalarInt {
#[inline] #[inline]
pub fn null(size: Size) -> Self { pub fn null(size: Size) -> Self {
Self { data: 0, size: NonZeroU8::new(size.bytes() as u8).unwrap() } Self { data: 0, size: NonZero::<u8>::new(size.bytes() as u8).unwrap() }
} }
#[inline] #[inline]
@ -208,7 +208,7 @@ impl ScalarInt {
pub fn try_from_uint(i: impl Into<u128>, size: Size) -> Option<Self> { pub fn try_from_uint(i: impl Into<u128>, size: Size) -> Option<Self> {
let data = i.into(); let data = i.into();
if size.truncate(data) == data { if size.truncate(data) == data {
Some(Self { data, size: NonZeroU8::new(size.bytes() as u8).unwrap() }) Some(Self { data, size: NonZero::<u8>::new(size.bytes() as u8).unwrap() })
} else { } else {
None None
} }
@ -220,7 +220,7 @@ impl ScalarInt {
// `into` performed sign extension, we have to truncate // `into` performed sign extension, we have to truncate
let truncated = size.truncate(i as u128); let truncated = size.truncate(i as u128);
if size.sign_extend(truncated) as i128 == i { if size.sign_extend(truncated) as i128 == i {
Some(Self { data: truncated, size: NonZeroU8::new(size.bytes() as u8).unwrap() }) Some(Self { data: truncated, size: NonZero::<u8>::new(size.bytes() as u8).unwrap() })
} else { } else {
None None
} }
@ -388,7 +388,7 @@ macro_rules! from {
fn from(u: $ty) -> Self { fn from(u: $ty) -> Self {
Self { Self {
data: u128::from(u), data: u128::from(u),
size: NonZeroU8::new(std::mem::size_of::<$ty>() as u8).unwrap(), size: NonZero::<u8>::new(std::mem::size_of::<$ty>() as u8).unwrap(),
} }
} }
} }
@ -427,7 +427,10 @@ impl TryFrom<ScalarInt> for bool {
impl From<char> for ScalarInt { impl From<char> for ScalarInt {
#[inline] #[inline]
fn from(c: char) -> Self { fn from(c: char) -> Self {
Self { data: c as u128, size: NonZeroU8::new(std::mem::size_of::<char>() as u8).unwrap() } Self {
data: c as u128,
size: NonZero::<u8>::new(std::mem::size_of::<char>() as u8).unwrap(),
}
} }
} }
@ -454,7 +457,7 @@ impl From<Single> for ScalarInt {
#[inline] #[inline]
fn from(f: Single) -> Self { fn from(f: Single) -> Self {
// We trust apfloat to give us properly truncated data. // We trust apfloat to give us properly truncated data.
Self { data: f.to_bits(), size: NonZeroU8::new((Single::BITS / 8) as u8).unwrap() } Self { data: f.to_bits(), size: NonZero::<u8>::new((Single::BITS / 8) as u8).unwrap() }
} }
} }
@ -470,7 +473,7 @@ impl From<Double> for ScalarInt {
#[inline] #[inline]
fn from(f: Double) -> Self { fn from(f: Double) -> Self {
// We trust apfloat to give us properly truncated data. // We trust apfloat to give us properly truncated data.
Self { data: f.to_bits(), size: NonZeroU8::new((Double::BITS / 8) as u8).unwrap() } Self { data: f.to_bits(), size: NonZero::<u8>::new((Double::BITS / 8) as u8).unwrap() }
} }
} }

View File

@ -18,7 +18,7 @@ use core::intrinsics;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::mem; use std::mem;
use std::num::NonZeroUsize; use std::num::NonZero;
use std::ops::{ControlFlow, Deref}; use std::ops::{ControlFlow, Deref};
use std::ptr::NonNull; use std::ptr::NonNull;
@ -144,7 +144,7 @@ impl<'tcx> GenericArg<'tcx> {
#[inline] #[inline]
pub fn unpack(self) -> GenericArgKind<'tcx> { pub fn unpack(self) -> GenericArgKind<'tcx> {
let ptr = unsafe { let ptr = unsafe {
self.ptr.map_addr(|addr| NonZeroUsize::new_unchecked(addr.get() & !TAG_MASK)) self.ptr.map_addr(|addr| NonZero::<usize>::new_unchecked(addr.get() & !TAG_MASK))
}; };
// SAFETY: use of `Interned::new_unchecked` here is ok because these // SAFETY: use of `Interned::new_unchecked` here is ok because these
// pointers were originally created from `Interned` types in `pack()`, // pointers were originally created from `Interned` types in `pack()`,

View File

@ -20,7 +20,7 @@ use rustc_target::spec::{abi::Abi as SpecAbi, HasTargetSpec, PanicStrategy, Targ
use std::cmp; use std::cmp;
use std::fmt; use std::fmt;
use std::num::NonZeroUsize; use std::num::NonZero;
use std::ops::Bound; use std::ops::Bound;
pub trait IntegerExt { pub trait IntegerExt {
@ -761,7 +761,7 @@ where
}; };
tcx.mk_layout(LayoutS { tcx.mk_layout(LayoutS {
variants: Variants::Single { index: variant_index }, variants: Variants::Single { index: variant_index },
fields: match NonZeroUsize::new(fields) { fields: match NonZero::<usize>::new(fields) {
Some(fields) => FieldsShape::Union(fields), Some(fields) => FieldsShape::Union(fields),
None => FieldsShape::Arbitrary { offsets: IndexVec::new(), memory_index: IndexVec::new() }, None => FieldsShape::Arbitrary { offsets: IndexVec::new(), memory_index: IndexVec::new() },
}, },

View File

@ -61,7 +61,7 @@ use std::fmt::Debug;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::marker::PhantomData; use std::marker::PhantomData;
use std::mem; use std::mem;
use std::num::NonZeroUsize; use std::num::NonZero;
use std::ops::ControlFlow; use std::ops::ControlFlow;
use std::ptr::NonNull; use std::ptr::NonNull;
use std::{fmt, str}; use std::{fmt, str};
@ -618,7 +618,7 @@ impl<'tcx> Term<'tcx> {
#[inline] #[inline]
pub fn unpack(self) -> TermKind<'tcx> { pub fn unpack(self) -> TermKind<'tcx> {
let ptr = unsafe { let ptr = unsafe {
self.ptr.map_addr(|addr| NonZeroUsize::new_unchecked(addr.get() & !TAG_MASK)) self.ptr.map_addr(|addr| NonZero::<usize>::new_unchecked(addr.get() & !TAG_MASK))
}; };
// SAFETY: use of `Interned::new_unchecked` here is ok because these // SAFETY: use of `Interned::new_unchecked` here is ok because these
// pointers were originally created from `Interned` types in `pack()`, // pointers were originally created from `Interned` types in `pack()`,

View File

@ -8,6 +8,7 @@
#![doc(rust_logo)] #![doc(rust_logo)]
#![feature(rustdoc_internals)] #![feature(rustdoc_internals)]
#![allow(internal_features)] #![allow(internal_features)]
#![feature(generic_nonzero)]
#![feature(let_chains)] #![feature(let_chains)]
#![feature(map_try_insert)] #![feature(map_try_insert)]
#![feature(try_blocks)] #![feature(try_blocks)]

View File

@ -27,7 +27,7 @@ use rustc_span::Span;
use rustc_target::spec::abi::Abi; use rustc_target::spec::abi::Abi;
use std::mem::replace; use std::mem::replace;
use std::num::NonZeroU32; use std::num::NonZero;
#[derive(PartialEq)] #[derive(PartialEq)]
enum AnnotationKind { enum AnnotationKind {
@ -645,7 +645,7 @@ fn stability_index(tcx: TyCtxt<'_>, (): ()) -> Index {
let stability = Stability { let stability = Stability {
level: attr::StabilityLevel::Unstable { level: attr::StabilityLevel::Unstable {
reason: UnstableReason::Default, reason: UnstableReason::Default,
issue: NonZeroU32::new(27812), issue: NonZero::<u32>::new(27812),
is_soft: false, is_soft: false,
implied_by: None, implied_by: None,
}, },

View File

@ -3,6 +3,7 @@
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)] #![doc(rust_logo)]
#![feature(rustdoc_internals)] #![feature(rustdoc_internals)]
#![feature(generic_nonzero)]
#![feature(min_specialization)] #![feature(min_specialization)]
#![feature(rustc_attrs)] #![feature(rustc_attrs)]
#![allow(rustc::potential_query_instability, unused_parens)] #![allow(rustc::potential_query_instability, unused_parens)]

View File

@ -30,7 +30,7 @@ use rustc_serialize::Decodable;
use rustc_serialize::Encodable; use rustc_serialize::Encodable;
use rustc_session::Limit; use rustc_session::Limit;
use rustc_span::def_id::LOCAL_CRATE; use rustc_span::def_id::LOCAL_CRATE;
use std::num::NonZeroU64; use std::num::NonZero;
use thin_vec::ThinVec; use thin_vec::ThinVec;
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
@ -68,7 +68,7 @@ impl QueryContext for QueryCtxt<'_> {
#[inline] #[inline]
fn next_job_id(self) -> QueryJobId { fn next_job_id(self) -> QueryJobId {
QueryJobId( QueryJobId(
NonZeroU64::new( NonZero::<u64>::new(
self.query_system.jobs.fetch_add(1, std::sync::atomic::Ordering::Relaxed), self.query_system.jobs.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
) )
.unwrap(), .unwrap(),

View File

@ -1,5 +1,6 @@
#![feature(assert_matches)] #![feature(assert_matches)]
#![feature(core_intrinsics)] #![feature(core_intrinsics)]
#![feature(generic_nonzero)]
#![feature(hash_raw_entry)] #![feature(hash_raw_entry)]
#![feature(min_specialization)] #![feature(min_specialization)]
#![feature(let_chains)] #![feature(let_chains)]

View File

@ -11,7 +11,7 @@ use rustc_span::Span;
use std::hash::Hash; use std::hash::Hash;
use std::io::Write; use std::io::Write;
use std::num::NonZeroU64; use std::num::NonZero;
#[cfg(parallel_compiler)] #[cfg(parallel_compiler)]
use { use {
@ -36,7 +36,7 @@ pub type QueryMap = FxHashMap<QueryJobId, QueryJobInfo>;
/// A value uniquely identifying an active query job. /// A value uniquely identifying an active query job.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct QueryJobId(pub NonZeroU64); pub struct QueryJobId(pub NonZero<u64>);
impl QueryJobId { impl QueryJobId {
fn query(self, map: &QueryMap) -> QueryStackFrame { fn query(self, map: &QueryMap) -> QueryStackFrame {

View File

@ -11,6 +11,7 @@
#![feature(associated_type_bounds)] #![feature(associated_type_bounds)]
#![feature(const_option)] #![feature(const_option)]
#![feature(core_intrinsics)] #![feature(core_intrinsics)]
#![feature(generic_nonzero)]
#![feature(inline_const)] #![feature(inline_const)]
#![feature(min_specialization)] #![feature(min_specialization)]
#![feature(never_type)] #![feature(never_type)]

View File

@ -6,6 +6,7 @@ use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::hash::{BuildHasher, Hash}; use std::hash::{BuildHasher, Hash};
use std::marker::PhantomData; use std::marker::PhantomData;
use std::num::NonZero;
use std::path; use std::path;
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
@ -216,15 +217,15 @@ impl<D: Decoder> Decodable<D> for ! {
} }
} }
impl<S: Encoder> Encodable<S> for ::std::num::NonZeroU32 { impl<S: Encoder> Encodable<S> for NonZero<u32> {
fn encode(&self, s: &mut S) { fn encode(&self, s: &mut S) {
s.emit_u32(self.get()); s.emit_u32(self.get());
} }
} }
impl<D: Decoder> Decodable<D> for ::std::num::NonZeroU32 { impl<D: Decoder> Decodable<D> for NonZero<u32> {
fn decode(d: &mut D) -> Self { fn decode(d: &mut D) -> Self {
::std::num::NonZeroU32::new(d.read_u32()).unwrap() NonZero::<u32>::new(d.read_u32()).unwrap()
} }
} }

View File

@ -3226,7 +3226,7 @@ pub(crate) mod dep_tracking {
}; };
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::hash::{DefaultHasher, Hash}; use std::hash::{DefaultHasher, Hash};
use std::num::NonZeroUsize; use std::num::NonZero;
use std::path::PathBuf; use std::path::PathBuf;
pub trait DepTrackingHash { pub trait DepTrackingHash {
@ -3268,7 +3268,7 @@ pub(crate) mod dep_tracking {
impl_dep_tracking_hash_via_hash!( impl_dep_tracking_hash_via_hash!(
bool, bool,
usize, usize,
NonZeroUsize, NonZero<usize>,
u64, u64,
Hash64, Hash64,
String, String,

View File

@ -1,4 +1,4 @@
use std::num::NonZeroU32; use std::num::NonZero;
use rustc_ast::token; use rustc_ast::token;
use rustc_ast::util::literal::LitError; use rustc_ast::util::literal::LitError;
@ -26,7 +26,7 @@ impl<'a> IntoDiagnostic<'a> for FeatureGateError {
#[derive(Subdiagnostic)] #[derive(Subdiagnostic)]
#[note(session_feature_diagnostic_for_issue)] #[note(session_feature_diagnostic_for_issue)]
pub struct FeatureDiagnosticForIssue { pub struct FeatureDiagnosticForIssue {
pub n: NonZeroU32, pub n: NonZero<u32>,
} }
#[derive(Subdiagnostic)] #[derive(Subdiagnostic)]

View File

@ -1,3 +1,4 @@
#![feature(generic_nonzero)]
#![feature(let_chains)] #![feature(let_chains)]
#![feature(lazy_cell)] #![feature(lazy_cell)]
#![feature(option_get_or_insert_default)] #![feature(option_get_or_insert_default)]

View File

@ -21,7 +21,7 @@ use rustc_span::SourceFileHashAlgorithm;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::hash::{DefaultHasher, Hasher}; use std::hash::{DefaultHasher, Hasher};
use std::num::{IntErrorKind, NonZeroUsize}; use std::num::{IntErrorKind, NonZero};
use std::path::PathBuf; use std::path::PathBuf;
use std::str; use std::str;
@ -617,7 +617,7 @@ mod parse {
pub(crate) fn parse_threads(slot: &mut usize, v: Option<&str>) -> bool { pub(crate) fn parse_threads(slot: &mut usize, v: Option<&str>) -> bool {
match v.and_then(|s| s.parse().ok()) { match v.and_then(|s| s.parse().ok()) {
Some(0) => { Some(0) => {
*slot = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get); *slot = std::thread::available_parallelism().map_or(1, NonZero::<usize>::get);
true true
} }
Some(i) => { Some(i) => {
@ -991,7 +991,10 @@ mod parse {
true true
} }
pub(crate) fn parse_treat_err_as_bug(slot: &mut Option<NonZeroUsize>, v: Option<&str>) -> bool { pub(crate) fn parse_treat_err_as_bug(
slot: &mut Option<NonZero<usize>>,
v: Option<&str>,
) -> bool {
match v { match v {
Some(s) => match s.parse() { Some(s) => match s.parse() {
Ok(val) => { Ok(val) => {
@ -1004,7 +1007,7 @@ mod parse {
} }
}, },
None => { None => {
*slot = NonZeroUsize::new(1); *slot = NonZero::<usize>::new(1);
true true
} }
} }
@ -1950,7 +1953,7 @@ written to standard error output)"),
"translate remapped paths into local paths when possible (default: yes)"), "translate remapped paths into local paths when possible (default: yes)"),
trap_unreachable: Option<bool> = (None, parse_opt_bool, [TRACKED], trap_unreachable: Option<bool> = (None, parse_opt_bool, [TRACKED],
"generate trap instructions for unreachable intrinsics (default: use target setting, usually yes)"), "generate trap instructions for unreachable intrinsics (default: use target setting, usually yes)"),
treat_err_as_bug: Option<NonZeroUsize> = (None, parse_treat_err_as_bug, [TRACKED], treat_err_as_bug: Option<NonZero<usize>> = (None, parse_treat_err_as_bug, [TRACKED],
"treat the `val`th error that occurs as bug (default if not specified: 0 - don't treat errors as bugs. \ "treat the `val`th error that occurs as bug (default if not specified: 0 - don't treat errors as bugs. \
default if specified without a value: 1 - treat the first error as bug)"), default if specified without a value: 1 - treat the first error as bug)"),
trim_diagnostic_paths: bool = (true, parse_bool, [UNTRACKED], trim_diagnostic_paths: bool = (true, parse_bool, [UNTRACKED],

View File

@ -147,7 +147,7 @@ use core::alloc::Allocator;
use core::fmt; use core::fmt;
use core::iter::{FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen}; use core::iter::{FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen};
use core::mem::{self, swap, ManuallyDrop}; use core::mem::{self, swap, ManuallyDrop};
use core::num::NonZeroUsize; use core::num::NonZero;
use core::ops::{Deref, DerefMut}; use core::ops::{Deref, DerefMut};
use core::ptr; use core::ptr;
@ -296,7 +296,7 @@ pub struct PeekMut<
heap: &'a mut BinaryHeap<T, A>, heap: &'a mut BinaryHeap<T, A>,
// If a set_len + sift_down are required, this is Some. If a &mut T has not // If a set_len + sift_down are required, this is Some. If a &mut T has not
// yet been exposed to peek_mut()'s caller, it's None. // yet been exposed to peek_mut()'s caller, it's None.
original_len: Option<NonZeroUsize>, original_len: Option<NonZero<usize>>,
} }
#[stable(feature = "collection_debug", since = "1.17.0")] #[stable(feature = "collection_debug", since = "1.17.0")]
@ -350,7 +350,7 @@ impl<T: Ord, A: Allocator> DerefMut for PeekMut<'_, T, A> {
// the standard library as "leak amplification". // the standard library as "leak amplification".
unsafe { unsafe {
// SAFETY: len > 1 so len != 0. // SAFETY: len > 1 so len != 0.
self.original_len = Some(NonZeroUsize::new_unchecked(len)); self.original_len = Some(NonZero::<usize>::new_unchecked(len));
// SAFETY: len > 1 so all this does for now is leak elements, // SAFETY: len > 1 so all this does for now is leak elements,
// which is safe. // which is safe.
self.heap.data.set_len(1); self.heap.data.set_len(1);
@ -1576,8 +1576,8 @@ unsafe impl<T, A: Allocator> SourceIter for IntoIter<T, A> {
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
#[doc(hidden)] #[doc(hidden)]
unsafe impl<I, A: Allocator> InPlaceIterable for IntoIter<I, A> { unsafe impl<I, A: Allocator> InPlaceIterable for IntoIter<I, A> {
const EXPAND_BY: Option<NonZeroUsize> = NonZeroUsize::new(1); const EXPAND_BY: Option<NonZero<usize>> = NonZero::<usize>::new(1);
const MERGE_BY: Option<NonZeroUsize> = NonZeroUsize::new(1); const MERGE_BY: Option<NonZero<usize>> = NonZero::<usize>::new(1);
} }
unsafe impl<I> AsVecIntoIter for IntoIter<I> { unsafe impl<I> AsVecIntoIter for IntoIter<I> {

View File

@ -1,5 +1,5 @@
use core::iter::{FusedIterator, TrustedLen}; use core::iter::{FusedIterator, TrustedLen};
use core::num::NonZeroUsize; use core::num::NonZero;
use core::{array, fmt, mem::MaybeUninit, ops::Try, ptr}; use core::{array, fmt, mem::MaybeUninit, ops::Try, ptr};
use crate::alloc::{Allocator, Global}; use crate::alloc::{Allocator, Global};
@ -54,7 +54,7 @@ impl<T, A: Allocator> Iterator for IntoIter<T, A> {
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let len = self.inner.len; let len = self.inner.len;
let rem = if len < n { let rem = if len < n {
self.inner.clear(); self.inner.clear();
@ -63,7 +63,7 @@ impl<T, A: Allocator> Iterator for IntoIter<T, A> {
self.inner.drain(..n); self.inner.drain(..n);
0 0
}; };
NonZeroUsize::new(rem).map_or(Ok(()), Err) NonZero::<usize>::new(rem).map_or(Ok(()), Err)
} }
#[inline] #[inline]
@ -183,7 +183,7 @@ impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let len = self.inner.len; let len = self.inner.len;
let rem = if len < n { let rem = if len < n {
self.inner.clear(); self.inner.clear();
@ -192,7 +192,7 @@ impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
self.inner.truncate(len - n); self.inner.truncate(len - n);
0 0
}; };
NonZeroUsize::new(rem).map_or(Ok(()), Err) NonZero::<usize>::new(rem).map_or(Ok(()), Err)
} }
fn try_rfold<B, F, R>(&mut self, mut init: B, mut f: F) -> R fn try_rfold<B, F, R>(&mut self, mut init: B, mut f: F) -> R

View File

@ -1,5 +1,5 @@
use core::iter::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use core::iter::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce};
use core::num::NonZeroUsize; use core::num::NonZero;
use core::ops::Try; use core::ops::Try;
use core::{fmt, mem, slice}; use core::{fmt, mem, slice};
@ -56,7 +56,7 @@ impl<'a, T> Iterator for Iter<'a, T> {
} }
} }
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let remaining = self.i1.advance_by(n); let remaining = self.i1.advance_by(n);
match remaining { match remaining {
Ok(()) => return Ok(()), Ok(()) => return Ok(()),
@ -128,7 +128,7 @@ impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
} }
} }
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
match self.i2.advance_back_by(n) { match self.i2.advance_back_by(n) {
Ok(()) => return Ok(()), Ok(()) => return Ok(()),
Err(n) => { Err(n) => {

View File

@ -1,5 +1,5 @@
use core::iter::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use core::iter::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce};
use core::num::NonZeroUsize; use core::num::NonZero;
use core::ops::Try; use core::ops::Try;
use core::{fmt, mem, slice}; use core::{fmt, mem, slice};
@ -48,7 +48,7 @@ impl<'a, T> Iterator for IterMut<'a, T> {
} }
} }
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
match self.i1.advance_by(n) { match self.i1.advance_by(n) {
Ok(()) => return Ok(()), Ok(()) => return Ok(()),
Err(remaining) => { Err(remaining) => {
@ -119,7 +119,7 @@ impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
} }
} }
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
match self.i2.advance_back_by(n) { match self.i2.advance_back_by(n) {
Ok(()) => return Ok(()), Ok(()) => return Ok(()),
Err(remaining) => { Err(remaining) => {

View File

@ -128,6 +128,7 @@
#![feature(extend_one)] #![feature(extend_one)]
#![feature(fmt_internals)] #![feature(fmt_internals)]
#![feature(fn_traits)] #![feature(fn_traits)]
#![feature(generic_nonzero)]
#![feature(hasher_prefixfree_extras)] #![feature(hasher_prefixfree_extras)]
#![feature(hint_assert_unchecked)] #![feature(hint_assert_unchecked)]
#![feature(inline_const)] #![feature(inline_const)]

View File

@ -160,14 +160,14 @@ use core::alloc::Layout;
use core::iter::{InPlaceIterable, SourceIter, TrustedRandomAccessNoCoerce}; use core::iter::{InPlaceIterable, SourceIter, TrustedRandomAccessNoCoerce};
use core::marker::PhantomData; use core::marker::PhantomData;
use core::mem::{self, ManuallyDrop, SizedTypeProperties}; use core::mem::{self, ManuallyDrop, SizedTypeProperties};
use core::num::NonZeroUsize; use core::num::NonZero;
use core::ptr::{self, NonNull}; use core::ptr::{self, NonNull};
use super::{InPlaceDrop, InPlaceDstDataSrcBufDrop, SpecFromIter, SpecFromIterNested, Vec}; use super::{InPlaceDrop, InPlaceDstDataSrcBufDrop, SpecFromIter, SpecFromIterNested, Vec};
const fn in_place_collectible<DEST, SRC>( const fn in_place_collectible<DEST, SRC>(
step_merge: Option<NonZeroUsize>, step_merge: Option<NonZero<usize>>,
step_expand: Option<NonZeroUsize>, step_expand: Option<NonZero<usize>>,
) -> bool { ) -> bool {
// Require matching alignments because an alignment-changing realloc is inefficient on many // Require matching alignments because an alignment-changing realloc is inefficient on many
// system allocators and better implementations would require the unstable Allocator trait. // system allocators and better implementations would require the unstable Allocator trait.

View File

@ -12,7 +12,7 @@ use core::iter::{
}; };
use core::marker::PhantomData; use core::marker::PhantomData;
use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties}; use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties};
use core::num::NonZeroUsize; use core::num::NonZero;
#[cfg(not(no_global_oom_handling))] #[cfg(not(no_global_oom_handling))]
use core::ops::Deref; use core::ops::Deref;
use core::ptr::{self, NonNull}; use core::ptr::{self, NonNull};
@ -234,7 +234,7 @@ impl<T, A: Allocator> Iterator for IntoIter<T, A> {
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let step_size = self.len().min(n); let step_size = self.len().min(n);
let to_drop = ptr::slice_from_raw_parts_mut(self.ptr.as_ptr(), step_size); let to_drop = ptr::slice_from_raw_parts_mut(self.ptr.as_ptr(), step_size);
if T::IS_ZST { if T::IS_ZST {
@ -248,7 +248,7 @@ impl<T, A: Allocator> Iterator for IntoIter<T, A> {
unsafe { unsafe {
ptr::drop_in_place(to_drop); ptr::drop_in_place(to_drop);
} }
NonZeroUsize::new(n - step_size).map_or(Ok(()), Err) NonZero::<usize>::new(n - step_size).map_or(Ok(()), Err)
} }
#[inline] #[inline]
@ -336,7 +336,7 @@ impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let step_size = self.len().min(n); let step_size = self.len().min(n);
if T::IS_ZST { if T::IS_ZST {
// SAFETY: same as for advance_by() // SAFETY: same as for advance_by()
@ -350,7 +350,7 @@ impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
unsafe { unsafe {
ptr::drop_in_place(to_drop); ptr::drop_in_place(to_drop);
} }
NonZeroUsize::new(n - step_size).map_or(Ok(()), Err) NonZero::<usize>::new(n - step_size).map_or(Ok(()), Err)
} }
} }
@ -457,8 +457,8 @@ unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter<T, A> {
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
#[doc(hidden)] #[doc(hidden)]
unsafe impl<T, A: Allocator> InPlaceIterable for IntoIter<T, A> { unsafe impl<T, A: Allocator> InPlaceIterable for IntoIter<T, A> {
const EXPAND_BY: Option<NonZeroUsize> = NonZeroUsize::new(1); const EXPAND_BY: Option<NonZero<usize>> = NonZero::<usize>::new(1);
const MERGE_BY: Option<NonZeroUsize> = NonZeroUsize::new(1); const MERGE_BY: Option<NonZero<usize>> = NonZero::<usize>::new(1);
} }
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]

View File

@ -13,6 +13,7 @@
#![feature(core_intrinsics)] #![feature(core_intrinsics)]
#![feature(extract_if)] #![feature(extract_if)]
#![feature(exact_size_is_empty)] #![feature(exact_size_is_empty)]
#![feature(generic_nonzero)]
#![feature(linked_list_cursors)] #![feature(linked_list_cursors)]
#![feature(map_try_insert)] #![feature(map_try_insert)]
#![feature(new_uninit)] #![feature(new_uninit)]

View File

@ -1,5 +1,5 @@
use core::alloc::{Allocator, Layout}; use core::alloc::{Allocator, Layout};
use core::num::NonZeroUsize; use core::num::NonZero;
use core::ptr::NonNull; use core::ptr::NonNull;
use core::{assert_eq, assert_ne}; use core::{assert_eq, assert_ne};
use std::alloc::System; use std::alloc::System;
@ -1089,9 +1089,9 @@ fn test_into_iter_advance_by() {
assert_eq!(i.advance_back_by(1), Ok(())); assert_eq!(i.advance_back_by(1), Ok(()));
assert_eq!(i.as_slice(), [2, 3, 4]); assert_eq!(i.as_slice(), [2, 3, 4]);
assert_eq!(i.advance_back_by(usize::MAX), Err(NonZeroUsize::new(usize::MAX - 3).unwrap())); assert_eq!(i.advance_back_by(usize::MAX), Err(NonZero::<usize>::new(usize::MAX - 3).unwrap()));
assert_eq!(i.advance_by(usize::MAX), Err(NonZeroUsize::new(usize::MAX).unwrap())); assert_eq!(i.advance_by(usize::MAX), Err(NonZero::<usize>::new(usize::MAX).unwrap()));
assert_eq!(i.advance_by(0), Ok(())); assert_eq!(i.advance_by(0), Ok(()));
assert_eq!(i.advance_back_by(0), Ok(())); assert_eq!(i.advance_back_by(0), Ok(()));
@ -1192,7 +1192,7 @@ fn test_from_iter_specialization_with_iterator_adapters() {
.map(|(a, b)| a + b) .map(|(a, b)| a + b)
.map_while(Option::Some) .map_while(Option::Some)
.skip(1) .skip(1)
.map(|e| if e != usize::MAX { Ok(std::num::NonZeroUsize::new(e)) } else { Err(()) }); .map(|e| if e != usize::MAX { Ok(NonZero::<usize>::new(e)) } else { Err(()) });
assert_in_place_trait(&iter); assert_in_place_trait(&iter);
let sink = iter.collect::<Result<Vec<_>, _>>().unwrap(); let sink = iter.collect::<Result<Vec<_>, _>>().unwrap();
let sinkptr = sink.as_ptr(); let sinkptr = sink.as_ptr();

View File

@ -1,4 +1,4 @@
use core::num::NonZeroUsize; use core::num::NonZero;
use std::assert_matches::assert_matches; use std::assert_matches::assert_matches;
use std::collections::TryReserveErrorKind::*; use std::collections::TryReserveErrorKind::*;
use std::collections::{vec_deque::Drain, VecDeque}; use std::collections::{vec_deque::Drain, VecDeque};
@ -445,9 +445,9 @@ fn test_into_iter() {
assert_eq!(it.next_back(), Some(3)); assert_eq!(it.next_back(), Some(3));
let mut it = VecDeque::from(vec![1, 2, 3, 4, 5]).into_iter(); let mut it = VecDeque::from(vec![1, 2, 3, 4, 5]).into_iter();
assert_eq!(it.advance_by(10), Err(NonZeroUsize::new(5).unwrap())); assert_eq!(it.advance_by(10), Err(NonZero::<usize>::new(5).unwrap()));
let mut it = VecDeque::from(vec![1, 2, 3, 4, 5]).into_iter(); let mut it = VecDeque::from(vec![1, 2, 3, 4, 5]).into_iter();
assert_eq!(it.advance_back_by(10), Err(NonZeroUsize::new(5).unwrap())); assert_eq!(it.advance_back_by(10), Err(NonZero::<usize>::new(5).unwrap()));
} }
} }

View File

@ -1,6 +1,6 @@
//! Defines the `IntoIter` owned iterator for arrays. //! Defines the `IntoIter` owned iterator for arrays.
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::{ use crate::{
fmt, fmt,
intrinsics::transmute_unchecked, intrinsics::transmute_unchecked,
@ -280,7 +280,7 @@ impl<T, const N: usize> Iterator for IntoIter<T, N> {
self.next_back() self.next_back()
} }
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
// This also moves the start, which marks them as conceptually "dropped", // This also moves the start, which marks them as conceptually "dropped",
// so if anything goes bad then our drop impl won't double-free them. // so if anything goes bad then our drop impl won't double-free them.
let range_to_drop = self.alive.take_prefix(n); let range_to_drop = self.alive.take_prefix(n);
@ -292,7 +292,7 @@ impl<T, const N: usize> Iterator for IntoIter<T, N> {
ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(slice)); ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(slice));
} }
NonZeroUsize::new(remaining).map_or(Ok(()), Err) NonZero::<usize>::new(remaining).map_or(Ok(()), Err)
} }
#[inline] #[inline]
@ -335,7 +335,7 @@ impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, N> {
}) })
} }
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
// This also moves the end, which marks them as conceptually "dropped", // This also moves the end, which marks them as conceptually "dropped",
// so if anything goes bad then our drop impl won't double-free them. // so if anything goes bad then our drop impl won't double-free them.
let range_to_drop = self.alive.take_suffix(n); let range_to_drop = self.alive.take_suffix(n);
@ -347,7 +347,7 @@ impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, N> {
ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(slice)); ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(slice));
} }
NonZeroUsize::new(remaining).map_or(Ok(()), Err) NonZero::<usize>::new(remaining).map_or(Ok(()), Err)
} }
} }

View File

@ -12,7 +12,7 @@
use crate::escape; use crate::escape;
use crate::fmt; use crate::fmt;
use crate::iter::FusedIterator; use crate::iter::FusedIterator;
use crate::num::NonZeroUsize; use crate::num::NonZero;
mod ascii_char; mod ascii_char;
#[unstable(feature = "ascii_char", issue = "110998")] #[unstable(feature = "ascii_char", issue = "110998")]
@ -133,7 +133,7 @@ impl Iterator for EscapeDefault {
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.0.advance_by(n) self.0.advance_by(n)
} }
} }
@ -146,7 +146,7 @@ impl DoubleEndedIterator for EscapeDefault {
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.0.advance_back_by(n) self.0.advance_back_by(n)
} }
} }

View File

@ -43,7 +43,7 @@ use crate::error::Error;
use crate::escape; use crate::escape;
use crate::fmt::{self, Write}; use crate::fmt::{self, Write};
use crate::iter::FusedIterator; use crate::iter::FusedIterator;
use crate::num::NonZeroUsize; use crate::num::NonZero;
pub(crate) use self::methods::EscapeDebugExtArgs; pub(crate) use self::methods::EscapeDebugExtArgs;
@ -185,7 +185,7 @@ impl Iterator for EscapeUnicode {
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.0.advance_by(n) self.0.advance_by(n)
} }
} }
@ -260,7 +260,7 @@ impl Iterator for EscapeDefault {
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.0.advance_by(n) self.0.advance_by(n)
} }
} }

View File

@ -33,7 +33,7 @@ is_bytewise_comparable!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128,
// so we can compare them directly. // so we can compare them directly.
is_bytewise_comparable!(bool, char, super::Ordering); is_bytewise_comparable!(bool, char, super::Ordering);
// SAFETY: Similarly, the non-zero types have a niche, but no undef and no pointers, // SAFETY: Similarly, the `NonZero` type has a niche, but no undef and no pointers,
// and they compare like their underlying numeric type. // and they compare like their underlying numeric type.
is_bytewise_comparable!( is_bytewise_comparable!(
NonZeroU8, NonZeroU8,
@ -50,7 +50,7 @@ is_bytewise_comparable!(
NonZeroIsize, NonZeroIsize,
); );
// SAFETY: The NonZero types have the "null" optimization guaranteed, and thus // SAFETY: The `NonZero` type has the "null" optimization guaranteed, and thus
// are also safe to equality-compare bitwise inside an `Option`. // are also safe to equality-compare bitwise inside an `Option`.
// The way `PartialOrd` is defined for `Option` means that this wouldn't work // The way `PartialOrd` is defined for `Option` means that this wouldn't work
// for `<` or `>` on the signed types, but since we only do `==` it's fine. // for `<` or `>` on the signed types, but since we only do `==` it's fine.

View File

@ -1,7 +1,7 @@
//! Helper code for character escaping. //! Helper code for character escaping.
use crate::ascii; use crate::ascii;
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::Range; use crate::ops::Range;
const HEX_DIGITS: [ascii::Char; 16] = *b"0123456789abcdef".as_ascii().unwrap(); const HEX_DIGITS: [ascii::Char; 16] = *b"0123456789abcdef".as_ascii().unwrap();
@ -106,11 +106,11 @@ impl<const N: usize> EscapeIterInner<N> {
self.alive.next_back().map(|i| self.data[usize::from(i)].to_u8()) self.alive.next_back().map(|i| self.data[usize::from(i)].to_u8())
} }
pub fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { pub fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.alive.advance_by(n) self.alive.advance_by(n)
} }
pub fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { pub fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.alive.advance_back_by(n) self.alive.advance_back_by(n)
} }
} }

View File

@ -3,7 +3,7 @@ use crate::iter::adapters::SourceIter;
use crate::iter::{ use crate::iter::{
ByRefSized, FusedIterator, InPlaceIterable, TrustedFused, TrustedRandomAccessNoCoerce, ByRefSized, FusedIterator, InPlaceIterable, TrustedFused, TrustedRandomAccessNoCoerce,
}; };
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{ControlFlow, NeverShortCircuit, Try}; use crate::ops::{ControlFlow, NeverShortCircuit, Try};
/// An iterator over `N` elements of the iterator at a time. /// An iterator over `N` elements of the iterator at a time.
@ -253,9 +253,9 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable + Iterator, const N: usize> InPlaceIterable for ArrayChunks<I, N> { unsafe impl<I: InPlaceIterable + Iterator, const N: usize> InPlaceIterable for ArrayChunks<I, N> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = const { const MERGE_BY: Option<NonZero<usize>> = const {
match (I::MERGE_BY, NonZeroUsize::new(N)) { match (I::MERGE_BY, NonZero::<usize>::new(N)) {
(Some(m), Some(n)) => m.checked_mul(n), (Some(m), Some(n)) => m.checked_mul(n),
_ => None, _ => None,
} }

View File

@ -1,4 +1,4 @@
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{NeverShortCircuit, Try}; use crate::ops::{NeverShortCircuit, Try};
/// Like `Iterator::by_ref`, but requiring `Sized` so it can forward generics. /// Like `Iterator::by_ref`, but requiring `Sized` so it can forward generics.
@ -27,7 +27,7 @@ impl<I: Iterator> Iterator for ByRefSized<'_, I> {
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
I::advance_by(self.0, n) I::advance_by(self.0, n)
} }
@ -63,7 +63,7 @@ impl<I: DoubleEndedIterator> DoubleEndedIterator for ByRefSized<'_, I> {
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
I::advance_back_by(self.0, n) I::advance_back_by(self.0, n)
} }

View File

@ -1,5 +1,5 @@
use crate::iter::{FusedIterator, TrustedLen}; use crate::iter::{FusedIterator, TrustedLen};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::Try; use crate::ops::Try;
/// An iterator that links two iterators together, in a chain. /// An iterator that links two iterators together, in a chain.
@ -96,7 +96,7 @@ where
} }
#[inline] #[inline]
fn advance_by(&mut self, mut n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, mut n: usize) -> Result<(), NonZero<usize>> {
if let Some(ref mut a) = self.a { if let Some(ref mut a) = self.a {
n = match a.advance_by(n) { n = match a.advance_by(n) {
Ok(()) => return Ok(()), Ok(()) => return Ok(()),
@ -110,7 +110,7 @@ where
// we don't fuse the second iterator // we don't fuse the second iterator
} }
NonZeroUsize::new(n).map_or(Ok(()), Err) NonZero::<usize>::new(n).map_or(Ok(()), Err)
} }
#[inline] #[inline]
@ -182,7 +182,7 @@ where
} }
#[inline] #[inline]
fn advance_back_by(&mut self, mut n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, mut n: usize) -> Result<(), NonZero<usize>> {
if let Some(ref mut b) = self.b { if let Some(ref mut b) = self.b {
n = match b.advance_back_by(n) { n = match b.advance_back_by(n) {
Ok(()) => return Ok(()), Ok(()) => return Ok(()),
@ -196,7 +196,7 @@ where
// we don't fuse the second iterator // we don't fuse the second iterator
} }
NonZeroUsize::new(n).map_or(Ok(()), Err) NonZero::<usize>::new(n).map_or(Ok(()), Err)
} }
#[inline] #[inline]

View File

@ -3,7 +3,7 @@ use crate::iter::adapters::{
}; };
use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen, UncheckedIterator}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen, UncheckedIterator};
use crate::ops::Try; use crate::ops::Try;
use core::num::NonZeroUsize; use core::num::NonZero;
/// An iterator that clones the elements of an underlying iterator. /// An iterator that clones the elements of an underlying iterator.
/// ///
@ -185,6 +185,6 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable> InPlaceIterable for Cloned<I> { unsafe impl<I: InPlaceIterable> InPlaceIterable for Cloned<I> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }

View File

@ -4,7 +4,7 @@ use crate::iter::adapters::{
use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen};
use crate::mem::MaybeUninit; use crate::mem::MaybeUninit;
use crate::mem::SizedTypeProperties; use crate::mem::SizedTypeProperties;
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::Try; use crate::ops::Try;
use crate::{array, ptr}; use crate::{array, ptr};
@ -90,7 +90,7 @@ where
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.it.advance_by(n) self.it.advance_by(n)
} }
@ -131,7 +131,7 @@ where
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.it.advance_back_by(n) self.it.advance_back_by(n)
} }
} }
@ -272,6 +272,6 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable> InPlaceIterable for Copied<I> { unsafe impl<I: InPlaceIterable> InPlaceIterable for Copied<I> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }

View File

@ -1,4 +1,4 @@
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::{iter::FusedIterator, ops::Try}; use crate::{iter::FusedIterator, ops::Try};
/// An iterator that repeats endlessly. /// An iterator that repeats endlessly.
@ -82,7 +82,7 @@ where
#[inline] #[inline]
#[rustc_inherit_overflow_checks] #[rustc_inherit_overflow_checks]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let mut n = match self.iter.advance_by(n) { let mut n = match self.iter.advance_by(n) {
Ok(()) => return Ok(()), Ok(()) => return Ok(()),
Err(rem) => rem.get(), Err(rem) => rem.get(),
@ -97,7 +97,7 @@ where
}; };
} }
NonZeroUsize::new(n).map_or(Ok(()), Err) NonZero::<usize>::new(n).map_or(Ok(()), Err)
} }
// No `fold` override, because `fold` doesn't make much sense for `Cycle`, // No `fold` override, because `fold` doesn't make much sense for `Cycle`,

View File

@ -2,7 +2,7 @@ use crate::iter::adapters::{
zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce, zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce,
}; };
use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused, TrustedLen}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused, TrustedLen};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::Try; use crate::ops::Try;
/// An iterator that yields the current count and the element during iteration. /// An iterator that yields the current count and the element during iteration.
@ -115,7 +115,7 @@ where
#[inline] #[inline]
#[rustc_inherit_overflow_checks] #[rustc_inherit_overflow_checks]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let remaining = self.iter.advance_by(n); let remaining = self.iter.advance_by(n);
let advanced = match remaining { let advanced = match remaining {
Ok(()) => n, Ok(()) => n,
@ -206,7 +206,7 @@ where
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
// we do not need to update the count since that only tallies the number of items // we do not need to update the count since that only tallies the number of items
// consumed from the front. consuming items from the back can never reduce that. // consumed from the front. consuming items from the back can never reduce that.
self.iter.advance_back_by(n) self.iter.advance_back_by(n)
@ -265,8 +265,8 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable> InPlaceIterable for Enumerate<I> { unsafe impl<I: InPlaceIterable> InPlaceIterable for Enumerate<I> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }
#[stable(feature = "default_iters", since = "1.70.0")] #[stable(feature = "default_iters", since = "1.70.0")]

View File

@ -1,6 +1,6 @@
use crate::fmt; use crate::fmt;
use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::Try; use crate::ops::Try;
use core::array; use core::array;
use core::mem::{ManuallyDrop, MaybeUninit}; use core::mem::{ManuallyDrop, MaybeUninit};
@ -209,6 +209,6 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable, P> InPlaceIterable for Filter<I, P> { unsafe impl<I: InPlaceIterable, P> InPlaceIterable for Filter<I, P> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }

View File

@ -1,6 +1,6 @@
use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused};
use crate::mem::{ManuallyDrop, MaybeUninit}; use crate::mem::{ManuallyDrop, MaybeUninit};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{ControlFlow, Try}; use crate::ops::{ControlFlow, Try};
use crate::{array, fmt}; use crate::{array, fmt};
@ -210,6 +210,6 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable, F> InPlaceIterable for FilterMap<I, F> { unsafe impl<I: InPlaceIterable, F> InPlaceIterable for FilterMap<I, F> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }

View File

@ -4,7 +4,7 @@ use crate::iter::{
TrustedLen, TrustedLen,
}; };
use crate::iter::{Once, OnceWith}; use crate::iter::{Once, OnceWith};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{ControlFlow, Try}; use crate::ops::{ControlFlow, Try};
use crate::result; use crate::result;
use crate::{array, fmt, option}; use crate::{array, fmt, option};
@ -90,7 +90,7 @@ where
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.inner.advance_by(n) self.inner.advance_by(n)
} }
@ -135,7 +135,7 @@ where
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.inner.advance_back_by(n) self.inner.advance_back_by(n)
} }
} }
@ -165,13 +165,13 @@ where
I: InPlaceIterable, I: InPlaceIterable,
U: BoundedSize + IntoIterator, U: BoundedSize + IntoIterator,
{ {
const EXPAND_BY: Option<NonZeroUsize> = const { const EXPAND_BY: Option<NonZero<usize>> = const {
match (I::EXPAND_BY, U::UPPER_BOUND) { match (I::EXPAND_BY, U::UPPER_BOUND) {
(Some(m), Some(n)) => m.checked_mul(n), (Some(m), Some(n)) => m.checked_mul(n),
_ => None, _ => None,
} }
}; };
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
@ -200,7 +200,7 @@ where
#[rustc_specialization_trait] #[rustc_specialization_trait]
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe trait BoundedSize { unsafe trait BoundedSize {
const UPPER_BOUND: Option<NonZeroUsize> = NonZeroUsize::new(1); const UPPER_BOUND: Option<NonZero<usize>> = NonZero::<usize>::new(1);
} }
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
@ -217,31 +217,31 @@ unsafe impl<T> BoundedSize for Once<T> {}
unsafe impl<T> BoundedSize for OnceWith<T> {} unsafe impl<T> BoundedSize for OnceWith<T> {}
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<T, const N: usize> BoundedSize for [T; N] { unsafe impl<T, const N: usize> BoundedSize for [T; N] {
const UPPER_BOUND: Option<NonZeroUsize> = NonZeroUsize::new(N); const UPPER_BOUND: Option<NonZero<usize>> = NonZero::<usize>::new(N);
} }
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<T, const N: usize> BoundedSize for array::IntoIter<T, N> { unsafe impl<T, const N: usize> BoundedSize for array::IntoIter<T, N> {
const UPPER_BOUND: Option<NonZeroUsize> = NonZeroUsize::new(N); const UPPER_BOUND: Option<NonZero<usize>> = NonZero::<usize>::new(N);
} }
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: BoundedSize, P> BoundedSize for Filter<I, P> { unsafe impl<I: BoundedSize, P> BoundedSize for Filter<I, P> {
const UPPER_BOUND: Option<NonZeroUsize> = I::UPPER_BOUND; const UPPER_BOUND: Option<NonZero<usize>> = I::UPPER_BOUND;
} }
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: BoundedSize, P> BoundedSize for FilterMap<I, P> { unsafe impl<I: BoundedSize, P> BoundedSize for FilterMap<I, P> {
const UPPER_BOUND: Option<NonZeroUsize> = I::UPPER_BOUND; const UPPER_BOUND: Option<NonZero<usize>> = I::UPPER_BOUND;
} }
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: BoundedSize, F> BoundedSize for Map<I, F> { unsafe impl<I: BoundedSize, F> BoundedSize for Map<I, F> {
const UPPER_BOUND: Option<NonZeroUsize> = I::UPPER_BOUND; const UPPER_BOUND: Option<NonZero<usize>> = I::UPPER_BOUND;
} }
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: BoundedSize> BoundedSize for Copied<I> { unsafe impl<I: BoundedSize> BoundedSize for Copied<I> {
const UPPER_BOUND: Option<NonZeroUsize> = I::UPPER_BOUND; const UPPER_BOUND: Option<NonZero<usize>> = I::UPPER_BOUND;
} }
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: BoundedSize> BoundedSize for Cloned<I> { unsafe impl<I: BoundedSize> BoundedSize for Cloned<I> {
const UPPER_BOUND: Option<NonZeroUsize> = I::UPPER_BOUND; const UPPER_BOUND: Option<NonZero<usize>> = I::UPPER_BOUND;
} }
/// An iterator that flattens one level of nesting in an iterator of things /// An iterator that flattens one level of nesting in an iterator of things
@ -322,7 +322,7 @@ where
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.inner.advance_by(n) self.inner.advance_by(n)
} }
@ -367,7 +367,7 @@ where
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.inner.advance_back_by(n) self.inner.advance_back_by(n)
} }
} }
@ -394,13 +394,13 @@ where
I: InPlaceIterable + Iterator, I: InPlaceIterable + Iterator,
<I as Iterator>::Item: IntoIterator + BoundedSize, <I as Iterator>::Item: IntoIterator + BoundedSize,
{ {
const EXPAND_BY: Option<NonZeroUsize> = const { const EXPAND_BY: Option<NonZero<usize>> = const {
match (I::EXPAND_BY, I::Item::UPPER_BOUND) { match (I::EXPAND_BY, I::Item::UPPER_BOUND) {
(Some(m), Some(n)) => m.checked_mul(n), (Some(m), Some(n)) => m.checked_mul(n),
_ => None, _ => None,
} }
}; };
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
@ -669,7 +669,7 @@ where
#[inline] #[inline]
#[rustc_inherit_overflow_checks] #[rustc_inherit_overflow_checks]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
#[inline] #[inline]
#[rustc_inherit_overflow_checks] #[rustc_inherit_overflow_checks]
fn advance<U: Iterator>(n: usize, iter: &mut U) -> ControlFlow<(), usize> { fn advance<U: Iterator>(n: usize, iter: &mut U) -> ControlFlow<(), usize> {
@ -680,7 +680,9 @@ where
} }
match self.iter_try_fold(n, advance) { match self.iter_try_fold(n, advance) {
ControlFlow::Continue(remaining) => NonZeroUsize::new(remaining).map_or(Ok(()), Err), ControlFlow::Continue(remaining) => {
NonZero::<usize>::new(remaining).map_or(Ok(()), Err)
}
_ => Ok(()), _ => Ok(()),
} }
} }
@ -759,7 +761,7 @@ where
#[inline] #[inline]
#[rustc_inherit_overflow_checks] #[rustc_inherit_overflow_checks]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
#[inline] #[inline]
#[rustc_inherit_overflow_checks] #[rustc_inherit_overflow_checks]
fn advance<U: DoubleEndedIterator>(n: usize, iter: &mut U) -> ControlFlow<(), usize> { fn advance<U: DoubleEndedIterator>(n: usize, iter: &mut U) -> ControlFlow<(), usize> {
@ -770,7 +772,9 @@ where
} }
match self.iter_try_rfold(n, advance) { match self.iter_try_rfold(n, advance) {
ControlFlow::Continue(remaining) => NonZeroUsize::new(remaining).map_or(Ok(()), Err), ControlFlow::Continue(remaining) => {
NonZero::<usize>::new(remaining).map_or(Ok(()), Err)
}
_ => Ok(()), _ => Ok(()),
} }
} }

View File

@ -1,6 +1,6 @@
use crate::fmt; use crate::fmt;
use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::Try; use crate::ops::Try;
/// An iterator that calls a function with a reference to each element before /// An iterator that calls a function with a reference to each element before
@ -168,6 +168,6 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable, F> InPlaceIterable for Inspect<I, F> { unsafe impl<I: InPlaceIterable, F> InPlaceIterable for Inspect<I, F> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }

View File

@ -3,7 +3,7 @@ use crate::iter::adapters::{
zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce, zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce,
}; };
use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, UncheckedIterator}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, UncheckedIterator};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::Try; use crate::ops::Try;
/// An iterator that maps the values of `iter` with `f`. /// An iterator that maps the values of `iter` with `f`.
@ -237,6 +237,6 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable, F> InPlaceIterable for Map<I, F> { unsafe impl<I: InPlaceIterable, F> InPlaceIterable for Map<I, F> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }

View File

@ -1,6 +1,6 @@
use crate::fmt; use crate::fmt;
use crate::iter::{adapters::SourceIter, InPlaceIterable}; use crate::iter::{adapters::SourceIter, InPlaceIterable};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{ControlFlow, Try}; use crate::ops::{ControlFlow, Try};
/// An iterator that only accepts elements while `predicate` returns `Some(_)`. /// An iterator that only accepts elements while `predicate` returns `Some(_)`.
@ -84,6 +84,6 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable, P> InPlaceIterable for MapWhile<I, P> { unsafe impl<I: InPlaceIterable, P> InPlaceIterable for MapWhile<I, P> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }

View File

@ -1,5 +1,5 @@
use crate::iter::InPlaceIterable; use crate::iter::InPlaceIterable;
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try}; use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};
mod array_chunks; mod array_chunks;
@ -234,6 +234,6 @@ unsafe impl<I, R> InPlaceIterable for GenericShunt<'_, I, R>
where where
I: InPlaceIterable, I: InPlaceIterable,
{ {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }

View File

@ -1,5 +1,5 @@
use crate::iter::{FusedIterator, TrustedLen}; use crate::iter::{FusedIterator, TrustedLen};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::Try; use crate::ops::Try;
/// A double-ended iterator with the direction inverted. /// A double-ended iterator with the direction inverted.
@ -39,7 +39,7 @@ where
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.iter.advance_back_by(n) self.iter.advance_back_by(n)
} }
@ -84,7 +84,7 @@ where
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.iter.advance_by(n) self.iter.advance_by(n)
} }

View File

@ -1,6 +1,6 @@
use crate::fmt; use crate::fmt;
use crate::iter::{adapters::SourceIter, InPlaceIterable}; use crate::iter::{adapters::SourceIter, InPlaceIterable};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{ControlFlow, Try}; use crate::ops::{ControlFlow, Try};
/// An iterator to maintain state while iterating another iterator. /// An iterator to maintain state while iterating another iterator.
@ -94,6 +94,6 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<St, F, I: InPlaceIterable> InPlaceIterable for Scan<I, St, F> { unsafe impl<St, F, I: InPlaceIterable> InPlaceIterable for Scan<I, St, F> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }

View File

@ -5,7 +5,7 @@ use crate::iter::{
adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedLen, TrustedRandomAccess, adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedLen, TrustedRandomAccess,
TrustedRandomAccessNoCoerce, TrustedRandomAccessNoCoerce,
}; };
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{ControlFlow, Try}; use crate::ops::{ControlFlow, Try};
/// An iterator that skips over `n` elements of `iter`. /// An iterator that skips over `n` elements of `iter`.
@ -134,7 +134,7 @@ where
#[inline] #[inline]
#[rustc_inherit_overflow_checks] #[rustc_inherit_overflow_checks]
fn advance_by(&mut self, mut n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, mut n: usize) -> Result<(), NonZero<usize>> {
let skip_inner = self.n; let skip_inner = self.n;
let skip_and_advance = skip_inner.saturating_add(n); let skip_and_advance = skip_inner.saturating_add(n);
@ -154,7 +154,7 @@ where
} }
} }
NonZeroUsize::new(n).map_or(Ok(()), Err) NonZero::<usize>::new(n).map_or(Ok(()), Err)
} }
#[doc(hidden)] #[doc(hidden)]
@ -234,11 +234,11 @@ where
impl_fold_via_try_fold! { rfold -> try_rfold } impl_fold_via_try_fold! { rfold -> try_rfold }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let min = crate::cmp::min(self.len(), n); let min = crate::cmp::min(self.len(), n);
let rem = self.iter.advance_back_by(min); let rem = self.iter.advance_back_by(min);
assert!(rem.is_ok(), "ExactSizeIterator contract violation"); assert!(rem.is_ok(), "ExactSizeIterator contract violation");
NonZeroUsize::new(n - min).map_or(Ok(()), Err) NonZero::<usize>::new(n - min).map_or(Ok(()), Err)
} }
} }
@ -264,8 +264,8 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable> InPlaceIterable for Skip<I> { unsafe impl<I: InPlaceIterable> InPlaceIterable for Skip<I> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }
#[doc(hidden)] #[doc(hidden)]

View File

@ -1,6 +1,6 @@
use crate::fmt; use crate::fmt;
use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::Try; use crate::ops::Try;
/// An iterator that rejects elements while `predicate` returns `true`. /// An iterator that rejects elements while `predicate` returns `true`.
@ -124,6 +124,6 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable, F> InPlaceIterable for SkipWhile<I, F> { unsafe impl<I: InPlaceIterable, F> InPlaceIterable for SkipWhile<I, F> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }

View File

@ -3,7 +3,7 @@ use crate::iter::{
adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused, TrustedLen,
TrustedRandomAccess, TrustedRandomAccess,
}; };
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{ControlFlow, Try}; use crate::ops::{ControlFlow, Try};
/// An iterator that only iterates over the first `n` iterations of `iter`. /// An iterator that only iterates over the first `n` iterations of `iter`.
@ -117,7 +117,7 @@ where
#[inline] #[inline]
#[rustc_inherit_overflow_checks] #[rustc_inherit_overflow_checks]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let min = self.n.min(n); let min = self.n.min(n);
let rem = match self.iter.advance_by(min) { let rem = match self.iter.advance_by(min) {
Ok(()) => 0, Ok(()) => 0,
@ -125,7 +125,7 @@ where
}; };
let advanced = min - rem; let advanced = min - rem;
self.n -= advanced; self.n -= advanced;
NonZeroUsize::new(n - advanced).map_or(Ok(()), Err) NonZero::<usize>::new(n - advanced).map_or(Ok(()), Err)
} }
} }
@ -145,8 +145,8 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable> InPlaceIterable for Take<I> { unsafe impl<I: InPlaceIterable> InPlaceIterable for Take<I> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }
#[stable(feature = "double_ended_take_iterator", since = "1.38.0")] #[stable(feature = "double_ended_take_iterator", since = "1.38.0")]
@ -219,7 +219,7 @@ where
#[inline] #[inline]
#[rustc_inherit_overflow_checks] #[rustc_inherit_overflow_checks]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
// The amount by which the inner iterator needs to be shortened for it to be // The amount by which the inner iterator needs to be shortened for it to be
// at most as long as the take() amount. // at most as long as the take() amount.
let trim_inner = self.iter.len().saturating_sub(self.n); let trim_inner = self.iter.len().saturating_sub(self.n);
@ -235,7 +235,7 @@ where
let advanced_by_inner = advance_by - remainder; let advanced_by_inner = advance_by - remainder;
let advanced_by = advanced_by_inner - trim_inner; let advanced_by = advanced_by_inner - trim_inner;
self.n -= advanced_by; self.n -= advanced_by;
NonZeroUsize::new(n - advanced_by).map_or(Ok(()), Err) NonZero::<usize>::new(n - advanced_by).map_or(Ok(()), Err)
} }
} }

View File

@ -1,6 +1,6 @@
use crate::fmt; use crate::fmt;
use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{ControlFlow, Try}; use crate::ops::{ControlFlow, Try};
/// An iterator that only accepts elements while `predicate` returns `true`. /// An iterator that only accepts elements while `predicate` returns `true`.
@ -125,6 +125,6 @@ where
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: InPlaceIterable, F> InPlaceIterable for TakeWhile<I, F> { unsafe impl<I: InPlaceIterable, F> InPlaceIterable for TakeWhile<I, F> {
const EXPAND_BY: Option<NonZeroUsize> = I::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = I::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
} }

View File

@ -2,7 +2,7 @@ use crate::cmp;
use crate::fmt::{self, Debug}; use crate::fmt::{self, Debug};
use crate::iter::{FusedIterator, TrustedFused}; use crate::iter::{FusedIterator, TrustedFused};
use crate::iter::{InPlaceIterable, SourceIter, TrustedLen, UncheckedIterator}; use crate::iter::{InPlaceIterable, SourceIter, TrustedLen, UncheckedIterator};
use crate::num::NonZeroUsize; use crate::num::NonZero;
/// An iterator that iterates two other iterators simultaneously. /// An iterator that iterates two other iterators simultaneously.
/// ///
@ -489,8 +489,8 @@ where
// Since SourceIter forwards the left hand side we do the same here // Since SourceIter forwards the left hand side we do the same here
#[unstable(issue = "none", feature = "inplace_iteration")] #[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<A: InPlaceIterable, B> InPlaceIterable for Zip<A, B> { unsafe impl<A: InPlaceIterable, B> InPlaceIterable for Zip<A, B> {
const EXPAND_BY: Option<NonZeroUsize> = A::EXPAND_BY; const EXPAND_BY: Option<NonZero<usize>> = A::EXPAND_BY;
const MERGE_BY: Option<NonZeroUsize> = A::MERGE_BY; const MERGE_BY: Option<NonZero<usize>> = A::MERGE_BY;
} }
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]

View File

@ -2,7 +2,7 @@ use crate::ascii::Char as AsciiChar;
use crate::convert::TryFrom; use crate::convert::TryFrom;
use crate::mem; use crate::mem;
use crate::net::{Ipv4Addr, Ipv6Addr}; use crate::net::{Ipv4Addr, Ipv6Addr};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{self, Try}; use crate::ops::{self, Try};
use super::{ use super::{
@ -629,12 +629,12 @@ trait RangeIteratorImpl {
// Iterator // Iterator
fn spec_next(&mut self) -> Option<Self::Item>; fn spec_next(&mut self) -> Option<Self::Item>;
fn spec_nth(&mut self, n: usize) -> Option<Self::Item>; fn spec_nth(&mut self, n: usize) -> Option<Self::Item>;
fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize>; fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>>;
// DoubleEndedIterator // DoubleEndedIterator
fn spec_next_back(&mut self) -> Option<Self::Item>; fn spec_next_back(&mut self) -> Option<Self::Item>;
fn spec_nth_back(&mut self, n: usize) -> Option<Self::Item>; fn spec_nth_back(&mut self, n: usize) -> Option<Self::Item>;
fn spec_advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize>; fn spec_advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>>;
} }
impl<A: Step> RangeIteratorImpl for ops::Range<A> { impl<A: Step> RangeIteratorImpl for ops::Range<A> {
@ -666,7 +666,7 @@ impl<A: Step> RangeIteratorImpl for ops::Range<A> {
} }
#[inline] #[inline]
default fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { default fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let available = if self.start <= self.end { let available = if self.start <= self.end {
Step::steps_between(&self.start, &self.end).unwrap_or(usize::MAX) Step::steps_between(&self.start, &self.end).unwrap_or(usize::MAX)
} else { } else {
@ -678,7 +678,7 @@ impl<A: Step> RangeIteratorImpl for ops::Range<A> {
self.start = self.start =
Step::forward_checked(self.start.clone(), taken).expect("`Step` invariants not upheld"); Step::forward_checked(self.start.clone(), taken).expect("`Step` invariants not upheld");
NonZeroUsize::new(n - taken).map_or(Ok(()), Err) NonZero::<usize>::new(n - taken).map_or(Ok(()), Err)
} }
#[inline] #[inline]
@ -707,7 +707,7 @@ impl<A: Step> RangeIteratorImpl for ops::Range<A> {
} }
#[inline] #[inline]
default fn spec_advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { default fn spec_advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let available = if self.start <= self.end { let available = if self.start <= self.end {
Step::steps_between(&self.start, &self.end).unwrap_or(usize::MAX) Step::steps_between(&self.start, &self.end).unwrap_or(usize::MAX)
} else { } else {
@ -719,7 +719,7 @@ impl<A: Step> RangeIteratorImpl for ops::Range<A> {
self.end = self.end =
Step::backward_checked(self.end.clone(), taken).expect("`Step` invariants not upheld"); Step::backward_checked(self.end.clone(), taken).expect("`Step` invariants not upheld");
NonZeroUsize::new(n - taken).map_or(Ok(()), Err) NonZero::<usize>::new(n - taken).map_or(Ok(()), Err)
} }
} }
@ -751,7 +751,7 @@ impl<T: TrustedStep> RangeIteratorImpl for ops::Range<T> {
} }
#[inline] #[inline]
fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let available = if self.start <= self.end { let available = if self.start <= self.end {
Step::steps_between(&self.start, &self.end).unwrap_or(usize::MAX) Step::steps_between(&self.start, &self.end).unwrap_or(usize::MAX)
} else { } else {
@ -766,7 +766,7 @@ impl<T: TrustedStep> RangeIteratorImpl for ops::Range<T> {
// Otherwise 0 is returned which always safe to use. // Otherwise 0 is returned which always safe to use.
self.start = unsafe { Step::forward_unchecked(self.start, taken) }; self.start = unsafe { Step::forward_unchecked(self.start, taken) };
NonZeroUsize::new(n - taken).map_or(Ok(()), Err) NonZero::<usize>::new(n - taken).map_or(Ok(()), Err)
} }
#[inline] #[inline]
@ -795,7 +795,7 @@ impl<T: TrustedStep> RangeIteratorImpl for ops::Range<T> {
} }
#[inline] #[inline]
fn spec_advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn spec_advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let available = if self.start <= self.end { let available = if self.start <= self.end {
Step::steps_between(&self.start, &self.end).unwrap_or(usize::MAX) Step::steps_between(&self.start, &self.end).unwrap_or(usize::MAX)
} else { } else {
@ -807,7 +807,7 @@ impl<T: TrustedStep> RangeIteratorImpl for ops::Range<T> {
// SAFETY: same as the spec_advance_by() implementation // SAFETY: same as the spec_advance_by() implementation
self.end = unsafe { Step::backward_unchecked(self.end, taken) }; self.end = unsafe { Step::backward_unchecked(self.end, taken) };
NonZeroUsize::new(n - taken).map_or(Ok(()), Err) NonZero::<usize>::new(n - taken).map_or(Ok(()), Err)
} }
} }
@ -871,7 +871,7 @@ impl<A: Step> Iterator for ops::Range<A> {
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.spec_advance_by(n) self.spec_advance_by(n)
} }
@ -949,7 +949,7 @@ impl<A: Step> DoubleEndedIterator for ops::Range<A> {
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.spec_advance_back_by(n) self.spec_advance_back_by(n)
} }
} }

View File

@ -1,5 +1,5 @@
use crate::iter::{FusedIterator, TrustedLen}; use crate::iter::{FusedIterator, TrustedLen};
use crate::num::NonZeroUsize; use crate::num::NonZero;
/// Creates a new iterator that endlessly repeats a single element. /// Creates a new iterator that endlessly repeats a single element.
/// ///
@ -81,7 +81,7 @@ impl<A: Clone> Iterator for Repeat<A> {
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
// Advancing an infinite iterator of a single element is a no-op. // Advancing an infinite iterator of a single element is a no-op.
let _ = n; let _ = n;
Ok(()) Ok(())
@ -110,7 +110,7 @@ impl<A: Clone> DoubleEndedIterator for Repeat<A> {
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
// Advancing an infinite iterator of a single element is a no-op. // Advancing an infinite iterator of a single element is a no-op.
let _ = n; let _ = n;
Ok(()) Ok(())

View File

@ -1,6 +1,6 @@
use crate::iter::{FusedIterator, TrustedLen}; use crate::iter::{FusedIterator, TrustedLen};
use crate::mem::ManuallyDrop; use crate::mem::ManuallyDrop;
use crate::num::NonZeroUsize; use crate::num::NonZero;
/// Creates a new iterator that repeats a single element a given number of times. /// Creates a new iterator that repeats a single element a given number of times.
/// ///
@ -136,7 +136,7 @@ impl<A: Clone> Iterator for RepeatN<A> {
} }
#[inline] #[inline]
fn advance_by(&mut self, skip: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, skip: usize) -> Result<(), NonZero<usize>> {
let len = self.count; let len = self.count;
if skip >= len { if skip >= len {
@ -145,7 +145,7 @@ impl<A: Clone> Iterator for RepeatN<A> {
if skip > len { if skip > len {
// SAFETY: we just checked that the difference is positive // SAFETY: we just checked that the difference is positive
Err(unsafe { NonZeroUsize::new_unchecked(skip - len) }) Err(unsafe { NonZero::<usize>::new_unchecked(skip - len) })
} else { } else {
self.count = len - skip; self.count = len - skip;
Ok(()) Ok(())
@ -178,7 +178,7 @@ impl<A: Clone> DoubleEndedIterator for RepeatN<A> {
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
self.advance_by(n) self.advance_by(n)
} }

View File

@ -1,4 +1,4 @@
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{ControlFlow, Try}; use crate::ops::{ControlFlow, Try};
/// An iterator able to yield elements from both ends. /// An iterator able to yield elements from both ends.
@ -119,8 +119,8 @@ pub trait DoubleEndedIterator: Iterator {
/// ///
/// ``` /// ```
/// #![feature(iter_advance_by)] /// #![feature(iter_advance_by)]
///
/// use std::num::NonZeroUsize; /// use std::num::NonZeroUsize;
///
/// let a = [3, 4, 5, 6]; /// let a = [3, 4, 5, 6];
/// let mut iter = a.iter(); /// let mut iter = a.iter();
/// ///
@ -134,11 +134,11 @@ pub trait DoubleEndedIterator: Iterator {
/// [`Err(k)`]: Err /// [`Err(k)`]: Err
#[inline] #[inline]
#[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")] #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
for i in 0..n { for i in 0..n {
if self.next_back().is_none() { if self.next_back().is_none() {
// SAFETY: `i` is always less than `n`. // SAFETY: `i` is always less than `n`.
return Err(unsafe { NonZeroUsize::new_unchecked(n - i) }); return Err(unsafe { NonZero::<usize>::new_unchecked(n - i) });
} }
} }
Ok(()) Ok(())
@ -373,7 +373,7 @@ impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
fn next_back(&mut self) -> Option<I::Item> { fn next_back(&mut self) -> Option<I::Item> {
(**self).next_back() (**self).next_back()
} }
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
(**self).advance_back_by(n) (**self).advance_back_by(n)
} }
fn nth_back(&mut self, n: usize) -> Option<I::Item> { fn nth_back(&mut self, n: usize) -> Option<I::Item> {

View File

@ -1,6 +1,6 @@
use crate::array; use crate::array;
use crate::cmp::{self, Ordering}; use crate::cmp::{self, Ordering};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try}; use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};
use super::super::try_process; use super::super::try_process;
@ -320,8 +320,8 @@ pub trait Iterator {
/// ///
/// ``` /// ```
/// #![feature(iter_advance_by)] /// #![feature(iter_advance_by)]
///
/// use std::num::NonZeroUsize; /// use std::num::NonZeroUsize;
///
/// let a = [1, 2, 3, 4]; /// let a = [1, 2, 3, 4];
/// let mut iter = a.iter(); /// let mut iter = a.iter();
/// ///
@ -333,11 +333,11 @@ pub trait Iterator {
#[inline] #[inline]
#[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")] #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
#[rustc_do_not_const_check] #[rustc_do_not_const_check]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
for i in 0..n { for i in 0..n {
if self.next().is_none() { if self.next().is_none() {
// SAFETY: `i` is always less than `n`. // SAFETY: `i` is always less than `n`.
return Err(unsafe { NonZeroUsize::new_unchecked(n - i) }); return Err(unsafe { NonZero::<usize>::new_unchecked(n - i) });
} }
} }
Ok(()) Ok(())
@ -4138,7 +4138,7 @@ impl<I: Iterator + ?Sized> Iterator for &mut I {
fn size_hint(&self) -> (usize, Option<usize>) { fn size_hint(&self) -> (usize, Option<usize>) {
(**self).size_hint() (**self).size_hint()
} }
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
(**self).advance_by(n) (**self).advance_by(n)
} }
fn nth(&mut self, n: usize) -> Option<Self::Item> { fn nth(&mut self, n: usize) -> Option<Self::Item> {

View File

@ -1,5 +1,5 @@
use crate::iter::Step; use crate::iter::Step;
use crate::num::NonZeroUsize; use crate::num::NonZero;
/// Same as FusedIterator /// Same as FusedIterator
/// ///
@ -91,12 +91,12 @@ pub unsafe trait InPlaceIterable {
/// E.g. [[u8; 4]; 4].iter().flatten().flatten() would have a `EXPAND_BY` of 16. /// E.g. [[u8; 4]; 4].iter().flatten().flatten() would have a `EXPAND_BY` of 16.
/// This is an upper bound, i.e. the transformations will produce at most this many items per /// This is an upper bound, i.e. the transformations will produce at most this many items per
/// input. It's meant for layout calculations. /// input. It's meant for layout calculations.
const EXPAND_BY: Option<NonZeroUsize>; const EXPAND_BY: Option<NonZero<usize>>;
/// The product of many-to-one item reductions that happen throughout the iterator pipeline. /// The product of many-to-one item reductions that happen throughout the iterator pipeline.
/// E.g. [u8].iter().array_chunks::<4>().array_chunks::<4>() would have a `MERGE_BY` of 16. /// E.g. [u8].iter().array_chunks::<4>().array_chunks::<4>() would have a `MERGE_BY` of 16.
/// This is a lower bound, i.e. the transformations will consume at least this many items per /// This is a lower bound, i.e. the transformations will consume at least this many items per
/// output. /// output.
const MERGE_BY: Option<NonZeroUsize>; const MERGE_BY: Option<NonZero<usize>>;
} }
/// A type that upholds all invariants of [`Step`]. /// A type that upholds all invariants of [`Step`].

View File

@ -312,10 +312,10 @@ macro_rules! nonzero_integer {
/// #![feature(non_zero_count_ones)] /// #![feature(non_zero_count_ones)]
/// # fn main() { test().unwrap(); } /// # fn main() { test().unwrap(); }
/// # fn test() -> Option<()> { /// # fn test() -> Option<()> {
#[doc = concat!("# use std::num::{self, ", stringify!($Ty), "};")] /// # use std::num::*;
/// /// #
/// let one = num::NonZeroU32::new(1)?; /// let one = NonZeroU32::new(1)?;
/// let three = num::NonZeroU32::new(3)?; /// let three = NonZeroU32::new(3)?;
#[doc = concat!("let a = ", stringify!($Ty), "::new(0b100_0000)?;")] #[doc = concat!("let a = ", stringify!($Ty), "::new(0b100_0000)?;")]
#[doc = concat!("let b = ", stringify!($Ty), "::new(0b100_0011)?;")] #[doc = concat!("let b = ", stringify!($Ty), "::new(0b100_0011)?;")]
/// ///
@ -336,7 +336,7 @@ macro_rules! nonzero_integer {
// SAFETY: // SAFETY:
// `self` is non-zero, which means it has at least one bit set, which means // `self` is non-zero, which means it has at least one bit set, which means
// that the result of `count_ones` is non-zero. // that the result of `count_ones` is non-zero.
unsafe { NonZeroU32::new_unchecked(self.get().count_ones()) } unsafe { NonZero::<u32>::new_unchecked(self.get().count_ones()) }
} }
nonzero_integer_signedness_dependent_methods! { nonzero_integer_signedness_dependent_methods! {

View File

@ -1,6 +1,6 @@
use crate::intrinsics::{unchecked_add, unchecked_sub}; use crate::intrinsics::{unchecked_add, unchecked_sub};
use crate::iter::{FusedIterator, TrustedLen}; use crate::iter::{FusedIterator, TrustedLen};
use crate::num::NonZeroUsize; use crate::num::NonZero;
/// Like a `Range<usize>`, but with a safety invariant that `start <= end`. /// Like a `Range<usize>`, but with a safety invariant that `start <= end`.
/// ///
@ -130,9 +130,9 @@ impl Iterator for IndexRange {
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let taken = self.take_prefix(n); let taken = self.take_prefix(n);
NonZeroUsize::new(n - taken.len()).map_or(Ok(()), Err) NonZero::<usize>::new(n - taken.len()).map_or(Ok(()), Err)
} }
} }
@ -148,9 +148,9 @@ impl DoubleEndedIterator for IndexRange {
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let taken = self.take_suffix(n); let taken = self.take_suffix(n);
NonZeroUsize::new(n - taken.len()).map_or(Ok(()), Err) NonZero::<usize>::new(n - taken.len()).map_or(Ok(()), Err)
} }
} }

View File

@ -1,5 +1,5 @@
use crate::convert::{TryFrom, TryInto}; use crate::convert::{TryFrom, TryInto};
use crate::num::NonZeroUsize; use crate::num::{NonZero, NonZeroUsize};
use crate::{cmp, fmt, hash, mem, num}; use crate::{cmp, fmt, hash, mem, num};
/// A type storing a `usize` which is a power of two, and thus /// A type storing a `usize` which is a power of two, and thus
@ -100,7 +100,7 @@ impl Alignment {
#[inline] #[inline]
pub const fn as_nonzero(self) -> NonZeroUsize { pub const fn as_nonzero(self) -> NonZeroUsize {
// SAFETY: All the discriminants are non-zero. // SAFETY: All the discriminants are non-zero.
unsafe { NonZeroUsize::new_unchecked(self.as_usize()) } unsafe { NonZero::<usize>::new_unchecked(self.as_usize()) }
} }
/// Returns the base-2 logarithm of the alignment. /// Returns the base-2 logarithm of the alignment.

View File

@ -6,7 +6,7 @@ use crate::intrinsics::assert_unsafe_precondition;
use crate::marker::Unsize; use crate::marker::Unsize;
use crate::mem::SizedTypeProperties; use crate::mem::SizedTypeProperties;
use crate::mem::{self, MaybeUninit}; use crate::mem::{self, MaybeUninit};
use crate::num::NonZeroUsize; use crate::num::{NonZero, NonZeroUsize};
use crate::ops::{CoerceUnsized, DispatchFromDyn}; use crate::ops::{CoerceUnsized, DispatchFromDyn};
use crate::ptr; use crate::ptr;
use crate::ptr::Unique; use crate::ptr::Unique;
@ -295,7 +295,7 @@ impl<T: ?Sized> NonNull<T> {
pub fn addr(self) -> NonZeroUsize { pub fn addr(self) -> NonZeroUsize {
// SAFETY: The pointer is guaranteed by the type to be non-null, // SAFETY: The pointer is guaranteed by the type to be non-null,
// meaning that the address will be non-zero. // meaning that the address will be non-zero.
unsafe { NonZeroUsize::new_unchecked(self.pointer.addr()) } unsafe { NonZero::<usize>::new_unchecked(self.pointer.addr()) }
} }
/// Creates a new pointer with the given address. /// Creates a new pointer with the given address.

View File

@ -11,7 +11,7 @@ use crate::iter::{
}; };
use crate::marker::PhantomData; use crate::marker::PhantomData;
use crate::mem::{self, SizedTypeProperties}; use crate::mem::{self, SizedTypeProperties};
use crate::num::{NonZero, NonZeroUsize}; use crate::num::NonZero;
use crate::ptr::{self, invalid, invalid_mut, NonNull}; use crate::ptr::{self, invalid, invalid_mut, NonNull};
use super::{from_raw_parts, from_raw_parts_mut}; use super::{from_raw_parts, from_raw_parts_mut};

View File

@ -196,11 +196,11 @@ macro_rules! iterator {
} }
#[inline] #[inline]
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let advance = cmp::min(len!(self), n); let advance = cmp::min(len!(self), n);
// SAFETY: By construction, `advance` does not exceed `self.len()`. // SAFETY: By construction, `advance` does not exceed `self.len()`.
unsafe { self.post_inc_start(advance) }; unsafe { self.post_inc_start(advance) };
NonZeroUsize::new(n - advance).map_or(Ok(()), Err) NonZero::<usize>::new(n - advance).map_or(Ok(()), Err)
} }
#[inline] #[inline]
@ -421,11 +421,11 @@ macro_rules! iterator {
} }
#[inline] #[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
let advance = cmp::min(len!(self), n); let advance = cmp::min(len!(self), n);
// SAFETY: By construction, `advance` does not exceed `self.len()`. // SAFETY: By construction, `advance` does not exceed `self.len()`.
unsafe { self.pre_dec_end(advance) }; unsafe { self.pre_dec_end(advance) };
NonZeroUsize::new(n - advance).map_or(Ok(()), Err) NonZero::<usize>::new(n - advance).map_or(Ok(()), Err)
} }
} }

View File

@ -11,7 +11,7 @@ use crate::fmt;
use crate::hint; use crate::hint;
use crate::intrinsics::exact_div; use crate::intrinsics::exact_div;
use crate::mem::{self, SizedTypeProperties}; use crate::mem::{self, SizedTypeProperties};
use crate::num::NonZeroUsize; use crate::num::NonZero;
use crate::ops::{Bound, OneSidedRange, Range, RangeBounds}; use crate::ops::{Bound, OneSidedRange, Range, RangeBounds};
use crate::panic::debug_assert_nounwind; use crate::panic::debug_assert_nounwind;
use crate::ptr; use crate::ptr;
@ -1086,7 +1086,7 @@ impl<T> [T] {
#[inline] #[inline]
#[track_caller] #[track_caller]
pub fn windows(&self, size: usize) -> Windows<'_, T> { pub fn windows(&self, size: usize) -> Windows<'_, T> {
let size = NonZeroUsize::new(size).expect("window size must be non-zero"); let size = NonZero::<usize>::new(size).expect("window size must be non-zero");
Windows::new(self, size) Windows::new(self, size)
} }

View File

@ -8,7 +8,7 @@ use crate::iter::{TrustedRandomAccess, TrustedRandomAccessNoCoerce};
use crate::ops::Try; use crate::ops::Try;
use crate::option; use crate::option;
use crate::slice::{self, Split as SliceSplit}; use crate::slice::{self, Split as SliceSplit};
use core::num::NonZeroUsize; use core::num::{NonZero, NonZeroUsize};
use super::from_utf8_unchecked; use super::from_utf8_unchecked;
use super::pattern::Pattern; use super::pattern::Pattern;
@ -96,7 +96,7 @@ impl<'a> Iterator for Chars<'a> {
unsafe { self.iter.advance_by(slurp).unwrap_unchecked() }; unsafe { self.iter.advance_by(slurp).unwrap_unchecked() };
} }
NonZeroUsize::new(remainder).map_or(Ok(()), Err) NonZero::<usize>::new(remainder).map_or(Ok(()), Err)
} }
#[inline] #[inline]

View File

@ -1,4 +1,4 @@
use core::num::NonZeroUsize; use core::num::NonZero;
use core::sync::atomic::{AtomicUsize, Ordering}; use core::sync::atomic::{AtomicUsize, Ordering};
use core::{array, assert_eq}; use core::{array, assert_eq};
@ -548,7 +548,7 @@ fn array_intoiter_advance_by() {
assert_eq!(counter.get(), 13); assert_eq!(counter.get(), 13);
let r = it.advance_by(123456); let r = it.advance_by(123456);
assert_eq!(r, Err(NonZeroUsize::new(123456 - 87).unwrap())); assert_eq!(r, Err(NonZero::<usize>::new(123456 - 87).unwrap()));
assert_eq!(it.len(), 0); assert_eq!(it.len(), 0);
assert_eq!(counter.get(), 100); assert_eq!(counter.get(), 100);
@ -558,7 +558,7 @@ fn array_intoiter_advance_by() {
assert_eq!(counter.get(), 100); assert_eq!(counter.get(), 100);
let r = it.advance_by(10); let r = it.advance_by(10);
assert_eq!(r, Err(NonZeroUsize::new(10).unwrap())); assert_eq!(r, Err(NonZero::<usize>::new(10).unwrap()));
assert_eq!(it.len(), 0); assert_eq!(it.len(), 0);
assert_eq!(counter.get(), 100); assert_eq!(counter.get(), 100);
} }
@ -601,7 +601,7 @@ fn array_intoiter_advance_back_by() {
assert_eq!(counter.get(), 13); assert_eq!(counter.get(), 13);
let r = it.advance_back_by(123456); let r = it.advance_back_by(123456);
assert_eq!(r, Err(NonZeroUsize::new(123456 - 87).unwrap())); assert_eq!(r, Err(NonZero::<usize>::new(123456 - 87).unwrap()));
assert_eq!(it.len(), 0); assert_eq!(it.len(), 0);
assert_eq!(counter.get(), 100); assert_eq!(counter.get(), 100);
@ -611,7 +611,7 @@ fn array_intoiter_advance_back_by() {
assert_eq!(counter.get(), 100); assert_eq!(counter.get(), 100);
let r = it.advance_back_by(10); let r = it.advance_back_by(10);
assert_eq!(r, Err(NonZeroUsize::new(10).unwrap())); assert_eq!(r, Err(NonZero::<usize>::new(10).unwrap()));
assert_eq!(it.len(), 0); assert_eq!(it.len(), 0);
assert_eq!(counter.get(), 100); assert_eq!(counter.get(), 100);
} }

View File

@ -1,6 +1,6 @@
use super::*; use super::*;
use core::iter::*; use core::iter::*;
use core::num::NonZeroUsize; use core::num::NonZero;
#[test] #[test]
fn test_iterator_chain() { fn test_iterator_chain() {
@ -34,7 +34,10 @@ fn test_iterator_chain_advance_by() {
let mut iter = Unfuse::new(xs).chain(Unfuse::new(ys)); let mut iter = Unfuse::new(xs).chain(Unfuse::new(ys));
assert_eq!(iter.advance_by(i), Ok(())); assert_eq!(iter.advance_by(i), Ok(()));
assert_eq!(iter.next(), Some(&xs[i])); assert_eq!(iter.next(), Some(&xs[i]));
assert_eq!(iter.advance_by(100), Err(NonZeroUsize::new(100 - (len - i - 1)).unwrap())); assert_eq!(
iter.advance_by(100),
Err(NonZero::<usize>::new(100 - (len - i - 1)).unwrap())
);
assert_eq!(iter.advance_by(0), Ok(())); assert_eq!(iter.advance_by(0), Ok(()));
} }
@ -44,7 +47,7 @@ fn test_iterator_chain_advance_by() {
assert_eq!(iter.next(), Some(&ys[i])); assert_eq!(iter.next(), Some(&ys[i]));
assert_eq!( assert_eq!(
iter.advance_by(100), iter.advance_by(100),
Err(NonZeroUsize::new(100 - (ys.len() - i - 1)).unwrap()) Err(NonZero::<usize>::new(100 - (ys.len() - i - 1)).unwrap())
); );
assert_eq!(iter.advance_by(0), Ok(())); assert_eq!(iter.advance_by(0), Ok(()));
} }
@ -55,7 +58,7 @@ fn test_iterator_chain_advance_by() {
assert_eq!(iter.advance_by(0), Ok(())); assert_eq!(iter.advance_by(0), Ok(()));
let mut iter = xs.iter().chain(ys); let mut iter = xs.iter().chain(ys);
assert_eq!(iter.advance_by(len + 1), Err(NonZeroUsize::new(1).unwrap())); assert_eq!(iter.advance_by(len + 1), Err(NonZero::<usize>::new(1).unwrap()));
assert_eq!(iter.advance_by(0), Ok(())); assert_eq!(iter.advance_by(0), Ok(()));
} }
@ -76,7 +79,7 @@ fn test_iterator_chain_advance_back_by() {
assert_eq!(iter.next_back(), Some(&ys[ys.len() - i - 1])); assert_eq!(iter.next_back(), Some(&ys[ys.len() - i - 1]));
assert_eq!( assert_eq!(
iter.advance_back_by(100), iter.advance_back_by(100),
Err(NonZeroUsize::new(100 - (len - i - 1)).unwrap()) Err(NonZero::<usize>::new(100 - (len - i - 1)).unwrap())
); );
assert_eq!(iter.advance_back_by(0), Ok(())); assert_eq!(iter.advance_back_by(0), Ok(()));
} }
@ -87,7 +90,7 @@ fn test_iterator_chain_advance_back_by() {
assert_eq!(iter.next_back(), Some(&xs[xs.len() - i - 1])); assert_eq!(iter.next_back(), Some(&xs[xs.len() - i - 1]));
assert_eq!( assert_eq!(
iter.advance_back_by(100), iter.advance_back_by(100),
Err(NonZeroUsize::new(100 - (xs.len() - i - 1)).unwrap()) Err(NonZero::<usize>::new(100 - (xs.len() - i - 1)).unwrap())
); );
assert_eq!(iter.advance_back_by(0), Ok(())); assert_eq!(iter.advance_back_by(0), Ok(()));
} }
@ -98,7 +101,7 @@ fn test_iterator_chain_advance_back_by() {
assert_eq!(iter.advance_back_by(0), Ok(())); assert_eq!(iter.advance_back_by(0), Ok(()));
let mut iter = xs.iter().chain(ys); let mut iter = xs.iter().chain(ys);
assert_eq!(iter.advance_back_by(len + 1), Err(NonZeroUsize::new(1).unwrap())); assert_eq!(iter.advance_back_by(len + 1), Err(NonZero::<usize>::new(1).unwrap()));
assert_eq!(iter.advance_back_by(0), Ok(())); assert_eq!(iter.advance_back_by(0), Ok(()));
} }

View File

@ -1,5 +1,5 @@
use core::iter::*; use core::iter::*;
use core::num::NonZeroUsize; use core::num::NonZero;
#[test] #[test]
fn test_iterator_enumerate() { fn test_iterator_enumerate() {
@ -66,7 +66,7 @@ fn test_iterator_enumerate_advance_by() {
assert_eq!(it.next(), Some((2, &2))); assert_eq!(it.next(), Some((2, &2)));
assert_eq!(it.advance_by(2), Ok(())); assert_eq!(it.advance_by(2), Ok(()));
assert_eq!(it.next(), Some((5, &5))); assert_eq!(it.next(), Some((5, &5)));
assert_eq!(it.advance_by(1), Err(NonZeroUsize::new(1).unwrap())); assert_eq!(it.advance_by(1), Err(NonZero::<usize>::new(1).unwrap()));
assert_eq!(it.next(), None); assert_eq!(it.next(), None);
} }

View File

@ -1,7 +1,7 @@
use super::*; use super::*;
use core::assert_eq; use core::assert_eq;
use core::iter::*; use core::iter::*;
use core::num::NonZeroUsize; use core::num::NonZero;
#[test] #[test]
fn test_iterator_flatten() { fn test_iterator_flatten() {
@ -72,8 +72,8 @@ fn test_flatten_advance_by() {
assert_eq!(it.advance_back_by(9), Ok(())); assert_eq!(it.advance_back_by(9), Ok(()));
assert_eq!(it.next_back(), Some(25)); assert_eq!(it.next_back(), Some(25));
assert_eq!(it.advance_by(usize::MAX), Err(NonZeroUsize::new(usize::MAX - 9).unwrap())); assert_eq!(it.advance_by(usize::MAX), Err(NonZero::<usize>::new(usize::MAX - 9).unwrap()));
assert_eq!(it.advance_back_by(usize::MAX), Err(NonZeroUsize::new(usize::MAX).unwrap())); assert_eq!(it.advance_back_by(usize::MAX), Err(NonZero::<usize>::new(usize::MAX).unwrap()));
assert_eq!(it.advance_by(0), Ok(())); assert_eq!(it.advance_by(0), Ok(()));
assert_eq!(it.advance_back_by(0), Ok(())); assert_eq!(it.advance_back_by(0), Ok(()));
assert_eq!(it.size_hint(), (0, Some(0))); assert_eq!(it.size_hint(), (0, Some(0)));

View File

@ -1,5 +1,5 @@
use core::iter::*; use core::iter::*;
use core::num::NonZeroUsize; use core::num::NonZero;
use super::Unfuse; use super::Unfuse;
@ -75,14 +75,14 @@ fn test_iterator_skip_nth() {
#[test] #[test]
fn test_skip_advance_by() { fn test_skip_advance_by() {
assert_eq!((0..0).skip(10).advance_by(0), Ok(())); assert_eq!((0..0).skip(10).advance_by(0), Ok(()));
assert_eq!((0..0).skip(10).advance_by(1), Err(NonZeroUsize::new(1).unwrap())); assert_eq!((0..0).skip(10).advance_by(1), Err(NonZero::<usize>::new(1).unwrap()));
assert_eq!( assert_eq!(
(0u128..(usize::MAX as u128) + 1).skip(usize::MAX - 10).advance_by(usize::MAX - 5), (0u128..(usize::MAX as u128) + 1).skip(usize::MAX - 10).advance_by(usize::MAX - 5),
Err(NonZeroUsize::new(usize::MAX - 16).unwrap()) Err(NonZero::<usize>::new(usize::MAX - 16).unwrap())
); );
assert_eq!((0u128..u128::MAX).skip(usize::MAX - 10).advance_by(20), Ok(())); assert_eq!((0u128..u128::MAX).skip(usize::MAX - 10).advance_by(20), Ok(()));
assert_eq!((0..2).skip(1).advance_back_by(10), Err(NonZeroUsize::new(9).unwrap())); assert_eq!((0..2).skip(1).advance_back_by(10), Err(NonZero::<usize>::new(9).unwrap()));
assert_eq!((0..0).skip(1).advance_back_by(0), Ok(())); assert_eq!((0..0).skip(1).advance_back_by(0), Ok(()));
} }

View File

@ -1,5 +1,5 @@
use core::iter::*; use core::iter::*;
use core::num::NonZeroUsize; use core::num::NonZero;
#[test] #[test]
fn test_iterator_take() { fn test_iterator_take() {
@ -79,23 +79,23 @@ fn test_take_advance_by() {
let mut take = (0..10).take(3); let mut take = (0..10).take(3);
assert_eq!(take.advance_by(2), Ok(())); assert_eq!(take.advance_by(2), Ok(()));
assert_eq!(take.next(), Some(2)); assert_eq!(take.next(), Some(2));
assert_eq!(take.advance_by(1), Err(NonZeroUsize::new(1).unwrap())); assert_eq!(take.advance_by(1), Err(NonZero::<usize>::new(1).unwrap()));
assert_eq!((0..0).take(10).advance_by(0), Ok(())); assert_eq!((0..0).take(10).advance_by(0), Ok(()));
assert_eq!((0..0).take(10).advance_by(1), Err(NonZeroUsize::new(1).unwrap())); assert_eq!((0..0).take(10).advance_by(1), Err(NonZero::<usize>::new(1).unwrap()));
assert_eq!((0..10).take(4).advance_by(5), Err(NonZeroUsize::new(1).unwrap())); assert_eq!((0..10).take(4).advance_by(5), Err(NonZero::<usize>::new(1).unwrap()));
let mut take = (0..10).take(3); let mut take = (0..10).take(3);
assert_eq!(take.advance_back_by(2), Ok(())); assert_eq!(take.advance_back_by(2), Ok(()));
assert_eq!(take.next(), Some(0)); assert_eq!(take.next(), Some(0));
assert_eq!(take.advance_back_by(1), Err(NonZeroUsize::new(1).unwrap())); assert_eq!(take.advance_back_by(1), Err(NonZero::<usize>::new(1).unwrap()));
assert_eq!((0..2).take(1).advance_back_by(10), Err(NonZeroUsize::new(9).unwrap())); assert_eq!((0..2).take(1).advance_back_by(10), Err(NonZero::<usize>::new(9).unwrap()));
assert_eq!((0..0).take(1).advance_back_by(1), Err(NonZeroUsize::new(1).unwrap())); assert_eq!((0..0).take(1).advance_back_by(1), Err(NonZero::<usize>::new(1).unwrap()));
assert_eq!((0..0).take(1).advance_back_by(0), Ok(())); assert_eq!((0..0).take(1).advance_back_by(0), Ok(()));
assert_eq!( assert_eq!(
(0..usize::MAX).take(100).advance_back_by(usize::MAX), (0..usize::MAX).take(100).advance_back_by(usize::MAX),
Err(NonZeroUsize::new(usize::MAX - 100).unwrap()) Err(NonZero::<usize>::new(usize::MAX - 100).unwrap())
); );
} }

Some files were not shown because too many files have changed in this diff Show More