summaryrefslogtreecommitdiff
path: root/rust/kernel/safety.rs
blob: c1c6bd0fa2cc9271a487870d7e2a2e247c049a85 (plain)
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
// SPDX-License-Identifier: GPL-2.0

//! Safety related APIs.

/// Checks that a precondition of an unsafe function is followed.
///
/// The check is enabled at runtime if debug assertions (`CONFIG_RUST_DEBUG_ASSERTIONS`)
/// are enabled. Otherwise, this macro is a no-op.
///
/// # Examples
///
/// ```no_run
/// use kernel::unsafe_precondition_assert;
///
/// struct RawBuffer<T: Copy, const N: usize> {
///     data: [T; N],
/// }
///
/// impl<T: Copy, const N: usize> RawBuffer<T, N> {
///     /// # Safety
///     ///
///     /// The caller must ensure that `index` is less than `N`.
///     unsafe fn set_unchecked(&mut self, index: usize, value: T) {
///         unsafe_precondition_assert!(
///             index < N,
///             "RawBuffer::set_unchecked() requires index ({index}) < N ({N})"
///         );
///
///         // SAFETY: By the safety requirements of this function, `index` is valid.
///         unsafe {
///             *self.data.get_unchecked_mut(index) = value;
///         }
///     }
/// }
/// ```
///
/// # Panics
///
/// Panics if the expression is evaluated to [`false`] at runtime.
#[macro_export]
macro_rules! unsafe_precondition_assert {
    ($cond:expr $(,)?) => {
        $crate::unsafe_precondition_assert!(@inner $cond, ::core::stringify!($cond))
    };

    ($cond:expr, $($arg:tt)+) => {
        $crate::unsafe_precondition_assert!(@inner $cond, $crate::prelude::fmt!($($arg)+))
    };

    (@inner $cond:expr, $msg:expr) => {
        ::core::debug_assert!($cond, "unsafe precondition violated: {}", $msg)
    };
}