Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit b6a23b8

Browse files
committedFeb 23, 2024
Auto merge of #121454 - reitermarkus:generic-nonzero-library, r=dtolnay
Use generic `NonZero` everywhere in `library`. Tracking issue: #120257 Use generic `NonZero` everywhere (except stable examples). r? `@dtolnay`
2 parents 52cea08 + b74d8db commit b6a23b8

File tree

18 files changed

+128
-142
lines changed

18 files changed

+128
-142
lines changed
 

‎library/alloc/src/ffi/c_str.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use core::borrow::Borrow;
1111
use core::ffi::{c_char, CStr};
1212
use core::fmt;
1313
use core::mem;
14-
use core::num::NonZeroU8;
14+
use core::num::NonZero;
1515
use core::ops;
1616
use core::ptr;
1717
use core::slice;
@@ -795,22 +795,22 @@ impl From<Box<CStr>> for CString {
795795
}
796796

797797
#[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
798-
impl From<Vec<NonZeroU8>> for CString {
799-
/// Converts a <code>[Vec]<[NonZeroU8]></code> into a [`CString`] without
798+
impl From<Vec<NonZero<u8>>> for CString {
799+
/// Converts a <code>[Vec]<[NonZero]<[u8]>></code> into a [`CString`] without
800800
/// copying nor checking for inner nul bytes.
801801
#[inline]
802-
fn from(v: Vec<NonZeroU8>) -> CString {
802+
fn from(v: Vec<NonZero<u8>>) -> CString {
803803
unsafe {
804-
// Transmute `Vec<NonZeroU8>` to `Vec<u8>`.
804+
// Transmute `Vec<NonZero<u8>>` to `Vec<u8>`.
805805
let v: Vec<u8> = {
806806
// SAFETY:
807-
// - transmuting between `NonZeroU8` and `u8` is sound;
808-
// - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
809-
let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
807+
// - transmuting between `NonZero<u8>` and `u8` is sound;
808+
// - `alloc::Layout<NonZero<u8>> == alloc::Layout<u8>`.
809+
let (ptr, len, cap): (*mut NonZero<u8>, _, _) = Vec::into_raw_parts(v);
810810
Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
811811
};
812812
// SAFETY: `v` cannot contain nul bytes, given the type-level
813-
// invariant of `NonZeroU8`.
813+
// invariant of `NonZero<u8>`.
814814
Self::_from_vec_unchecked(v)
815815
}
816816
}

‎library/alloc/src/vec/is_zero.rs

Lines changed: 19 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use core::num::{Saturating, Wrapping};
1+
use core::num::{NonZero, Saturating, Wrapping};
22

33
use crate::boxed::Box;
44

@@ -69,7 +69,7 @@ unsafe impl<T: IsZero, const N: usize> IsZero for [T; N] {
6969
}
7070

7171
// This is recursive macro.
72-
macro_rules! impl_for_tuples {
72+
macro_rules! impl_is_zero_tuples {
7373
// Stopper
7474
() => {
7575
// No use for implementing for empty tuple because it is ZST.
@@ -88,11 +88,11 @@ macro_rules! impl_for_tuples {
8888
}
8989
}
9090

91-
impl_for_tuples!($($rest),*);
91+
impl_is_zero_tuples!($($rest),*);
9292
}
9393
}
9494

95-
impl_for_tuples!(A, B, C, D, E, F, G, H);
95+
impl_is_zero_tuples!(A, B, C, D, E, F, G, H);
9696

9797
// `Option<&T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
9898
// For fat pointers, the bytes that would be the pointer metadata in the `Some`
@@ -115,16 +115,15 @@ unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
115115
}
116116
}
117117

118-
// `Option<num::NonZeroU32>` and similar have a representation guarantee that
118+
// `Option<NonZero<u32>>` and similar have a representation guarantee that
119119
// they're the same size as the corresponding `u32` type, as well as a guarantee
120-
// that transmuting between `NonZeroU32` and `Option<num::NonZeroU32>` works.
120+
// that transmuting between `NonZero<u32>` and `Option<NonZero<u32>>` works.
121121
// While the documentation officially makes it UB to transmute from `None`,
122122
// we're the standard library so we can make extra inferences, and we know that
123123
// the only niche available to represent `None` is the one that's all zeros.
124-
125-
macro_rules! impl_is_zero_option_of_nonzero {
126-
($($t:ident,)+) => {$(
127-
unsafe impl IsZero for Option<core::num::$t> {
124+
macro_rules! impl_is_zero_option_of_nonzero_int {
125+
($($t:ty),+ $(,)?) => {$(
126+
unsafe impl IsZero for Option<NonZero<$t>> {
128127
#[inline]
129128
fn is_zero(&self) -> bool {
130129
self.is_none()
@@ -133,23 +132,10 @@ macro_rules! impl_is_zero_option_of_nonzero {
133132
)+};
134133
}
135134

136-
impl_is_zero_option_of_nonzero!(
137-
NonZeroU8,
138-
NonZeroU16,
139-
NonZeroU32,
140-
NonZeroU64,
141-
NonZeroU128,
142-
NonZeroI8,
143-
NonZeroI16,
144-
NonZeroI32,
145-
NonZeroI64,
146-
NonZeroI128,
147-
NonZeroUsize,
148-
NonZeroIsize,
149-
);
150-
151-
macro_rules! impl_is_zero_option_of_num {
152-
($($t:ty,)+) => {$(
135+
impl_is_zero_option_of_nonzero_int!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
136+
137+
macro_rules! impl_is_zero_option_of_int {
138+
($($t:ty),+ $(,)?) => {$(
153139
unsafe impl IsZero for Option<$t> {
154140
#[inline]
155141
fn is_zero(&self) -> bool {
@@ -163,7 +149,7 @@ macro_rules! impl_is_zero_option_of_num {
163149
)+};
164150
}
165151

166-
impl_is_zero_option_of_num!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, usize, isize,);
152+
impl_is_zero_option_of_int!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, usize, isize);
167153

168154
unsafe impl<T: IsZero> IsZero for Wrapping<T> {
169155
#[inline]
@@ -179,8 +165,8 @@ unsafe impl<T: IsZero> IsZero for Saturating<T> {
179165
}
180166
}
181167

182-
macro_rules! impl_for_optional_bool {
183-
($($t:ty,)+) => {$(
168+
macro_rules! impl_is_zero_option_of_bool {
169+
($($t:ty),+ $(,)?) => {$(
184170
unsafe impl IsZero for $t {
185171
#[inline]
186172
fn is_zero(&self) -> bool {
@@ -194,9 +180,10 @@ macro_rules! impl_for_optional_bool {
194180
}
195181
)+};
196182
}
197-
impl_for_optional_bool! {
183+
184+
impl_is_zero_option_of_bool! {
198185
Option<bool>,
199186
Option<Option<bool>>,
200187
Option<Option<Option<bool>>>,
201-
// Could go further, but not worth the metadata overhead
188+
// Could go further, but not worth the metadata overhead.
202189
}

‎library/core/src/array/mod.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -511,7 +511,7 @@ impl<T, const N: usize> [T; N] {
511511
/// # Examples
512512
///
513513
/// ```
514-
/// #![feature(array_try_map)]
514+
/// #![feature(array_try_map, generic_nonzero)]
515515
/// let a = ["1", "2", "3"];
516516
/// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
517517
/// assert_eq!(b, [2, 3, 4]);
@@ -520,12 +520,12 @@ impl<T, const N: usize> [T; N] {
520520
/// let b = a.try_map(|v| v.parse::<u32>());
521521
/// assert!(b.is_err());
522522
///
523-
/// use std::num::NonZeroU32;
523+
/// use std::num::NonZero;
524524
/// let z = [1, 2, 0, 3, 4];
525-
/// assert_eq!(z.try_map(NonZeroU32::new), None);
525+
/// assert_eq!(z.try_map(NonZero::new), None);
526526
/// let a = [1, 2, 3];
527-
/// let b = a.try_map(NonZeroU32::new);
528-
/// let c = b.map(|x| x.map(NonZeroU32::get));
527+
/// let b = a.try_map(NonZero::new);
528+
/// let c = b.map(|x| x.map(NonZero::get));
529529
/// assert_eq!(c, Some(a));
530530
/// ```
531531
#[unstable(feature = "array_try_map", issue = "79711")]

‎library/core/src/cmp/bytewise.rs

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
use crate::num::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize};
2-
use crate::num::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize};
1+
use crate::num::NonZero;
32

43
/// Types where `==` & `!=` are equivalent to comparing their underlying bytes.
54
///
@@ -36,37 +35,37 @@ is_bytewise_comparable!(bool, char, super::Ordering);
3635
// SAFETY: Similarly, the `NonZero` type has a niche, but no undef and no pointers,
3736
// and they compare like their underlying numeric type.
3837
is_bytewise_comparable!(
39-
NonZeroU8,
40-
NonZeroU16,
41-
NonZeroU32,
42-
NonZeroU64,
43-
NonZeroU128,
44-
NonZeroUsize,
45-
NonZeroI8,
46-
NonZeroI16,
47-
NonZeroI32,
48-
NonZeroI64,
49-
NonZeroI128,
50-
NonZeroIsize,
38+
NonZero<u8>,
39+
NonZero<u16>,
40+
NonZero<u32>,
41+
NonZero<u64>,
42+
NonZero<u128>,
43+
NonZero<usize>,
44+
NonZero<i8>,
45+
NonZero<i16>,
46+
NonZero<i32>,
47+
NonZero<i64>,
48+
NonZero<i128>,
49+
NonZero<isize>,
5150
);
5251

5352
// SAFETY: The `NonZero` type has the "null" optimization guaranteed, and thus
5453
// are also safe to equality-compare bitwise inside an `Option`.
5554
// The way `PartialOrd` is defined for `Option` means that this wouldn't work
5655
// for `<` or `>` on the signed types, but since we only do `==` it's fine.
5756
is_bytewise_comparable!(
58-
Option<NonZeroU8>,
59-
Option<NonZeroU16>,
60-
Option<NonZeroU32>,
61-
Option<NonZeroU64>,
62-
Option<NonZeroU128>,
63-
Option<NonZeroUsize>,
64-
Option<NonZeroI8>,
65-
Option<NonZeroI16>,
66-
Option<NonZeroI32>,
67-
Option<NonZeroI64>,
68-
Option<NonZeroI128>,
69-
Option<NonZeroIsize>,
57+
Option<NonZero<u8>>,
58+
Option<NonZero<u16>>,
59+
Option<NonZero<u32>>,
60+
Option<NonZero<u64>>,
61+
Option<NonZero<u128>>,
62+
Option<NonZero<usize>>,
63+
Option<NonZero<i8>>,
64+
Option<NonZero<i16>>,
65+
Option<NonZero<i32>>,
66+
Option<NonZero<i64>>,
67+
Option<NonZero<i128>>,
68+
Option<NonZero<isize>>,
7069
);
7170

7271
macro_rules! is_bytewise_comparable_array_length {

‎library/core/src/iter/traits/double_ended.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ pub trait DoubleEndedIterator: Iterator {
100100
/// to `n` times until [`None`] is encountered.
101101
///
102102
/// `advance_back_by(n)` will return `Ok(())` if the iterator successfully advances by
103-
/// `n` elements, or a `Err(NonZeroUsize)` with value `k` if [`None`] is encountered, where `k`
103+
/// `n` elements, or a `Err(NonZero<usize>)` with value `k` if [`None`] is encountered, where `k`
104104
/// is remaining number of steps that could not be advanced because the iterator ran out.
105105
/// If `self` is empty and `n` is non-zero, then this returns `Err(n)`.
106106
/// Otherwise, `k` is always less than `n`.
@@ -118,16 +118,16 @@ pub trait DoubleEndedIterator: Iterator {
118118
/// Basic usage:
119119
///
120120
/// ```
121-
/// #![feature(iter_advance_by)]
122-
/// use std::num::NonZeroUsize;
121+
/// #![feature(generic_nonzero, iter_advance_by)]
122+
/// use std::num::NonZero;
123123
///
124124
/// let a = [3, 4, 5, 6];
125125
/// let mut iter = a.iter();
126126
///
127127
/// assert_eq!(iter.advance_back_by(2), Ok(()));
128128
/// assert_eq!(iter.next_back(), Some(&4));
129129
/// assert_eq!(iter.advance_back_by(0), Ok(()));
130-
/// assert_eq!(iter.advance_back_by(100), Err(NonZeroUsize::new(99).unwrap())); // only `&3` was skipped
130+
/// assert_eq!(iter.advance_back_by(100), Err(NonZero::new(99).unwrap())); // only `&3` was skipped
131131
/// ```
132132
///
133133
/// [`Ok(())`]: Ok

‎library/core/src/iter/traits/iterator.rs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ pub trait Iterator {
304304
/// times until [`None`] is encountered.
305305
///
306306
/// `advance_by(n)` will return `Ok(())` if the iterator successfully advances by
307-
/// `n` elements, or a `Err(NonZeroUsize)` with value `k` if [`None`] is encountered,
307+
/// `n` elements, or a `Err(NonZero<usize>)` with value `k` if [`None`] is encountered,
308308
/// where `k` is remaining number of steps that could not be advanced because the iterator ran out.
309309
/// If `self` is empty and `n` is non-zero, then this returns `Err(n)`.
310310
/// Otherwise, `k` is always less than `n`.
@@ -319,16 +319,16 @@ pub trait Iterator {
319319
/// # Examples
320320
///
321321
/// ```
322-
/// #![feature(iter_advance_by)]
323-
/// use std::num::NonZeroUsize;
322+
/// #![feature(generic_nonzero, iter_advance_by)]
323+
/// use std::num::NonZero;
324324
///
325325
/// let a = [1, 2, 3, 4];
326326
/// let mut iter = a.iter();
327327
///
328328
/// assert_eq!(iter.advance_by(2), Ok(()));
329329
/// assert_eq!(iter.next(), Some(&3));
330330
/// assert_eq!(iter.advance_by(0), Ok(()));
331-
/// assert_eq!(iter.advance_by(100), Err(NonZeroUsize::new(99).unwrap())); // only `&4` was skipped
331+
/// assert_eq!(iter.advance_by(100), Err(NonZero::new(99).unwrap())); // only `&4` was skipped
332332
/// ```
333333
#[inline]
334334
#[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
@@ -2967,17 +2967,18 @@ pub trait Iterator {
29672967
/// assert!(result.is_err());
29682968
/// ```
29692969
///
2970-
/// This also supports other types which implement `Try`, not just `Result`.
2970+
/// This also supports other types which implement [`Try`], not just [`Result`].
2971+
///
29712972
/// ```
2972-
/// #![feature(try_find)]
2973+
/// #![feature(generic_nonzero, try_find)]
2974+
/// use std::num::NonZero;
29732975
///
2974-
/// use std::num::NonZeroU32;
2975-
/// let a = [3, 5, 7, 4, 9, 0, 11];
2976-
/// let result = a.iter().try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
2976+
/// let a = [3, 5, 7, 4, 9, 0, 11u32];
2977+
/// let result = a.iter().try_find(|&&x| NonZero::new(x).map(|y| y.is_power_of_two()));
29772978
/// assert_eq!(result, Some(Some(&4)));
2978-
/// let result = a.iter().take(3).try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
2979+
/// let result = a.iter().take(3).try_find(|&&x| NonZero::new(x).map(|y| y.is_power_of_two()));
29792980
/// assert_eq!(result, Some(None));
2980-
/// let result = a.iter().rev().try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
2981+
/// let result = a.iter().rev().try_find(|&&x| NonZero::new(x).map(|y| y.is_power_of_two()));
29812982
/// assert_eq!(result, None);
29822983
/// ```
29832984
#[inline]

‎library/core/src/num/nonzero.rs

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ mod private {
2323

2424
/// A marker trait for primitive types which can be zero.
2525
///
26-
/// This is an implementation detail for [`NonZero<T>`](NonZero) which may disappear or be replaced at any time.
26+
/// This is an implementation detail for <code>[NonZero]\<T></code> which may disappear or be replaced at any time.
2727
#[unstable(
2828
feature = "nonzero_internals",
2929
reason = "implementation detail which may disappear or be replaced at any time",
@@ -507,18 +507,16 @@ macro_rules! nonzero_integer {
507507
/// Basic usage:
508508
///
509509
/// ```
510-
/// #![feature(non_zero_count_ones)]
510+
/// #![feature(generic_nonzero, non_zero_count_ones)]
511511
/// # fn main() { test().unwrap(); }
512512
/// # fn test() -> Option<()> {
513513
/// # use std::num::*;
514514
/// #
515-
/// let one = NonZeroU32::new(1)?;
516-
/// let three = NonZeroU32::new(3)?;
517-
#[doc = concat!("let a = ", stringify!($Ty), "::new(0b100_0000)?;")]
518-
#[doc = concat!("let b = ", stringify!($Ty), "::new(0b100_0011)?;")]
515+
#[doc = concat!("let a = NonZero::<", stringify!($Int), ">::new(0b100_0000)?;")]
516+
#[doc = concat!("let b = NonZero::<", stringify!($Int), ">::new(0b100_0011)?;")]
519517
///
520-
/// assert_eq!(a.count_ones(), one);
521-
/// assert_eq!(b.count_ones(), three);
518+
/// assert_eq!(a.count_ones(), NonZero::new(1)?);
519+
/// assert_eq!(b.count_ones(), NonZero::new(3)?);
522520
/// # Some(())
523521
/// # }
524522
/// ```
@@ -530,7 +528,7 @@ macro_rules! nonzero_integer {
530528
#[must_use = "this returns the result of the operation, \
531529
without modifying the original"]
532530
#[inline(always)]
533-
pub const fn count_ones(self) -> NonZeroU32 {
531+
pub const fn count_ones(self) -> NonZero<u32> {
534532
// SAFETY:
535533
// `self` is non-zero, which means it has at least one bit set, which means
536534
// that the result of `count_ones` is non-zero.

‎library/core/src/option.rs

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,7 @@ use crate::panicking::{panic, panic_str};
558558
use crate::pin::Pin;
559559
use crate::{
560560
cmp, convert, hint, mem,
561+
num::NonZero,
561562
ops::{self, ControlFlow, Deref, DerefMut},
562563
slice,
563564
};
@@ -2194,18 +2195,18 @@ macro_rules! non_zero_option {
21942195
}
21952196

21962197
non_zero_option! {
2197-
#[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU8;
2198-
#[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU16;
2199-
#[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU32;
2200-
#[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU64;
2201-
#[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU128;
2202-
#[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroUsize;
2203-
#[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI8;
2204-
#[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI16;
2205-
#[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI32;
2206-
#[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI64;
2207-
#[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI128;
2208-
#[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroIsize;
2198+
#[stable(feature = "nonzero", since = "1.28.0")] NonZero<u8>;
2199+
#[stable(feature = "nonzero", since = "1.28.0")] NonZero<u16>;
2200+
#[stable(feature = "nonzero", since = "1.28.0")] NonZero<u32>;
2201+
#[stable(feature = "nonzero", since = "1.28.0")] NonZero<u64>;
2202+
#[stable(feature = "nonzero", since = "1.28.0")] NonZero<u128>;
2203+
#[stable(feature = "nonzero", since = "1.28.0")] NonZero<usize>;
2204+
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZero<i8>;
2205+
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZero<i16>;
2206+
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZero<i32>;
2207+
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZero<i64>;
2208+
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZero<i128>;
2209+
#[stable(feature = "signed_nonzero", since = "1.34.0")] NonZero<isize>;
22092210
}
22102211

22112212
#[stable(feature = "nonnull", since = "1.25.0")]

‎library/core/src/primitive_docs.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1577,8 +1577,7 @@ mod prim_ref {}
15771577
/// - Any two types with size 0 and alignment 1 are ABI-compatible.
15781578
/// - A `repr(transparent)` type `T` is ABI-compatible with its unique non-trivial field, i.e., the
15791579
/// unique field that doesn't have size 0 and alignment 1 (if there is such a field).
1580-
/// - `i32` is ABI-compatible with `NonZeroI32`, and similar for all other integer types with their
1581-
/// matching `NonZero*` type.
1580+
/// - `i32` is ABI-compatible with `NonZero<i32>`, and similar for all other integer types.
15821581
/// - If `T` is guaranteed to be subject to the [null pointer
15831582
/// optimization](option/index.html#representation), then `T` and `Option<T>` are ABI-compatible.
15841583
///
@@ -1613,9 +1612,9 @@ mod prim_ref {}
16131612
/// type in the function pointer to the type at the function declaration, and the return value is
16141613
/// [`transmute`d][mem::transmute] from the type in the declaration to the type in the
16151614
/// pointer. All the usual caveats and concerns around transmutation apply; for instance, if the
1616-
/// function expects a `NonZeroI32` and the function pointer uses the ABI-compatible type
1617-
/// `Option<NonZeroI32>`, and the value used for the argument is `None`, then this call is Undefined
1618-
/// Behavior since transmuting `None::<NonZeroI32>` to `NonZeroI32` violates the non-zero
1615+
/// function expects a `NonZero<i32>` and the function pointer uses the ABI-compatible type
1616+
/// `Option<NonZero<i32>>`, and the value used for the argument is `None`, then this call is Undefined
1617+
/// Behavior since transmuting `None::<NonZero<i32>>` to `NonZero<i32>` violates the non-zero
16191618
/// requirement.
16201619
///
16211620
/// #### Requirements concerning target features

‎library/core/src/ptr/alignment.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::convert::{TryFrom, TryInto};
2-
use crate::num::{NonZero, NonZeroUsize};
2+
use crate::num::NonZero;
33
use crate::{cmp, fmt, hash, mem, num};
44

55
/// A type storing a `usize` which is a power of two, and thus
@@ -87,19 +87,19 @@ impl Alignment {
8787
unsafe { mem::transmute::<usize, Alignment>(align) }
8888
}
8989

90-
/// Returns the alignment as a [`usize`]
90+
/// Returns the alignment as a [`usize`].
9191
#[unstable(feature = "ptr_alignment_type", issue = "102070")]
9292
#[rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070")]
9393
#[inline]
9494
pub const fn as_usize(self) -> usize {
9595
self.0 as usize
9696
}
9797

98-
/// Returns the alignment as a [`NonZeroUsize`]
98+
/// Returns the alignment as a <code>[NonZero]<[usize]></code>.
9999
#[unstable(feature = "ptr_alignment_type", issue = "102070")]
100100
#[rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070")]
101101
#[inline]
102-
pub const fn as_nonzero(self) -> NonZeroUsize {
102+
pub const fn as_nonzero(self) -> NonZero<usize> {
103103
// SAFETY: All the discriminants are non-zero.
104104
unsafe { NonZero::new_unchecked(self.as_usize()) }
105105
}
@@ -164,11 +164,11 @@ impl fmt::Debug for Alignment {
164164
}
165165

166166
#[unstable(feature = "ptr_alignment_type", issue = "102070")]
167-
impl TryFrom<NonZeroUsize> for Alignment {
167+
impl TryFrom<NonZero<usize>> for Alignment {
168168
type Error = num::TryFromIntError;
169169

170170
#[inline]
171-
fn try_from(align: NonZeroUsize) -> Result<Alignment, Self::Error> {
171+
fn try_from(align: NonZero<usize>) -> Result<Alignment, Self::Error> {
172172
align.get().try_into()
173173
}
174174
}
@@ -184,9 +184,9 @@ impl TryFrom<usize> for Alignment {
184184
}
185185

186186
#[unstable(feature = "ptr_alignment_type", issue = "102070")]
187-
impl From<Alignment> for NonZeroUsize {
187+
impl From<Alignment> for NonZero<usize> {
188188
#[inline]
189-
fn from(align: Alignment) -> NonZeroUsize {
189+
fn from(align: Alignment) -> NonZero<usize> {
190190
align.as_nonzero()
191191
}
192192
}

‎library/core/src/ptr/non_null.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::intrinsics;
55
use crate::intrinsics::assert_unsafe_precondition;
66
use crate::marker::Unsize;
77
use crate::mem::{MaybeUninit, SizedTypeProperties};
8-
use crate::num::{NonZero, NonZeroUsize};
8+
use crate::num::NonZero;
99
use crate::ops::{CoerceUnsized, DispatchFromDyn};
1010
use crate::ptr;
1111
use crate::ptr::Unique;
@@ -291,7 +291,7 @@ impl<T: ?Sized> NonNull<T> {
291291
#[must_use]
292292
#[inline]
293293
#[unstable(feature = "strict_provenance", issue = "95228")]
294-
pub fn addr(self) -> NonZeroUsize {
294+
pub fn addr(self) -> NonZero<usize> {
295295
// SAFETY: The pointer is guaranteed by the type to be non-null,
296296
// meaning that the address will be non-zero.
297297
unsafe { NonZero::new_unchecked(self.pointer.addr()) }
@@ -306,7 +306,7 @@ impl<T: ?Sized> NonNull<T> {
306306
#[must_use]
307307
#[inline]
308308
#[unstable(feature = "strict_provenance", issue = "95228")]
309-
pub fn with_addr(self, addr: NonZeroUsize) -> Self {
309+
pub fn with_addr(self, addr: NonZero<usize>) -> Self {
310310
// SAFETY: The result of `ptr::from::with_addr` is non-null because `addr` is guaranteed to be non-zero.
311311
unsafe { NonNull::new_unchecked(self.pointer.with_addr(addr.get()) as *mut _) }
312312
}
@@ -320,7 +320,7 @@ impl<T: ?Sized> NonNull<T> {
320320
#[must_use]
321321
#[inline]
322322
#[unstable(feature = "strict_provenance", issue = "95228")]
323-
pub fn map_addr(self, f: impl FnOnce(NonZeroUsize) -> NonZeroUsize) -> Self {
323+
pub fn map_addr(self, f: impl FnOnce(NonZero<usize>) -> NonZero<usize>) -> Self {
324324
self.with_addr(f(self.addr()))
325325
}
326326

‎library/core/src/str/iter.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@ use crate::fmt::{self, Write};
55
use crate::iter::{Chain, FlatMap, Flatten};
66
use crate::iter::{Copied, Filter, FusedIterator, Map, TrustedLen};
77
use crate::iter::{TrustedRandomAccess, TrustedRandomAccessNoCoerce};
8+
use crate::num::NonZero;
89
use crate::ops::Try;
910
use crate::option;
1011
use crate::slice::{self, Split as SliceSplit};
11-
use core::num::{NonZero, NonZeroUsize};
1212

1313
use super::from_utf8_unchecked;
1414
use super::pattern::Pattern;
@@ -51,7 +51,7 @@ impl<'a> Iterator for Chars<'a> {
5151
}
5252

5353
#[inline]
54-
fn advance_by(&mut self, mut remainder: usize) -> Result<(), NonZeroUsize> {
54+
fn advance_by(&mut self, mut remainder: usize) -> Result<(), NonZero<usize>> {
5555
const CHUNK_SIZE: usize = 32;
5656

5757
if remainder >= CHUNK_SIZE {

‎library/proc_macro/src/bridge/symbol.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ thread_local! {
136136
arena: arena::Arena::new(),
137137
names: fxhash::FxHashMap::default(),
138138
strings: Vec::new(),
139-
// Start with a base of 1 to make sure that `NonZeroU32` works.
139+
// Start with a base of 1 to make sure that `NonZero<u32>` works.
140140
sym_base: NonZero::new(1).unwrap(),
141141
});
142142
}

‎library/std/src/io/error/repr_bitpacked.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373
//! union Repr {
7474
//! // holds integer (Simple/Os) variants, and
7575
//! // provides access to the tag bits.
76-
//! bits: NonZeroU64,
76+
//! bits: NonZero<u64>,
7777
//! // Tag is 0, so this is stored untagged.
7878
//! msg: &'static SimpleMessage,
7979
//! // Tagged (offset) `Box<Custom>` pointer.
@@ -93,7 +93,7 @@
9393
//! `io::Result<()>` and `io::Result<usize>` larger, which defeats part of
9494
//! the motivation of this bitpacking.
9595
//!
96-
//! Storing everything in a `NonZeroUsize` (or some other integer) would be a
96+
//! Storing everything in a `NonZero<usize>` (or some other integer) would be a
9797
//! bit more traditional for pointer tagging, but it would lose provenance
9898
//! information, couldn't be constructed from a `const fn`, and would probably
9999
//! run into other issues as well.

‎library/std/src/process.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ use crate::ffi::OsStr;
111111
use crate::fmt;
112112
use crate::fs;
113113
use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut};
114-
use crate::num::NonZeroI32;
114+
use crate::num::NonZero;
115115
use crate::path::Path;
116116
use crate::str;
117117
use crate::sys::pipe::{read2, AnonPipe};
@@ -1775,9 +1775,9 @@ impl ExitStatusError {
17751775
self.code_nonzero().map(Into::into)
17761776
}
17771777

1778-
/// Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero`
1778+
/// Reports the exit code, if applicable, from an `ExitStatusError`, as a [`NonZero`].
17791779
///
1780-
/// This is exactly like [`code()`](Self::code), except that it returns a `NonZeroI32`.
1780+
/// This is exactly like [`code()`](Self::code), except that it returns a <code>[NonZero]<[i32]></code>.
17811781
///
17821782
/// Plain `code`, returning a plain integer, is provided because it is often more convenient.
17831783
/// The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want
@@ -1786,17 +1786,17 @@ impl ExitStatusError {
17861786
/// # Examples
17871787
///
17881788
/// ```
1789-
/// #![feature(exit_status_error)]
1789+
/// #![feature(exit_status_error, generic_nonzero)]
17901790
/// # if cfg!(unix) {
1791-
/// use std::num::NonZeroI32;
1791+
/// use std::num::NonZero;
17921792
/// use std::process::Command;
17931793
///
17941794
/// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err();
1795-
/// assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap());
1795+
/// assert_eq!(bad.code_nonzero().unwrap(), NonZero::new(1).unwrap());
17961796
/// # } // cfg!(unix)
17971797
/// ```
17981798
#[must_use]
1799-
pub fn code_nonzero(&self) -> Option<NonZeroI32> {
1799+
pub fn code_nonzero(&self) -> Option<NonZero<i32>> {
18001800
self.0.code()
18011801
}
18021802

‎library/std/src/thread/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ use crate::fmt;
165165
use crate::io;
166166
use crate::marker::PhantomData;
167167
use crate::mem::{self, forget};
168-
use crate::num::{NonZero, NonZeroU64, NonZeroUsize};
168+
use crate::num::NonZero;
169169
use crate::panic;
170170
use crate::panicking;
171171
use crate::pin::Pin;
@@ -1222,7 +1222,7 @@ impl ThreadId {
12221222
/// change across Rust versions.
12231223
#[must_use]
12241224
#[unstable(feature = "thread_id_value", issue = "67939")]
1225-
pub fn as_u64(&self) -> NonZeroU64 {
1225+
pub fn as_u64(&self) -> NonZero<u64> {
12261226
self.0
12271227
}
12281228
}
@@ -1784,6 +1784,6 @@ fn _assert_sync_and_send() {
17841784
#[doc(alias = "hardware_concurrency")] // Alias for C++ `std::thread::hardware_concurrency`.
17851785
#[doc(alias = "num_cpus")] // Alias for a popular ecosystem crate which provides similar functionality.
17861786
#[stable(feature = "available_parallelism", since = "1.59.0")]
1787-
pub fn available_parallelism() -> io::Result<NonZeroUsize> {
1787+
pub fn available_parallelism() -> io::Result<NonZero<usize>> {
17881788
imp::available_parallelism()
17891789
}

‎library/test/src/helpers/concurrency.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
//! Helper module which helps to determine amount of threads to be used
22
//! during tests execution.
3-
use std::{env, num::NonZeroUsize, thread};
3+
use std::{env, num::NonZero, thread};
44

55
pub fn get_concurrency() -> usize {
66
if let Ok(value) = env::var("RUST_TEST_THREADS") {
7-
match value.parse::<NonZeroUsize>().ok() {
7+
match value.parse::<NonZero<usize>>().ok() {
88
Some(n) => n.get(),
99
_ => panic!("RUST_TEST_THREADS is `{value}`, should be a positive integer."),
1010
}

‎library/test/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
#![unstable(feature = "test", issue = "50297")]
1818
#![doc(test(attr(deny(warnings))))]
1919
#![doc(rust_logo)]
20+
#![feature(generic_nonzero)]
2021
#![feature(rustdoc_internals)]
2122
#![feature(internal_output_capture)]
2223
#![feature(staged_api)]

0 commit comments

Comments
 (0)
Please sign in to comment.