stm32_rust_template/utils/
mod.rs

1//! # Utility Functions
2//!
3//! Common utility functions for bit manipulation and other low-level operations
4//! used throughout the STM32 template.
5//!
6//! These functions provide safe, efficient implementations for register-level
7//! operations that are frequently needed when working with microcontroller hardware.
8use core::assert;
9
10/// Sets `n_bits` bits at `bit_position` in `value` to `new_bits_val`.
11pub fn set_bits(value: u32, new_bits_val: u32, bit_position: u32, n_bits: u32) -> u32 {
12    assert!(
13        n_bits > 0 && n_bits <= 32,
14        "n_bits must be between 1 and 32"
15    );
16    assert!(bit_position < 32, "bit_position must be less than 32");
17    let mask = ((1 << n_bits) - 1) << bit_position;
18    (value & !mask) | ((new_bits_val << bit_position) & mask)
19}
20
21/// Sets or clears a single bit at `bit_position` in `value` according to `bit_val`.
22pub fn set_bit(value: u32, bit_position: u32, bit_val: bool) -> u32 {
23    if bit_val {
24        value | (1 << bit_position)
25    } else {
26        value & !(1 << bit_position)
27    }
28}
29
30/// Reads the bit at `bit_position` in `value`.
31pub fn read_bit(value: u32, bit_position: u32) -> bool {
32    (value & (1 << bit_position)) != 0
33}