@@ -8,6 +8,55 @@ use super::from_str_radix;
88use super :: { IntErrorKind , ParseIntError } ;
99use crate :: intrinsics;
1010
11+ /// Generic type alias for the non-zero type that corresponds to each integer
12+ /// primitive.
13+ ///
14+ /// This type alias simply provides an alternative spelling of the various
15+ /// `NonZero` structs found in [`core::num`]. For example `NonZero<u16>` refers
16+ /// to the struct [`core::num::NonZeroU16`].
17+ ///
18+ /// **Note:** this is *not* intended for writing code that is generic over
19+ /// multiple types of non-zero integers. The relevant trait bound you would need
20+ /// for that is not exposed. The only thing this is, is an alternative spelling.
21+ ///
22+ /// # Example
23+ ///
24+ /// Where this comes in handy is if the primitive types themselves are being
25+ /// used via a type alias, such as [`std::os::raw::c_char`][c_char]. The
26+ /// `c_char` type refers to either `i8` or `u8` depending on whether the
27+ /// platform's C character type is signed or unsigned, and without `NonZero<N>`
28+ /// there is not a straightforward way to name either `NonZeroI8` or `NonZeroU8`
29+ /// depending on which one a non-zero `c_char` corresponds to.
30+ ///
31+ /// [c_char]: ../../std/os/raw/type.c_char.html
32+ ///
33+ /// ```
34+ /// #![feature(nonzero_generic_type_alias)]
35+ ///
36+ /// use std::num::NonZero;
37+ /// use std::os::raw::c_char;
38+ ///
39+ /// // A separator that we're planning to use with nul-terminated C strings,
40+ /// // where \0 would be nonsensical.
41+ /// pub struct Separator {
42+ /// ch: NonZero<c_char>,
43+ /// }
44+ ///
45+ /// impl Separator {
46+ /// pub fn new(ch: c_char) -> Option<Self> {
47+ /// NonZero::<c_char>::new(ch).map(|ch| Separator { ch })
48+ /// }
49+ /// }
50+ /// ```
51+ #[ unstable( feature = "nonzero_generic_type_alias" , issue = "82363" ) ]
52+ pub type NonZero < N > = <N as IntegerPrimitive >:: NonZero ;
53+
54+ // Not exposed at any publicly accessible path, only via NonZero<N>.
55+ #[ unstable( feature = "nonzero_implementation_detail" , issue = "none" ) ]
56+ pub trait IntegerPrimitive {
57+ type NonZero ;
58+ }
59+
1160macro_rules! impl_nonzero_fmt {
1261 ( #[ $stability: meta] ( $( $Trait: ident ) ,+ ) for $Ty: ident ) => {
1362 $(
@@ -41,6 +90,11 @@ macro_rules! nonzero_integers {
4190 #[ rustc_nonnull_optimization_guaranteed]
4291 pub struct $Ty( $Int) ;
4392
93+ #[ unstable( feature = "nonzero_implementation_detail" , issue = "none" ) ]
94+ impl IntegerPrimitive for $Int {
95+ type NonZero = $Ty;
96+ }
97+
4498 impl $Ty {
4599 /// Creates a non-zero without checking whether the value is non-zero.
46100 /// This results in undefined behaviour if the value is zero.
0 commit comments