Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. kernel/scheduler/algorithm/priority_bitmask.rs

kernel/scheduler/algorithm/
priority_bitmask.rs

1// Copyright 2026 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15use core::mem;
16
17use crate::scheduler::Priority;
18
19/// Provides bitmask utility sufficient for tracking the status of all priorities.
20/// All operations are restricted to the valid range of priorities.
21pub struct PriorityBitmask {
22    /// Invariant: The bits set within `bitmasks` always correspond to valid
23    /// `Priority` enum values. This is enforced by the `set_priority` and
24    /// `clear_priority` methods, which only accept `Priority` enum values.
25    bitmasks: [usize; Self::CHUNKS],
26}
27
28impl Default for PriorityBitmask {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34impl PriorityBitmask {
35    const BITS_PER_CHUNK: usize = pw_cast::cast!(usize::BITS => usize);
36    const CHUNKS: usize = Priority::NUM_PRIORITIES.div_ceil(Self::BITS_PER_CHUNK);
37
38    #[must_use]
39    pub const fn new() -> Self {
40        // Run compile-time assertions that the Priority enum is suitable for
41        // use in the PriorityBitmask. This is necessary to guarantee the
42        // transmute in `get_highest_priority` is safe.
43        const _: () = {
44            // Guarantee assumptions on the size and range of the Priority enum.
45            assert!(mem::size_of::<Priority>() <= mem::size_of::<u8>());
46            assert!(Priority::NUM_PRIORITIES - 1 <= u8::MAX as usize);
47        };
48
49        Self {
50            bitmasks: [0; Self::CHUNKS],
51        }
52    }
53
54    /// Marks a priority as active.
55    pub fn set_priority(&mut self, priority: Priority) {
56        let chunk_index = priority as usize / Self::BITS_PER_CHUNK;
57        let bit_in_chunk = priority as usize % Self::BITS_PER_CHUNK;
58        self.bitmasks[chunk_index] |= 1 << bit_in_chunk;
59    }
60
61    /// Marks a priority as inactive.
62    pub fn clear_priority(&mut self, priority: Priority) {
63        let chunk_index = priority as usize / Self::BITS_PER_CHUNK;
64        let bit_in_chunk = priority as usize % Self::BITS_PER_CHUNK;
65        self.bitmasks[chunk_index] &= !(1 << bit_in_chunk);
66    }
67
68    /// Retrieves the highest priority that is active. If no priorities are active,
69    /// `None` is returned.
70    #[must_use]
71    pub fn get_highest_priority(&self) -> Option<Priority> {
72        use pw_cast::CastInto as _;
73
74        const OFFSET: u32 = usize::BITS - 1;
75        for i in (0..Self::CHUNKS).rev() {
76            if self.bitmasks[i] != 0 {
77                let highest_bit_index: usize =
78                    (OFFSET - self.bitmasks[i].leading_zeros()).cast_into();
79                let raw_priority_value = highest_bit_index + (i * Self::BITS_PER_CHUNK);
80
81                // Priority values are guaranteed to be u8 sized.
82                #[expect(clippy::cast_possible_truncation)]
83                let priority_value = raw_priority_value as u8;
84
85                // SAFETY: Per the `PriorityBitmask` invariant, all set bits
86                // correspond to valid `Priority` enum values. Thus, the
87                // extracted `priority_value` is guaranteed to be a valid
88                // discriminant for `Priority`.
89                let priority = unsafe { mem::transmute::<u8, Priority>(priority_value) };
90                return Some(priority);
91            }
92        }
93
94        None
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use unittest::test;
101
102    use super::*;
103
104    #[test]
105    fn empty_bitmask_returns_none() -> unittest::Result<()> {
106        let bitmask = PriorityBitmask::new();
107        unittest::assert_eq!(bitmask.get_highest_priority(), None);
108        Ok(())
109    }
110
111    #[test]
112    fn set_and_clear_priorities_tracks_highest() -> unittest::Result<()> {
113        let mut bitmask = PriorityBitmask::new();
114        bitmask.set_priority(Priority::Level0);
115        unittest::assert_eq!(bitmask.get_highest_priority(), Some(Priority::Level0));
116
117        bitmask.set_priority(Priority::Level15);
118        unittest::assert_eq!(bitmask.get_highest_priority(), Some(Priority::Level15));
119
120        bitmask.set_priority(Priority::Level31);
121        unittest::assert_eq!(bitmask.get_highest_priority(), Some(Priority::Level31));
122
123        bitmask.clear_priority(Priority::Level31);
124        unittest::assert_eq!(bitmask.get_highest_priority(), Some(Priority::Level15));
125
126        bitmask.clear_priority(Priority::Level15);
127        unittest::assert_eq!(bitmask.get_highest_priority(), Some(Priority::Level0));
128
129        bitmask.clear_priority(Priority::Level0);
130        unittest::assert_eq!(bitmask.get_highest_priority(), None);
131        Ok(())
132    }
133
134    #[test]
135    fn non_monotonic_clear_and_duplicate_ops_preserve_invariants() -> unittest::Result<()> {
136        let mut bitmask = PriorityBitmask::new();
137
138        // Clearing an already-unset priority is a safe no-op.
139        bitmask.clear_priority(Priority::Level15);
140        unittest::assert_eq!(bitmask.get_highest_priority(), None);
141
142        // Duplicate `set_priority` calls are idempotent.
143        bitmask.set_priority(Priority::Level0);
144        bitmask.set_priority(Priority::Level15);
145        bitmask.set_priority(Priority::Level31);
146        bitmask.set_priority(Priority::Level15);
147        unittest::assert_eq!(bitmask.get_highest_priority(), Some(Priority::Level31));
148
149        // Clearing a middle priority while a higher priority remains set keeps `Level31`.
150        bitmask.clear_priority(Priority::Level15);
151        bitmask.clear_priority(Priority::Level15);
152        unittest::assert_eq!(bitmask.get_highest_priority(), Some(Priority::Level31));
153
154        // Clearing `Level31` skips the cleared `Level15` bit directly down to `Level0`.
155        bitmask.clear_priority(Priority::Level31);
156        unittest::assert_eq!(bitmask.get_highest_priority(), Some(Priority::Level0));
157
158        bitmask.clear_priority(Priority::Level0);
159        unittest::assert_eq!(bitmask.get_highest_priority(), None);
160        Ok(())
161    }
162}