devela/num/niche/
impls.rs

1// devela::num::niche::impls
2//
3//! Implements `BitSized`, `ConstDefault` and `MemPod` for `NonValue*`.
4//
5
6#[cfg(all(feature = "unsafe_layout", not(feature = "safe_mem")))]
7use crate::MemPod;
8#[cfg(feature = "bit")]
9use crate::{BitSized, ByteSized};
10use crate::{
11    ConstDefault, NonExtremeI8, NonExtremeI16, NonExtremeI32, NonExtremeI64, NonExtremeI128,
12    NonExtremeIsize, NonExtremeU8, NonExtremeU16, NonExtremeU32, NonExtremeU64, NonExtremeU128,
13    NonExtremeUsize, paste,
14};
15#[allow(unused, reason = "±unsafe")]
16use crate::{
17    NonValueI8, NonValueI16, NonValueI32, NonValueI64, NonValueI128, NonValueIsize, NonValueU8,
18    NonValueU16, NonValueU32, NonValueU64, NonValueU128, NonValueUsize,
19};
20
21macro_rules! impl_for_non_value {
22    () => {
23        impl_for_non_value![
24            u8, u16, u32, u64, u128, usize,
25            i8, i16, i32, i64, i128, isize,
26        ];
27    };
28    ($($IP:ty),+ $(,)?) => { paste! {
29        $(
30            impl_for_non_value!(@
31                [<NonValue $IP:camel>],
32                [<NonExtreme $IP:camel>],
33                $IP
34                );
35            )+
36    }};
37    (@$nv:ident, $ne:ident, $IP:ty) => {
38
39        // BitSized for NonValue*
40        #[cfg(feature = "bit")]
41        impl<const V: $IP> BitSized<{<$IP>::BYTE_SIZE * 8}> for $nv<V> {}
42
43        // ConstDefault for NonExtreme*
44        impl ConstDefault for $ne {
45            /// # Features
46            /// Makes use of the `unsafe_niche` feature if enabled.
47            const DEFAULT: Self = {
48                #[cfg(any(feature = "safe_num", not(feature = "unsafe_niche")))]
49                if let Some(v) = Self::new(<$IP>::DEFAULT) { v } else { unreachable![] }
50
51                #[cfg(all(not(feature = "safe_num"), feature = "unsafe_niche"))]
52                // SAFETY: the default primitive value is always 0, and their MAX is never 0.
53                unsafe { $ne::new_unchecked(<$IP>::DEFAULT) }
54            };
55        }
56
57        // MemPod for NonValue*
58        #[cfg(feature = "unsafe_layout")]
59        #[cfg(not(any(feature = "safe_mem", feature = "safe_num")))]
60        #[cfg_attr(nightly_doc, doc(cfg(feature = "unsafe_layout")))]
61        #[cfg_attr(nightly_doc, doc(cfg(not(feature = "safe_mem"))))]
62        #[cfg_attr(nightly_doc, doc(cfg(not(feature = "safe_num"))))]
63        unsafe impl<const V: $IP> MemPod for Option<$nv<V>> {}
64    };
65}
66impl_for_non_value![];