1use crate::error::{ParseIntError, TryFromIntError};
5
6macro_rules! int_fmt {
8 ($nv:ident, $prim:ident, $($Trait:ident),+ $(,)?) => {
9 $(
10 impl<const N: $prim> core::fmt::$Trait for $nv<N> {
11 #[inline]
12 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
13 core::fmt::$Trait::fmt(&self.get(), f)
14 }
15 }
16 )+
17 };
18}
19
20macro_rules! niche_int {
21 (@common $nv:ident, $nonzero:ident, $prim:ident, $nonmax:ident, $nonmin:ident) => {
22 #[doc = concat!("An [`", stringify!($prim), "`] that is known not to equal the const value `N`.")]
23 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
27 #[repr(transparent)]
28 pub struct $nv<const N: $prim>(core::num::$nonzero);
29
30 impl<const N: $prim> $nv<N> {
31 #[inline]
33 pub const fn new(value: $prim) -> Option<Self> {
34 match core::num::$nonzero::new(value ^ N) {
35 None => None,
36 Some(inner) => Some(Self(inner)),
37 }
38 }
39
40 #[inline]
46 pub const unsafe fn new_unchecked(value: $prim) -> Self {
47 Self(unsafe { core::num::$nonzero::new_unchecked(value ^ N) })
49 }
50
51 #[inline]
53 pub const fn get(&self) -> $prim {
54 self.0.get() ^ N
55 }
56 }
57
58 impl<const N: $prim> core::cmp::Ord for $nv<N> {
59 #[inline]
60 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
61 self.get().cmp(&other.get())
62 }
63 }
64 impl<const N: $prim> core::cmp::PartialOrd for $nv<N> {
65 #[inline]
66 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
67 Some(self.cmp(other))
68 }
69 }
70
71 impl<const N: $prim> From<$nv<N>> for $prim {
72 #[inline]
73 fn from(value: $nv<N>) -> Self {
74 value.get()
75 }
76 }
77
78 impl<const N: $prim> core::convert::TryFrom<$prim> for $nv<N> {
79 type Error = TryFromIntError;
80 #[inline]
81 fn try_from(value: $prim) -> Result<Self, Self::Error> {
82 Self::new(value).ok_or(TryFromIntError(()))
83 }
84 }
85
86 impl<const N: $prim> core::str::FromStr for $nv<N> {
87 type Err = ParseIntError;
88 #[inline]
89 fn from_str(value: &str) -> Result<Self, Self::Err> {
90 Self::new(<$prim as core::str::FromStr>::from_str(value)?).ok_or(ParseIntError(()))
91 }
92 }
93
94 int_fmt!($nv, $prim, Debug, Display, Binary, Octal, LowerHex, UpperHex);
95
96 #[cfg(feature = "serde")]
97 impl<const N: $prim> serde::Serialize for $nv<N> {
98 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
99 self.get().serialize(serializer)
100 }
101 }
102 #[cfg(feature = "serde")]
103 impl<'de, const N: $prim> serde::Deserialize<'de> for $nv<N> {
104 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
105 let value = <$prim as serde::Deserialize>::deserialize(deserializer)?;
106 Self::new(value).ok_or_else(|| serde::de::Error::custom("value is forbidden by niche type"))
107 }
108 }
109
110 #[doc = concat!("A [`", stringify!($prim), "`] that is known not to equal its maximum. Drop-in for `nonmax::", stringify!($nonmax), "`.")]
111 pub type $nonmax = $nv<{ $prim::MAX }>;
112
113 #[doc = concat!("A [`", stringify!($prim), "`] that is known not to equal its minimum.")]
114 pub type $nonmin = $nv<{ $prim::MIN }>;
115
116 impl $nv<{ $prim::MAX }> {
119 pub const ZERO: Self = unsafe { Self::new_unchecked(0) };
121 pub const ONE: Self = unsafe { Self::new_unchecked(1) };
123 pub const MAX: Self = unsafe { Self::new_unchecked($prim::MAX - 1) };
125 }
126
127 impl Default for $nv<{ $prim::MAX }> {
128 #[inline]
129 fn default() -> Self {
130 unsafe { Self::new_unchecked(0) }
132 }
133 }
134
135 impl core::ops::BitAnd for $nv<{ $prim::MAX }> {
138 type Output = Self;
139 #[inline]
140 fn bitand(self, rhs: Self) -> Self {
141 unsafe { Self::new_unchecked(self.get() & rhs.get()) }
143 }
144 }
145 impl core::ops::BitAndAssign for $nv<{ $prim::MAX }> {
146 #[inline]
147 fn bitand_assign(&mut self, rhs: Self) {
148 *self = *self & rhs;
149 }
150 }
151
152 const _: () = {
153 assert!(core::mem::size_of::<$nonmax>() == core::mem::size_of::<$prim>());
154 assert!(core::mem::size_of::<Option<$nonmax>>() == core::mem::size_of::<$prim>());
155 };
156 };
157
158 (signed $nv:ident, $nonzero:ident, $prim:ident, $nonmax:ident, $nonmin:ident) => {
159 niche_int!(@common $nv, $nonzero, $prim, $nonmax, $nonmin);
160 };
161
162 (unsigned $nv:ident, $nonzero:ident, $prim:ident, $nonmax:ident, $nonmin:ident) => {
163 niche_int!(@common $nv, $nonzero, $prim, $nonmax, $nonmin);
164
165 impl core::ops::BitAnd<$prim> for $nv<{ $prim::MAX }> {
168 type Output = Self;
169 #[inline]
170 fn bitand(self, rhs: $prim) -> Self {
171 unsafe { Self::new_unchecked(self.get() & rhs) }
173 }
174 }
175 impl core::ops::BitAnd<$nv<{ $prim::MAX }>> for $prim {
176 type Output = $nv<{ $prim::MAX }>;
177 #[inline]
178 fn bitand(self, rhs: $nv<{ $prim::MAX }>) -> Self::Output {
179 unsafe { <$nv<{ $prim::MAX }>>::new_unchecked(self & rhs.get()) }
181 }
182 }
183 impl core::ops::BitAndAssign<$prim> for $nv<{ $prim::MAX }> {
184 #[inline]
185 fn bitand_assign(&mut self, rhs: $prim) {
186 *self = *self & rhs;
187 }
188 }
189 impl core::ops::BitAndAssign<$nv<{ $prim::MAX }>> for $prim {
190 #[inline]
191 fn bitand_assign(&mut self, rhs: $nv<{ $prim::MAX }>) {
192 *self = *self & rhs.get();
193 }
194 }
195
196 impl From<core::num::$nonzero> for $nv<0> {
200 #[inline]
201 fn from(value: core::num::$nonzero) -> Self {
202 Self(value)
205 }
206 }
207 impl From<$nv<0>> for core::num::$nonzero {
208 #[inline]
209 fn from(value: $nv<0>) -> Self {
210 value.0
211 }
212 }
213 };
214}
215
216niche_int!(signed NonValueI8, NonZeroI8, i8, NonMaxI8, NonMinI8);
217niche_int!(signed NonValueI16, NonZeroI16, i16, NonMaxI16, NonMinI16);
218niche_int!(signed NonValueI32, NonZeroI32, i32, NonMaxI32, NonMinI32);
219niche_int!(signed NonValueI64, NonZeroI64, i64, NonMaxI64, NonMinI64);
220niche_int!(signed NonValueI128, NonZeroI128, i128, NonMaxI128, NonMinI128);
221niche_int!(signed NonValueIsize, NonZeroIsize, isize, NonMaxIsize, NonMinIsize);
222
223niche_int!(unsigned NonValueU8, NonZeroU8, u8, NonMaxU8, NonMinU8);
224niche_int!(unsigned NonValueU16, NonZeroU16, u16, NonMaxU16, NonMinU16);
225niche_int!(unsigned NonValueU32, NonZeroU32, u32, NonMaxU32, NonMinU32);
226niche_int!(unsigned NonValueU64, NonZeroU64, u64, NonMaxU64, NonMinU64);
227niche_int!(unsigned NonValueU128, NonZeroU128, u128, NonMaxU128, NonMinU128);
228niche_int!(unsigned NonValueUsize, NonZeroUsize, usize, NonMaxUsize, NonMinUsize);
229
230macro_rules! widen_niche {
232 ($small:ty, $large:ty) => {
233 impl From<$small> for $large {
234 #[inline]
235 fn from(small: $small) -> Self {
236 unsafe { Self::new_unchecked(small.get().into()) }
239 }
240 }
241 };
242}
243macro_rules! widen_prim {
253 ($small:ty, $large:ty) => {
254 const _: () = assert!(
255 core::mem::size_of::<$small>() < core::mem::size_of::<$large>(),
256 "widen_prim! requires the source to be strictly narrower than the destination",
257 );
258 impl From<$small> for $large {
259 #[inline]
260 fn from(small: $small) -> Self {
261 unsafe { Self::new_unchecked(small.into()) }
265 }
266 }
267 };
268}
269
270widen_niche!(NonMaxU8, NonMaxU16);
272widen_niche!(NonMaxU8, NonMaxU32);
273widen_niche!(NonMaxU8, NonMaxU64);
274widen_niche!(NonMaxU8, NonMaxU128);
275widen_niche!(NonMaxU8, NonMaxUsize);
276widen_niche!(NonMaxU16, NonMaxU32);
277widen_niche!(NonMaxU16, NonMaxU64);
278widen_niche!(NonMaxU16, NonMaxU128);
279widen_niche!(NonMaxU16, NonMaxUsize);
280widen_niche!(NonMaxU32, NonMaxU64);
281widen_niche!(NonMaxU32, NonMaxU128);
282widen_niche!(NonMaxU64, NonMaxU128);
283
284widen_niche!(NonMaxI8, NonMaxI16);
286widen_niche!(NonMaxI8, NonMaxI32);
287widen_niche!(NonMaxI8, NonMaxI64);
288widen_niche!(NonMaxI8, NonMaxI128);
289widen_niche!(NonMaxI8, NonMaxIsize);
290widen_niche!(NonMaxI16, NonMaxI32);
291widen_niche!(NonMaxI16, NonMaxI64);
292widen_niche!(NonMaxI16, NonMaxI128);
293widen_niche!(NonMaxI16, NonMaxIsize);
294widen_niche!(NonMaxI32, NonMaxI64);
295widen_niche!(NonMaxI32, NonMaxI128);
296widen_niche!(NonMaxI64, NonMaxI128);
297
298widen_niche!(NonMaxU8, NonMaxI16);
300widen_niche!(NonMaxU8, NonMaxI32);
301widen_niche!(NonMaxU8, NonMaxI64);
302widen_niche!(NonMaxU8, NonMaxI128);
303widen_niche!(NonMaxU8, NonMaxIsize);
304widen_niche!(NonMaxU16, NonMaxI32);
305widen_niche!(NonMaxU16, NonMaxI64);
306widen_niche!(NonMaxU16, NonMaxI128);
307widen_niche!(NonMaxU32, NonMaxI64);
308widen_niche!(NonMaxU32, NonMaxI128);
309widen_niche!(NonMaxU64, NonMaxI128);
310
311widen_prim!(u8, NonMaxU16);
313widen_prim!(u8, NonMaxU32);
314widen_prim!(u8, NonMaxU64);
315widen_prim!(u8, NonMaxU128);
316widen_prim!(u8, NonMaxUsize);
317widen_prim!(u16, NonMaxU32);
318widen_prim!(u16, NonMaxU64);
319widen_prim!(u16, NonMaxU128);
320#[cfg(not(target_pointer_width = "16"))]
324widen_prim!(u16, NonMaxUsize);
325widen_prim!(u32, NonMaxU64);
326widen_prim!(u32, NonMaxU128);
327widen_prim!(u64, NonMaxU128);
328
329widen_prim!(i8, NonMaxI16);
331widen_prim!(i8, NonMaxI32);
332widen_prim!(i8, NonMaxI64);
333widen_prim!(i8, NonMaxI128);
334widen_prim!(i8, NonMaxIsize);
335widen_prim!(i16, NonMaxI32);
336widen_prim!(i16, NonMaxI64);
337widen_prim!(i16, NonMaxI128);
338#[cfg(not(target_pointer_width = "16"))]
342widen_prim!(i16, NonMaxIsize);
343widen_prim!(i32, NonMaxI64);
344widen_prim!(i32, NonMaxI128);
345widen_prim!(i64, NonMaxI128);
346
347widen_prim!(u8, NonMaxI16);
349widen_prim!(u8, NonMaxI32);
350widen_prim!(u8, NonMaxI64);
351widen_prim!(u8, NonMaxI128);
352widen_prim!(u8, NonMaxIsize);
353widen_prim!(u16, NonMaxI32);
354widen_prim!(u16, NonMaxI64);
355widen_prim!(u16, NonMaxI128);
356widen_prim!(u32, NonMaxI64);
357widen_prim!(u32, NonMaxI128);
358widen_prim!(u64, NonMaxI128);
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363 use core::mem::size_of;
364
365 #[test]
366 fn generic_forbidden_value() {
367 let v = NonValueU8::<7>::new(3).unwrap();
369 assert_eq!(v.get(), 3);
370 assert!(NonValueU8::<7>::new(7).is_none());
371 assert_eq!(NonValueU8::<7>::new(0).unwrap().get(), 0);
372 assert_eq!(NonValueU8::<7>::new(255).unwrap().get(), 255);
373 }
374
375 #[test]
376 fn exhaustive_u8_all_forbidden() {
377 macro_rules! check_n {
379 ($n:literal) => {{
380 for value in 0..=u8::MAX {
381 match NonValueU8::<$n>::new(value) {
382 None => assert_eq!(value, $n),
383 Some(v) => {
384 assert_ne!(value, $n);
385 assert_eq!(v.get(), value);
386 }
387 }
388 }
389 }};
390 }
391 check_n!(0);
392 check_n!(1);
393 check_n!(42);
394 check_n!(128);
395 check_n!(254);
396 check_n!(255);
397 }
398
399 #[test]
400 fn exhaustive_i8_all_forbidden() {
401 macro_rules! check_n {
402 ($n:literal) => {{
403 for value in i8::MIN..=i8::MAX {
404 match NonValueI8::<$n>::new(value) {
405 None => assert_eq!(value, $n),
406 Some(v) => assert_eq!(v.get(), value),
407 }
408 }
409 }};
410 }
411 check_n!(-128);
412 check_n!(-1);
413 check_n!(0);
414 check_n!(1);
415 check_n!(127);
416 }
417
418 #[test]
419 fn nonmax_nonmin_aliases() {
420 assert!(NonMaxU8::new(u8::MAX).is_none());
421 assert_eq!(NonMaxU8::new(0).unwrap().get(), 0);
422 assert!(NonMinU8::new(u8::MIN).is_none());
423 assert_eq!(NonMinU8::new(255).unwrap().get(), 255);
424
425 assert!(NonMaxI8::new(i8::MAX).is_none());
426 assert!(NonMinI8::new(i8::MIN).is_none());
427 assert_eq!(NonMinI8::new(-127).unwrap().get(), -127);
428 }
429
430 #[test]
431 fn nonmax_constants_and_default() {
432 assert_eq!(NonMaxU8::ZERO.get(), 0);
433 assert_eq!(NonMaxU8::ONE.get(), 1);
434 assert_eq!(NonMaxU8::MAX.get(), 254);
435 assert_eq!(NonMaxU8::default().get(), 0);
436 assert_eq!(NonMaxI16::MAX.get(), i16::MAX - 1);
437 }
438
439 #[test]
440 fn ordering_is_by_value_not_bits() {
441 let zero = NonMaxU8::new(0).unwrap();
442 let one = NonMaxU8::new(1).unwrap();
443 let big = NonMaxU8::new(200).unwrap();
444 assert!(zero < one);
445 assert!(one < big);
446 assert!(big > one);
448 }
449
450 #[test]
451 fn bitand_unsigned_matches_primitive() {
452 for left in 0..=u8::MAX {
453 for right in 0..=u8::MAX {
454 let vanilla = left & right;
455 if let (Some(l), Some(r)) = (NonMaxU8::new(left), NonMaxU8::new(right)) {
456 assert_eq!((l & r).get(), vanilla);
457 }
458 if let Some(l) = NonMaxU8::new(left) {
459 assert_eq!((l & right).get(), vanilla); }
461 if let Some(r) = NonMaxU8::new(right) {
462 assert_eq!((left & r).get(), vanilla); }
464 }
465 }
466 }
467
468 #[test]
469 fn bitand_signed_closed() {
470 for left in i8::MIN..=i8::MAX {
471 for right in i8::MIN..=i8::MAX {
472 if let (Some(l), Some(r)) = (NonMaxI8::new(left), NonMaxI8::new(right)) {
473 assert_eq!((l & r).get(), left & right);
474 }
475 }
476 }
477 }
478
479 #[test]
480 fn conversions() {
481 use core::convert::TryFrom;
482 let v = NonValueU8::<7>::try_from(3).unwrap();
483 assert_eq!(u8::from(v), 3);
484 NonValueU8::<7>::try_from(7).unwrap_err();
485
486 let small = NonMaxU8::new(200).unwrap();
488 let large: NonMaxU32 = small.into();
489 assert_eq!(large.get(), 200);
490 let from_prim: NonMaxU16 = 200u8.into();
491 assert_eq!(from_prim.get(), 200);
492 }
493
494 #[test]
495 fn nonzero_interop() {
496 use core::num::NonZeroU16;
497 let nz = NonZeroU16::new(42).unwrap();
498 let nm: NonMinU16 = nz.into();
500 assert_eq!(nm.get(), 42);
501 let back: NonZeroU16 = nm.into();
502 assert_eq!(back.get(), 42);
503 assert!(NonMinU16::new(0).is_none());
504 }
505
506 #[test]
507 fn parse() {
508 let v: NonValueU8<7> = "3".parse().unwrap();
509 assert_eq!(v.get(), 3);
510 "7".parse::<NonValueU8<7>>().unwrap_err();
511 "300".parse::<NonMaxU8>().unwrap_err();
512 }
513
514 #[test]
515 #[cfg(feature = "std")] fn fmt_forwards_to_value() {
517 let v = NonValueU8::<7>::new(200).unwrap();
518 assert_eq!(format!("{v}"), "200");
519 assert_eq!(format!("{v:?}"), "200");
520 assert_eq!(format!("{v:b}"), format!("{:b}", 200u8));
521 assert_eq!(format!("{v:x}"), format!("{:x}", 200u8));
522 }
523
524 #[test]
525 fn sizes_niche_optimized() {
526 assert_eq!(size_of::<Option<NonValueU8<7>>>(), size_of::<u8>());
527 assert_eq!(size_of::<Option<NonMaxU32>>(), size_of::<u32>());
528 assert_eq!(size_of::<Option<NonMinI64>>(), size_of::<i64>());
529 assert_eq!(size_of::<Option<NonValueUsize<3>>>(), size_of::<usize>());
530 }
531
532 #[test]
533 fn const_context() {
534 const V: NonValueU8<7> = match NonValueU8::<7>::new(9) {
535 Some(v) => v,
536 None => panic!(),
537 };
538 const G: u8 = V.get();
539 assert_eq!(G, 9);
540 }
541
542 #[test]
543 #[cfg(feature = "serde")]
544 fn serde_roundtrip() {
545 let v = NonValueU8::<7>::new(3).unwrap();
546 let bytes = bincode::serialize(&v).unwrap();
547 let back: NonValueU8<7> = bincode::deserialize(&bytes).unwrap();
548 assert_eq!(v, back);
549 let bad = bincode::serialize(&7u8).unwrap();
551 assert!(bincode::deserialize::<NonValueU8<7>>(&bad).is_err());
552 }
553}