Skip to content

Commit a1160ba

Browse files
committed
Use generic NonZero.
1 parent e94ddb2 commit a1160ba

File tree

19 files changed

+62
-61
lines changed

19 files changed

+62
-61
lines changed

compiler/rustc_abi/src/layout.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::borrow::{Borrow, Cow};
22
use std::cmp;
33
use std::fmt::{self, Write};
44
use std::iter;
5+
use std::num::NonZero;
56
use std::ops::Bound;
67
use std::ops::Deref;
78

@@ -10,8 +11,8 @@ use tracing::debug;
1011

1112
use crate::{
1213
Abi, AbiAndPrefAlign, Align, FieldsShape, IndexSlice, IndexVec, Integer, LayoutS, Niche,
13-
NonZeroUsize, Primitive, ReprOptions, Scalar, Size, StructKind, TagEncoding, TargetDataLayout,
14-
Variants, WrappingRange,
14+
Primitive, ReprOptions, Scalar, Size, StructKind, TagEncoding, TargetDataLayout, Variants,
15+
WrappingRange,
1516
};
1617

1718
// A variant is absent if it's uninhabited and only has ZST fields.
@@ -327,7 +328,7 @@ pub trait LayoutCalculator {
327328

328329
Some(LayoutS {
329330
variants: Variants::Single { index: VariantIdx::new(0) },
330-
fields: FieldsShape::Union(NonZeroUsize::new(only_variant.len())?),
331+
fields: FieldsShape::Union(NonZero::new(only_variant.len())?),
331332
abi,
332333
largest_niche: None,
333334
align,

compiler/rustc_abi/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
#![cfg_attr(feature = "nightly", feature(rustdoc_internals))]
55

66
use std::fmt;
7-
use std::num::{NonZeroUsize, ParseIntError};
7+
use std::num::{NonZero, ParseIntError};
88
use std::ops::{Add, AddAssign, Mul, RangeInclusive, Sub};
99
use std::str::FromStr;
1010

@@ -1137,7 +1137,7 @@ pub enum FieldsShape<FieldIdx: Idx> {
11371137
Primitive,
11381138

11391139
/// All fields start at no offset. The `usize` is the field count.
1140-
Union(NonZeroUsize),
1140+
Union(NonZero<usize>),
11411141

11421142
/// Array/vector-like placement, with all fields of identical types.
11431143
Array { stride: Size, count: u64 },

compiler/rustc_ast/src/ast.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2158,7 +2158,7 @@ pub enum TyKind {
21582158
MacCall(P<MacCall>),
21592159
/// Placeholder for a `va_list`.
21602160
CVarArgs,
2161-
/// Pattern types like `pattern_type!(u32 is 1..=)`, which is the same as `NonZeroU32`,
2161+
/// Pattern types like `pattern_type!(u32 is 1..=)`, which is the same as `NonZero<u32>`,
21622162
/// just as part of the type system.
21632163
Pat(P<Ty>, P<Pat>),
21642164
/// Sometimes we need a dummy value when no error has occurred.

compiler/stable_mir/src/abi.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::ty::{Align, IndexedVal, Ty, VariantIdx};
66
use crate::Error;
77
use crate::Opaque;
88
use std::fmt::{self, Debug};
9-
use std::num::NonZeroUsize;
9+
use std::num::NonZero;
1010
use std::ops::RangeInclusive;
1111

1212
/// A function ABI definition.
@@ -133,7 +133,7 @@ pub enum FieldsShape {
133133
Primitive,
134134

135135
/// All fields start at no offset. The `usize` is the field count.
136-
Union(NonZeroUsize),
136+
Union(NonZero<usize>),
137137

138138
/// Array/vector-like placement, with all fields of identical types.
139139
Array { stride: Size, count: u64 },

library/core/src/iter/adapters/step_by.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::{
22
intrinsics,
33
iter::{from_fn, TrustedLen, TrustedRandomAccess},
4-
num::NonZeroUsize,
4+
num::NonZero,
55
ops::{Range, Try},
66
};
77

@@ -42,10 +42,10 @@ impl<I> StepBy<I> {
4242
/// The `step` that was originally passed to `Iterator::step_by(step)`,
4343
/// aka `self.step_minus_one + 1`.
4444
#[inline]
45-
fn original_step(&self) -> NonZeroUsize {
45+
fn original_step(&self) -> NonZero<usize> {
4646
// SAFETY: By type invariant, `step_minus_one` cannot be `MAX`, which
4747
// means the addition cannot overflow and the result cannot be zero.
48-
unsafe { NonZeroUsize::new_unchecked(intrinsics::unchecked_add(self.step_minus_one, 1)) }
48+
unsafe { NonZero::new_unchecked(intrinsics::unchecked_add(self.step_minus_one, 1)) }
4949
}
5050
}
5151

@@ -231,12 +231,12 @@ unsafe impl<I: Iterator> StepByImpl<I> for StepBy<I> {
231231
#[inline]
232232
default fn spec_size_hint(&self) -> (usize, Option<usize>) {
233233
#[inline]
234-
fn first_size(step: NonZeroUsize) -> impl Fn(usize) -> usize {
234+
fn first_size(step: NonZero<usize>) -> impl Fn(usize) -> usize {
235235
move |n| if n == 0 { 0 } else { 1 + (n - 1) / step }
236236
}
237237

238238
#[inline]
239-
fn other_size(step: NonZeroUsize) -> impl Fn(usize) -> usize {
239+
fn other_size(step: NonZero<usize>) -> impl Fn(usize) -> usize {
240240
move |n| n / step
241241
}
242242

src/tools/build-manifest/src/main.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ fn main() {
236236
let num_threads = if let Some(num) = env::var_os("BUILD_MANIFEST_NUM_THREADS") {
237237
num.to_str().unwrap().parse().expect("invalid number for BUILD_MANIFEST_NUM_THREADS")
238238
} else {
239-
std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get)
239+
std::thread::available_parallelism().map_or(1, std::num::NonZero::get)
240240
};
241241
rayon::ThreadPoolBuilder::new()
242242
.num_threads(num_threads)

src/tools/clippy/clippy_lints/src/transmute/eager_transmute.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ pub(super) fn check<'tcx>(
8787
&& is_normalizable(cx, cx.param_env, from_ty)
8888
&& is_normalizable(cx, cx.param_env, to_ty)
8989
// we only want to lint if the target type has a niche that is larger than the one of the source type
90-
// e.g. `u8` to `NonZeroU8` should lint, but `NonZeroU8` to `u8` should not
90+
// e.g. `u8` to `NonZero<u8>` should lint, but `NonZero<u8>` to `u8` should not
9191
&& let Ok(from_layout) = cx.tcx.layout_of(cx.param_env.and(from_ty))
9292
&& let Ok(to_layout) = cx.tcx.layout_of(cx.param_env.and(to_ty))
9393
&& match (from_layout.largest_niche, to_layout.largest_niche) {

src/tools/clippy/lintcheck/src/config.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use clap::Parser;
2-
use std::num::NonZeroUsize;
2+
use std::num::NonZero;
33
use std::path::PathBuf;
44

55
#[derive(Clone, Debug, Parser)]
@@ -61,7 +61,7 @@ impl LintcheckConfig {
6161
config.max_jobs = if config.fix || config.recursive {
6262
1
6363
} else {
64-
std::thread::available_parallelism().map_or(1, NonZeroUsize::get)
64+
std::thread::available_parallelism().map_or(1, NonZero::get)
6565
};
6666
};
6767

src/tools/clippy/tests/ui/arithmetic_side_effects.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
extern crate proc_macro_derive;
1717

18-
use core::num::{NonZeroUsize, Saturating, Wrapping};
18+
use core::num::{NonZero, Saturating, Wrapping};
1919

2020
const ONE: i32 = 1;
2121
const ZERO: i32 = 0;
@@ -494,15 +494,15 @@ pub fn issue_11262() {
494494
}
495495

496496
pub fn issue_11392() {
497-
fn example_div(unsigned: usize, nonzero_unsigned: NonZeroUsize) -> usize {
497+
fn example_div(unsigned: usize, nonzero_unsigned: NonZero<usize>) -> usize {
498498
unsigned / nonzero_unsigned
499499
}
500500

501-
fn example_rem(unsigned: usize, nonzero_unsigned: NonZeroUsize) -> usize {
501+
fn example_rem(unsigned: usize, nonzero_unsigned: NonZero<usize>) -> usize {
502502
unsigned % nonzero_unsigned
503503
}
504504

505-
let (unsigned, nonzero_unsigned) = (0, NonZeroUsize::new(1).unwrap());
505+
let (unsigned, nonzero_unsigned) = (0, NonZero::new(1).unwrap());
506506
example_div(unsigned, nonzero_unsigned);
507507
example_rem(unsigned, nonzero_unsigned);
508508
}

src/tools/clippy/tests/ui/eager_transmute.rs

+10-10
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
#![warn(clippy::eager_transmute)]
33
#![allow(clippy::transmute_int_to_non_zero, clippy::missing_transmute_annotations)]
44

5-
use std::num::NonZeroU8;
5+
use std::num::NonZero;
66

77
#[repr(u8)]
88
enum Opcode {
@@ -85,21 +85,21 @@ macro_rules! impls {
8585
}
8686
impls!(NonMaxU8, NonZeroNonMaxU8);
8787

88-
fn niche_tests(v1: u8, v2: NonZeroU8, v3: NonZeroNonMaxU8) {
89-
// u8 -> NonZeroU8, do lint
90-
let _: Option<NonZeroU8> = (v1 > 0).then_some(unsafe { std::mem::transmute(v1) });
88+
fn niche_tests(v1: u8, v2: NonZero<u8>, v3: NonZeroNonMaxU8) {
89+
// u8 -> NonZero<u8>, do lint
90+
let _: Option<NonZero<u8>> = (v1 > 0).then_some(unsafe { std::mem::transmute(v1) });
9191

92-
// NonZeroU8 -> u8, don't lint, target type has no niche and therefore a higher validity range
93-
let _: Option<u8> = (v2 > NonZeroU8::new(1).unwrap()).then_some(unsafe { std::mem::transmute(v2) });
92+
// NonZero<u8> -> u8, don't lint, target type has no niche and therefore a higher validity range
93+
let _: Option<u8> = (v2 > NonZero::new(1u8).unwrap()).then_some(unsafe { std::mem::transmute(v2) });
9494

95-
// NonZeroU8 -> NonMaxU8, do lint, different niche
96-
let _: Option<NonMaxU8> = (v2 < NonZeroU8::new(255).unwrap()).then_some(unsafe { std::mem::transmute(v2) });
95+
// NonZero<u8> -> NonMaxU8, do lint, different niche
96+
let _: Option<NonMaxU8> = (v2 < NonZero::new(255u8).unwrap()).then_some(unsafe { std::mem::transmute(v2) });
9797

9898
// NonZeroNonMaxU8 -> NonMaxU8, don't lint, target type has more validity
9999
let _: Option<NonMaxU8> = (v3 < 255).then_some(unsafe { std::mem::transmute(v2) });
100100

101-
// NonZeroU8 -> NonZeroNonMaxU8, do lint, target type has less validity
102-
let _: Option<NonZeroNonMaxU8> = (v2 < NonZeroU8::new(255).unwrap()).then_some(unsafe { std::mem::transmute(v2) });
101+
// NonZero<u8> -> NonZeroNonMaxU8, do lint, target type has less validity
102+
let _: Option<NonZeroNonMaxU8> = (v2 < NonZero::new(255u8).unwrap()).then_some(unsafe { std::mem::transmute(v2) });
103103
}
104104

105105
fn main() {}

src/tools/miri/tests/fail/enum-set-discriminant-niche-variant-wrong.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
#![feature(custom_mir)]
33

44
use std::intrinsics::mir::*;
5-
use std::num::NonZeroI32;
5+
use std::num::NonZero;
66

77
// We define our own option type so that we can control the variant indices.
88
#[allow(unused)]
@@ -13,7 +13,7 @@ enum Option<T> {
1313
use Option::*;
1414

1515
#[custom_mir(dialect = "runtime", phase = "optimized")]
16-
fn set_discriminant(ptr: &mut Option<NonZeroI32>) {
16+
fn set_discriminant(ptr: &mut Option<NonZero<i32>>) {
1717
mir! {
1818
{
1919
// We set the discriminant to `Some`, which is a NOP since this is the niched variant.
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
use std::num::*;
1+
use std::num::NonZero;
22

33
#[repr(C)]
4-
struct S1(NonZeroI32);
4+
struct S1(NonZero<i32>);
55

66
#[repr(C)]
77
struct S2(i32);
@@ -11,6 +11,6 @@ fn callee(_s: S2) {}
1111
fn main() {
1212
let fnptr: fn(S2) = callee;
1313
let fnptr: fn(S1) = unsafe { std::mem::transmute(fnptr) };
14-
fnptr(S1(NonZeroI32::new(1).unwrap()));
14+
fnptr(S1(NonZero::new(1).unwrap()));
1515
//~^ ERROR: calling a function with argument of type S2 passing data of type S1
1616
}

src/tools/miri/tests/fail/validity/cast_fn_ptr_invalid_callee_ret.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22
#![feature(core_intrinsics, custom_mir)]
33

44
use std::intrinsics::mir::*;
5-
use std::num::NonZeroU32;
5+
use std::num::NonZero;
66
use std::ptr;
77

8-
// This function supposedly returns a NonZeroU32, but actually returns something invalid in a way that
9-
// never materializes a bad NonZeroU32 value: we take a pointer to the return place and cast the pointer
8+
// This function supposedly returns a `NonZero<u32>`, but actually returns something invalid in a way that
9+
// never materializes a bad `NonZero<u32>` value: we take a pointer to the return place and cast the pointer
1010
// type. That way we never get an "invalid value constructed" error inside the function, it can
1111
// only possibly be detected when the return value is passed to the caller.
1212
#[custom_mir(dialect = "runtime", phase = "optimized")]
13-
fn f() -> NonZeroU32 {
13+
fn f() -> NonZero<u32> {
1414
mir! {
1515
{
1616
let tmp = ptr::addr_of_mut!(RET);
@@ -22,7 +22,7 @@ fn f() -> NonZeroU32 {
2222
}
2323

2424
fn main() {
25-
let f: fn() -> u32 = unsafe { std::mem::transmute(f as fn() -> NonZeroU32) };
26-
// There's a NonZeroU32-to-u32 transmute happening here
25+
let f: fn() -> u32 = unsafe { std::mem::transmute(f as fn() -> NonZero<u32>) };
26+
// There's a `NonZero<u32>` to `u32` transmute happening here.
2727
f(); //~ERROR: expected something greater or equal to 1
2828
}

src/tools/miri/tests/fail/validity/cast_fn_ptr_invalid_caller_arg.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,24 @@
22
#![feature(core_intrinsics, custom_mir)]
33

44
use std::intrinsics::mir::*;
5-
use std::num::NonZeroU32;
5+
use std::num::NonZero;
66
use std::ptr;
77

88
fn f(c: u32) {
99
println!("{c}");
1010
}
1111

12-
// Call that function in a bad way, with an invalid NonZeroU32, but without
13-
// ever materializing this as a NonZeroU32 value outside the call itself.
12+
// Call that function in a bad way, with an invalid `NonZero<u32>`, but without
13+
// ever materializing this as a `NonZero<u32>` value outside the call itself.
1414
#[custom_mir(dialect = "runtime", phase = "optimized")]
15-
fn call(f: fn(NonZeroU32)) {
15+
fn call(f: fn(NonZero<u32>)) {
1616
mir! {
1717
let _res: ();
1818
{
1919
let c = 0;
2020
let tmp = ptr::addr_of!(c);
21-
let ptr = tmp as *const NonZeroU32;
22-
// The call site now is a NonZeroU32-to-u32 transmute.
21+
let ptr = tmp as *const NonZero<u32>;
22+
// The call site now is a `NonZero<u32>` to `u32` transmute.
2323
Call(_res = f(*ptr), ReturnTo(retblock), UnwindContinue()) //~ERROR: expected something greater or equal to 1
2424
}
2525
retblock = {
@@ -29,6 +29,6 @@ fn call(f: fn(NonZeroU32)) {
2929
}
3030

3131
fn main() {
32-
let f: fn(NonZeroU32) = unsafe { std::mem::transmute(f as fn(u32)) };
32+
let f: fn(NonZero<u32>) = unsafe { std::mem::transmute(f as fn(u32)) };
3333
call(f);
3434
}
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
//@compile-flags: -Zmiri-num-cpus=1024
22

3-
use std::num::NonZeroUsize;
3+
use std::num::NonZero;
44
use std::thread::available_parallelism;
55

66
fn main() {
7-
assert_eq!(available_parallelism().unwrap(), NonZeroUsize::new(1024).unwrap());
7+
assert_eq!(available_parallelism().unwrap(), NonZero::new(1024).unwrap());
88
}

src/tools/miri/tests/pass/function_calls/abi_compat.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ fn main() {
7070
test_abi_compat(0usize, 0u64);
7171
test_abi_compat(0isize, 0i64);
7272
}
73-
test_abi_compat(42u32, num::NonZeroU32::new(1).unwrap());
73+
test_abi_compat(42u32, num::NonZero::new(1u32).unwrap());
7474
// - `char` and `u32`.
7575
test_abi_compat(42u32, 'x');
7676
// - Reference/pointer types with the same pointee.
@@ -86,9 +86,9 @@ fn main() {
8686
// - Guaranteed null-pointer-optimizations (RFC 3391).
8787
test_abi_compat(&0u32 as *const u32, Some(&0u32));
8888
test_abi_compat(main as fn(), Some(main as fn()));
89-
test_abi_compat(0u32, Some(num::NonZeroU32::new(1).unwrap()));
89+
test_abi_compat(0u32, Some(num::NonZero::new(1u32).unwrap()));
9090
test_abi_compat(&0u32 as *const u32, Some(Wrapper(&0u32)));
91-
test_abi_compat(0u32, Some(Wrapper(num::NonZeroU32::new(1).unwrap())));
91+
test_abi_compat(0u32, Some(Wrapper(num::NonZero::new(1u32).unwrap())));
9292

9393
// These must work for *any* type, since we guarantee that `repr(transparent)` is ABI-compatible
9494
// with the wrapped field.
@@ -102,7 +102,7 @@ fn main() {
102102
test_abi_newtype::<[u32; 2]>();
103103
test_abi_newtype::<[u32; 32]>();
104104
test_abi_newtype::<Option<i32>>();
105-
test_abi_newtype::<Option<num::NonZeroU32>>();
105+
test_abi_newtype::<Option<num::NonZero<u32>>>();
106106

107107
// Extra test for assumptions made by arbitrary-self-dyn-receivers.
108108
// This is interesting since these types are not `repr(transparent)`. So this is not part of our

src/tools/miri/tests/ui.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::ffi::OsString;
2-
use std::num::NonZeroUsize;
2+
use std::num::NonZero;
33
use std::path::{Path, PathBuf};
44
use std::sync::OnceLock;
55
use std::{env, process::Command};
@@ -76,7 +76,7 @@ fn miri_config(target: &str, path: &str, mode: Mode, with_dependencies: bool) ->
7676
edition: Some("2021".into()), // keep in sync with `./miri run`
7777
threads: std::env::var("MIRI_TEST_THREADS")
7878
.ok()
79-
.map(|threads| NonZeroUsize::new(threads.parse().unwrap()).unwrap()),
79+
.map(|threads| NonZero::new(threads.parse().unwrap()).unwrap()),
8080
..Config::rustc(path)
8181
};
8282

tests/ui-fulldeps/stable-mir/check_abi.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ fn check_result(abi: &ArgAbi) {
9999
assert_matches!(layout.variants, VariantsShape::Multiple { .. })
100100
}
101101

102-
/// Check the niche information about: `NonZeroU8`
102+
/// Checks the niche information about `NonZero<u8>`.
103103
fn check_niche(abi: &ArgAbi) {
104104
assert!(abi.ty.kind().is_struct());
105105
assert_matches!(abi.mode, PassMode::Direct { .. });
@@ -150,12 +150,12 @@ fn generate_input(path: &str) -> std::io::Result<()> {
150150
#![feature(c_variadic)]
151151
#![allow(unused_variables)]
152152
153-
use std::num::NonZeroU8;
153+
use std::num::NonZero;
154154
155155
pub fn fn_abi(
156156
ignore: [u8; 0],
157157
primitive: char,
158-
niche: NonZeroU8,
158+
niche: NonZero<u8>,
159159
) -> Result<usize, &'static str> {{
160160
// We only care about the signature.
161161
todo!()

0 commit comments

Comments
 (0)