freertos_rust/
utils.rs

1use crate::base::*;
2use crate::prelude::v1::*;
3use crate::shim::*;
4
5use core::ffi::CStr;
6
7#[derive(Debug, Copy, Clone)]
8pub struct TypeSizeError {
9    pub id: usize,
10    pub c_size: usize,
11    pub rust_size: usize,
12}
13
14#[cfg(feature = "cpu_clock")]
15pub fn cpu_clock_hz() -> u32 {
16  unsafe { freertos_rs_get_configCPU_CLOCK_HZ() }
17}
18
19/// Perform checks whether the C FreeRTOS shim and Rust agree on the sizes of used types.
20pub fn shim_sanity_check() -> Result<(), TypeSizeError> {
21    let checks = [
22        (0, mem::size_of::<FreeRtosVoidPtr>()),
23        (1, mem::size_of::<FreeRtosCharPtr>()),
24        (2, mem::size_of::<FreeRtosChar>()),
25        (10, mem::size_of::<FreeRtosBaseType>()),
26        (11, mem::size_of::<FreeRtosUBaseType>()),
27        (12, mem::size_of::<FreeRtosTickType>()),
28        (20, mem::size_of::<FreeRtosTaskHandle>()),
29        (21, mem::size_of::<FreeRtosQueueHandle>()),
30        (22, mem::size_of::<FreeRtosSemaphoreHandle>()),
31        (23, mem::size_of::<FreeRtosTaskFunction>()),
32        (24, mem::size_of::<FreeRtosTimerHandle>()),
33        (25, mem::size_of::<FreeRtosTimerCallback>()),
34        (30, mem::size_of::<FreeRtosTaskStatusFfi>()),
35        (31, mem::size_of::<FreeRtosTaskState>()),
36        (32, mem::size_of::<FreeRtosUnsignedLong>()),
37        (33, mem::size_of::<FreeRtosUnsignedShort>()),
38    ];
39
40    for check in &checks {
41        let c_size = unsafe { freertos_rs_sizeof(check.0) };
42
43        if c_size != check.1 as u8 {
44            return Err(TypeSizeError {
45                id: check.0 as usize,
46                c_size: c_size as usize,
47                rust_size: check.1,
48            });
49        }
50    }
51
52    Ok(())
53}
54
55/// # Safety
56///
57/// `str` must be a pointer to the beginning of nul-terminated sequence of bytes.
58#[cfg(any(feature = "time", feature = "hooks", feature = "sync"))]
59pub unsafe fn str_from_c_string<'a>(str: *const u8) -> Result<&'a str, FreeRtosError> {
60    match CStr::from_ptr(str as *const _).to_str() {
61        Ok(s) => Ok(s),
62        Err(_) => Err(FreeRtosError::StringConversionError),
63    }
64}