kernel/utilities/
helpers.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Helper functions and macros.
6//!
7//! These are various utility functions and macros that are useful throughout
8//! the Tock kernel and are provided here for convenience.
9//!
10//! The macros are exported through the top level of the `kernel` crate.
11
12/// Create an object with the given capabilities.
13///
14/// ```
15/// # use kernel::capabilities::{ProcessManagementCapability, MemoryAllocationCapability};
16/// # use kernel::create_capability;
17/// let process_mgmt_cap = create_capability!(ProcessManagementCapability);
18/// let unified_cap = create_capability!(ProcessManagementCapability, MemoryAllocationCapability);
19/// ```
20///
21/// This helper macro cannot be called from `#![forbid(unsafe_code)]` crates,
22/// and is used by trusted code to generate a capability that it can either use
23/// or pass to another module.
24///
25/// # Safety
26///
27/// This macro can only be used in a context that is allowed to use
28/// `unsafe`. Specifically, an internal `allow(unsafe_code)` directive
29/// will conflict with any `forbid(unsafe_code)` at the crate or block
30/// level.
31///
32/// ```compile_fail
33/// # use kernel::capabilities::ProcessManagementCapability;
34/// # use kernel::create_capability;
35/// #[forbid(unsafe_code)]
36/// fn untrusted_fn() {
37///     let process_mgmt_cap = create_capability!(ProcessManagementCapability);
38/// }
39/// ```
40#[macro_export]
41macro_rules! create_capability {
42    ($($T:ty),+) => {{
43        #[allow(unsafe_code)]
44        struct Cap(());
45        $(
46            unsafe impl $T for Cap {}
47        )*
48        Cap(())
49    }};
50}
51
52/// Count the number of passed expressions.
53///
54/// Useful for constructing variable sized arrays in other macros.
55/// Taken from the Little Book of Rust Macros.
56///
57/// ```ignore
58/// use kernel:count_expressions;
59///
60/// let count: usize = count_expressions!(1+2, 3+4);
61/// ```
62#[macro_export]
63macro_rules! count_expressions {
64    () => (0usize);
65    ($head:expr $(,)?) => (1usize);
66    ($head:expr, $($tail:expr),* $(,)?) => (1usize + count_expressions!($($tail),*));
67}
68
69/// Compute a POSIX-style CRC32 checksum of a slice.
70///
71/// Online calculator: <https://crccalc.com/>
72pub fn crc32_posix(b: &[u8]) -> u32 {
73    let mut crc: u32 = 0;
74
75    for c in b {
76        crc ^= (*c as u32) << 24;
77
78        for _i in 0..8 {
79            if crc & (0b1 << 31) > 0 {
80                crc = (crc << 1) ^ 0x04c11db7;
81            } else {
82                crc <<= 1;
83            }
84        }
85    }
86    !crc
87}