assert_unchecked/
lib.rs

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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
//! Unsafe assertions that allow for optimizations in release mode. All of these
//! assertions if incorrect will invoke *undefined behavior* (UB) when
//! `debug_assertions` are disabled, so all usage of these macros must ensure
//! that they will truly never fail.
#![no_std]

/// Asserts that a boolean expression is `true` at runtime.
///
/// In builds with `debug-assertions` enabled, this will function equivalent to
/// [`assert`]. However, in an optimized build without `debug_assertions`
/// enabled, this assertion serves as an optimization hint; the boolean
/// expression itself will likely not appear in the generated code, but instead
/// will be assumed in a way that allows for optimizing the surrounding code.
///
/// # Safety
///
/// In release mode, the assertion failing is completely *undefined behavior*
/// (UB). Since the compiler assumes that all UB must never happen, it may use
/// the assumption that this assertion is true to optimize other sections of the
/// code.
///
/// If this assumption turns out to be wrong, i.e. the assertion can fail in
/// practice, the compiler will apply the wrong optimization strategy, and
/// may sometimes even corrupt seemingly unrelated code, causing
/// difficult-to-debug problems.
///
/// Use this function only when you can prove that the assertion will never be
/// false. Otherwise, consider just using [`assert`], or if assertions are
/// undesired in optimized code, use [`debug_assert`].
/// # Example
///
/// ```
/// use assert_unchecked::assert_unchecked;
/// fn copy(from_arr: &[u8], to_arr: &mut [u8]) {
///     assert_eq!(from_arr.len(), to_arr.len());
///     for i in 0..to_arr.len() {
///         // SAFETY: bounds of to_arr is checked outside of loop
///         // Without this line, the compiler isn't smart enough to remove the bounds check
///         unsafe { assert_unchecked!(i <= to_arr.len()) };
///         to_arr[i] = from_arr[i];
///     }
/// }
/// ```
#[macro_export]
macro_rules! assert_unchecked {
    ($cond:expr) => (assert_unchecked!($cond,));
    ($expr:expr, $($arg:tt)*) => ({
        #[cfg(debug_assertions)]
        {
            unsafe fn __needs_unsafe(){}
            __needs_unsafe();
            assert!($expr, $($arg)*);
        }
        #[cfg(not(debug_assertions))]
        {
            if !($expr) { core::hint::unreachable_unchecked() }
        }
    })
}

/// Asserts that two expressions are equal to each other (using [`PartialEq`]).
///
/// In builds with `debug-assertions` enabled, this will function equivalent to
/// [`assert_eq`]. However, in an optimized build without `debug_assertions`
/// enabled, this assertion serves as an optimization hint; the equality check
/// itself will likely not appear in the generated code, but instead will be
/// assumed in a way that allows for optimizing the surrounding code.
///
/// # Safety
///
/// In release mode, the assertion failing is completely *undefined behavior*
/// (UB). Since the compiler assumes that all UB must never happen, it may use
/// the assumption that this assertion is true to optimize other sections of the
/// code.
///
/// If this assumption turns out to be wrong, i.e. the assertion can fail in
/// practice, the compiler will apply the wrong optimization strategy, and
/// may sometimes even corrupt seemingly unrelated code, causing
/// difficult-to-debug problems.
///
/// Use this function only when you can prove that the assertion will never be
/// false. Otherwise, consider just using [`assert_eq`], or if assertions are
/// undesired in optimized code, use [`debug_assert_eq`].
///
/// # Example
///
/// ```
/// use assert_unchecked::assert_eq_unchecked;
/// fn get_last(len: usize) -> usize {
///     if len == 0 {
///         return 0;
///     }
///     let mut v = vec![0];
///     for i in 1..len {
///         v.push(i)
///     }
///     // SAFETY: `len` elements have been added to v at this point
///     // Without this line, the compiler isn't smart enough to remove the bounds check
///     unsafe { assert_eq_unchecked!(len, v.len()) };
///     v[len - 1]
/// }
/// ```
#[macro_export]
macro_rules! assert_eq_unchecked {
    ($left:expr, $right:expr) => (assert_eq_unchecked!($left, $right,));
    ($left:expr, $right:expr, $($arg:tt)*) => ({
        #[cfg(debug_assertions)]
        {
            unsafe fn __needs_unsafe(){}
            __needs_unsafe();
            assert_eq!($left, $right, $($arg)*);
        }
        #[cfg(not(debug_assertions))]
        {
            if !($left == $right) {
                core::hint::unreachable_unchecked()
            }
        }
    })
}

/// Asserts that two expressions are not equal to each other (using
/// [`PartialEq`]).
///
/// In builds with `debug-assertions` enabled, this will function equivalent to
/// [`assert_ne`]. However, in an optimized build without `debug_assertions`
/// enabled, this assertion serves as an optimization hint; the inequality check
/// itself will likely not appear in the generated code, but instead will be
/// assumed in a way that allows for optimizing the surrounding code.
///
/// # Safety
///
/// In release mode, the assertion failing is completely *undefined behavior*
/// (UB). Since the compiler assumes that all UB must never happen, it may use
/// the assumption that this assertion is true to optimize other sections of the
/// code.
///
/// If this assumption turns out to be wrong, i.e. the assertion can fail in
/// practice, the compiler will apply the wrong optimization strategy, and
/// may sometimes even corrupt seemingly unrelated code, causing
/// difficult-to-debug problems.
///
/// Use this function only when you can prove that the assertion will never be
/// false. Otherwise, consider just using [`assert_ne`], or if assertions are
/// undesired in optimized code, use [`debug_assert_ne`].
///
/// # Example
///
/// ```
/// use assert_unchecked::{assert_unchecked, assert_ne_unchecked};
/// // Modifies `a[0]` and `a[delta]`, and then returns `a[0]`.
/// // delta must be non-zero and delta < a.len().
/// // This also means that all bounds checks can be removed.
/// unsafe fn modify_start_and_delta(a: &mut [u8], delta: usize) -> u8 {
///     // SAFETY: requirements are invariants of the unsafe function.
///     assert_unchecked!(delta < a.len());
///     // With this assertion, we know that a[delta] does not modify a[0],
///     // which means the function can optimize the return value to always be 0.
///     assert_ne_unchecked!(delta, 0);
///     a[0] = 0;
///     a[delta] = 1;
///     a[0]
/// }
/// ```
#[macro_export]
macro_rules! assert_ne_unchecked {
    ($left:expr, $right:expr) => (assert_ne_unchecked!($left, $right,));
    ($left:expr, $right:expr, $($arg:tt)*) => ({
        #[cfg(debug_assertions)]
        {
            unsafe fn __needs_unsafe(){}
            __needs_unsafe();
            assert_ne!($left, $right, $($arg)*);
        }
        #[cfg(not(debug_assertions))]
        {
            if $left == $right {
                core::hint::unreachable_unchecked()
            }
        }
    })
}

/// Equivalent to the [`unreachable!`] macro in builds with `debug_assertions`
/// on, and otherwise calls [`core::hint::unreachable_unchecked`].
///
/// # Safety
///
/// In release mode, reaching this function is completely *undefined behavior*
/// (UB). For more details, see the documentation for [`unreachable_unchecked`].
///
/// Use this function only when you can prove that the code will never call it.
/// Otherwise, consider using the [`unreachable!`] macro, which does not allow
/// optimizations but will panic when executed.
///
/// # Example
///
/// ```
/// use assert_unchecked::unreachable_unchecked;
/// fn div_1(a: u32, b: u32) -> u32 {
///     // `b.saturating_add(1)` is always positive (not zero),
///     // hence `checked_div` will never return `None`.
///     // Therefore, the else branch is unreachable.
///     a.checked_div(b.saturating_add(1))
///         .unwrap_or_else(|| unsafe { unreachable_unchecked!("division by zero isn't possible") })
/// }
///
/// assert_eq!(div_1(7, 0), 7);
/// assert_eq!(div_1(9, 1), 4);
/// assert_eq!(div_1(11, u32::MAX), 0);
/// ```
#[macro_export]
macro_rules! unreachable_unchecked {
    ($($arg:tt)*) => ({
        #[cfg(debug_assertions)]
        {
            unsafe fn __needs_unsafe(){}
            __needs_unsafe();
            unreachable!($($arg)*);
        }
        #[cfg(not(debug_assertions))]
        {
            core::hint::unreachable_unchecked()
        }
    })
}

#[cfg(test)]
mod debug_assertion_tests {
    /// For tests that panic, we only test them when debug_assertions are on,
    /// as otherwise we'd be invoking UB.

    // Ensures that the expression isn't emplaced twice
    #[derive(Eq, PartialEq, Debug)]
    struct NoCopy(usize);

    #[test]
    fn test_assert_success() {
        unsafe {
            assert_unchecked!(NoCopy(0) == NoCopy(0));
            assert_unchecked!(NoCopy(1) == NoCopy(1),);
            assert_unchecked!(NoCopy(2) == NoCopy(2), "message won't appear");
            assert_unchecked!(NoCopy(3) == NoCopy(3), "{} won't {}", "message", "appear");
        }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "assertion failed: NoCopy(0) == NoCopy(1)")]
    fn test_assert_fail_no_message() {
        unsafe { assert_unchecked!(NoCopy(0) == NoCopy(1)) }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "assertion message")]
    fn test_assert_fail_message() {
        unsafe { assert_unchecked!(NoCopy(0) == NoCopy(1), "assertion message") }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "assertion message")]
    fn test_assert_fail_message_format() {
        unsafe { assert_unchecked!(NoCopy(0) == NoCopy(1), "assertion {}", "message") }
    }

    #[test]
    fn test_assert_eq_success() {
        unsafe {
            assert_eq_unchecked!(NoCopy(0), NoCopy(0));
            assert_eq_unchecked!(NoCopy(1), NoCopy(1),);
            assert_eq_unchecked!(NoCopy(2), NoCopy(2), "message won't appear");
            assert_eq_unchecked!(NoCopy(3), NoCopy(3), "{} won't {}", "message", "appear");
        }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "assertion failed: `(left == right)`")]
    fn test_assert_eq_fail_no_message() {
        unsafe { assert_eq_unchecked!(NoCopy(0), NoCopy(1)) }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "assertion message")]
    fn test_assert_eq_fail_message() {
        unsafe { assert_eq_unchecked!(NoCopy(0), NoCopy(1), "assertion message") }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "assertion message")]
    fn test_assert_eq_fail_message_format() {
        unsafe { assert_eq_unchecked!(NoCopy(0), NoCopy(1), "assertion {}", "message") }
    }

    #[test]
    fn test_assert_ne_success() {
        unsafe {
            assert_ne_unchecked!(NoCopy(0), NoCopy(1));
            assert_ne_unchecked!(NoCopy(1), NoCopy(2),);
            assert_ne_unchecked!(NoCopy(2), NoCopy(3), "message won't appear");
            assert_ne_unchecked!(NoCopy(3), NoCopy(4), "{} won't {}", "message", "appear");
        }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "assertion failed: `(left != right)`")]
    fn test_assert_ne_fail_no_message() {
        unsafe { assert_ne_unchecked!(NoCopy(0), NoCopy(0)) }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "assertion message")]
    fn test_assert_ne_fail_message() {
        unsafe { assert_ne_unchecked!(NoCopy(0), NoCopy(0), "assertion message") }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "assertion message")]
    fn test_assert_ne_fail_message_format() {
        unsafe { assert_ne_unchecked!(NoCopy(0), NoCopy(0), "assertion {}", "message") }
    }

    #[test]
    fn test_unreachable_unreachable() {
        match Some(0) {
            Some(_) => {}
            // SAFETY: this is clearly unreachable
            None => unsafe { unreachable_unchecked!() },
        }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "internal error: entered unreachable code")]
    fn test_unreachable_no_message() {
        unsafe { unreachable_unchecked!() }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "assertion message")]
    fn test_unreachable_message() {
        unsafe { unreachable_unchecked!("assertion message") }
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "assertion message")]
    fn test_unreachable_message_format() {
        unsafe { unreachable_unchecked!("assertion {}", "message") }
    }
}