Skip to main content

bitmap/
bitmap.rs

1// Copyright 2026 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use zx_status::Status;
6
7/// Result of a `get` operation on a bitmap.
8#[derive(Default)]
9pub struct GetResult<T> {
10    /// True if all bits in the range were set.
11    pub all_set: bool,
12    /// The index of the first unset bit in the range, or `bitmax` if all were set.
13    pub first_unset: T,
14}
15
16/// An abstract bitmap.
17pub trait Bitmap<T>
18where
19    T: Copy + core::ops::Add<Output = T> + From<u8>,
20{
21    /// Finds a run of `run_len` `is_set` bits, between `bitoff` and `bitmax`.
22    ///
23    /// Returns the start of the run, or `Status::NO_RESOURCES` if not found.
24    fn find(&self, is_set: bool, bitoff: T, bitmax: T, run_len: T) -> Result<T, Status>;
25
26    /// Returns true if all the bits in `[bitoff, bitmax)` are set.
27    ///
28    /// Also returns the index of the first unset bit in that range.
29    fn get(&self, bitoff: T, bitmax: T) -> GetResult<T>;
30
31    /// Sets all bits in the range `[bitoff, bitmax)`.
32    ///
33    /// Only fails on allocation error or if `bitmax < bitoff`.
34    fn set(&mut self, bitoff: T, bitmax: T) -> Result<(), Status>;
35
36    /// Clears all bits in the range `[bitoff, bitmax)`.
37    ///
38    /// Only fails on allocation error or if `bitmax < bitoff`.
39    fn clear(&mut self, bitoff: T, bitmax: T) -> Result<(), Status>;
40
41    /// Clear all bits in the bitmap.
42    fn clear_all(&mut self);
43
44    /// Returns true if the bit at `bitoff` is set.
45    fn get_one(&self, bitoff: T) -> bool {
46        self.get(bitoff, bitoff + T::from(1)).all_set
47    }
48
49    /// Sets the bit at `bitoff`.
50    fn set_one(&mut self, bitoff: T) -> Result<(), Status> {
51        self.set(bitoff, bitoff + T::from(1))
52    }
53
54    /// Clears the bit at `bitoff`.
55    fn clear_one(&mut self, bitoff: T) -> Result<(), Status> {
56        self.clear(bitoff, bitoff + T::from(1))
57    }
58}