1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
//! # `nonzero_macros`
//!
//! A collection of lightweight, `no_std`, dependency-free macros for `LibAFL` and general Rust development.
//!
//! ## Macros
//!
//! - [`nonzero!`](crate::nonzero): A compile-time checked way to create `NonZero*` types. Panics if the value is zero.
//! - [`try_nonzero!`](crate::try_nonzero): A compile-time checked way to create `Option<NonZero*>` types. Returns `None` if the value is zero.
//! - [`nonnull_raw_mut!`](crate::nonnull_raw_mut): A safe wrapper around `&raw mut` that returns a `NonNull` pointer.
/// Zero-cost way to construct `NonZero*` types from [`core::num`] at compile-time.
///
/// This macro ensures that the value is non-zero at compile-time and returns the corresponding `NonZero` type.
/// If the value is zero, it will cause a compile-time panic.
///
/// # Examples
///
/// ```
/// use core::num::NonZeroUsize;
///
/// use nonzero_macros::nonzero;
///
/// const VAL: NonZeroUsize = nonzero!(10);
/// assert_eq!(VAL.get(), 10);
/// ```
///
/// ```compile_fail
/// use nonzero_macros::nonzero;
/// let _ = nonzero!(0); // Panics at compile-time
/// ```
/// Construct `Option<NonZero*>` types from [`core::num`].
///
/// This macro creates an `Option<NonZero*>` from a value.
/// It works both at compile-time (in const contexts) and at runtime.
///
/// # Examples
///
/// ```
/// use core::num::NonZeroU8;
///
/// use nonzero_macros::try_nonzero;
///
/// // Compile-time
/// const VAL: Option<NonZeroU8> = try_nonzero!(5);
/// assert!(VAL.is_some());
///
/// const ZERO: Option<NonZeroU8> = try_nonzero!(0);
/// assert!(ZERO.is_none());
///
/// // Runtime
/// let x = 5;
/// let val = try_nonzero!(x);
/// assert!(val.is_some());
/// ```
/// Get a [`core::ptr::NonNull`] to a global static mut (or similar).
///
/// The same as [`core::ptr::addr_of_mut`] or `&raw mut`, but wrapped in said [`NonNull`](core::ptr::NonNull).
///
/// # Safety
///
/// The expression must be valid for `&raw mut`. The resulting pointer is guaranteed to be non-null
/// (unless the address of the variable is actually null, which shouldn't happen in safe Rust contexts for statics).
///
/// # Examples
///
/// ```
/// use nonzero_macros::nonnull_raw_mut;
///
/// static mut MY_STATIC: u32 = 0;
///
/// unsafe {
/// let ptr = nonnull_raw_mut!(MY_STATIC);
/// *ptr.as_ptr() = 42;
/// assert_eq!(*ptr.as_ptr(), 42);
/// }
/// ```