Skip to content
/ rust Public
forked from rust-lang/rust

Commit b6a23b8

Browse files
committed
Auto merge of rust-lang#121454 - reitermarkus:generic-nonzero-library, r=dtolnay
Use generic `NonZero` everywhere in `library`. Tracking issue: rust-lang#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

Diff for: library/alloc/src/ffi/c_str.rs

+9-9
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
}

Diff for: library/alloc/src/vec/is_zero.rs

+19-32
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
}

Diff for: library/core/src/array/mod.rs

+5-5
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")]

Diff for: library/core/src/cmp/bytewise.rs

+25-26
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 {

Diff for: library/core/src/iter/traits/double_ended.rs

+4-4
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

Diff for: library/core/src/iter/traits/iterator.rs

+12-11
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]

Diff for: library/core/src/num/nonzero.rs

+7-9
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.

0 commit comments

Comments
 (0)