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 capability.
13///
14/// ```ignore
15/// use kernel::capabilities::ProcessManagementCapability;
16/// use kernel;
17///
18/// let process_mgmt_cap = create_capability!(ProcessManagementCapability);
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#[macro_export]
25macro_rules! create_capability {
26    ($T:ty $(,)?) => {{
27        struct Cap;
28        #[allow(unsafe_code)]
29        unsafe impl $T for Cap {}
30        Cap
31    }};
32}
33
34/// Count the number of passed expressions.
35///
36/// Useful for constructing variable sized arrays in other macros.
37/// Taken from the Little Book of Rust Macros.
38///
39/// ```ignore
40/// use kernel:count_expressions;
41///
42/// let count: usize = count_expressions!(1+2, 3+4);
43/// ```
44#[macro_export]
45macro_rules! count_expressions {
46    () => (0usize);
47    ($head:expr $(,)?) => (1usize);
48    ($head:expr, $($tail:expr),* $(,)?) => (1usize + count_expressions!($($tail),*));
49}
50
51/// Compute a POSIX-style CRC32 checksum of a slice.
52///
53/// Online calculator: <https://crccalc.com/>
54pub fn crc32_posix(b: &[u8]) -> u32 {
55    let mut crc: u32 = 0;
56
57    for c in b {
58        crc ^= (*c as u32) << 24;
59
60        for _i in 0..8 {
61            if crc & (0b1 << 31) > 0 {
62                crc = (crc << 1) ^ 0x04c11db7;
63            } else {
64                crc <<= 1;
65            }
66        }
67    }
68    !crc
69}