Skip to main content

id_alloc/
lib.rs

1// SPDX-License-Identifier: MPL-2.0
2#![cfg_attr(not(test), no_std)]
3#![deny(unsafe_code)]
4#![feature(proc_macro_hygiene)]
5
6use vstd::prelude::*;
7use vstd_extra::prelude::*;
8
9use core::{fmt::Debug, ops::Range};
10
11use bitvec::prelude::BitVec;
12
13verus! {
14
15broadcast use {
16    group_bitvec_models,
17    axiom_bitvec_index_usize,
18    axiom_bitvec_index_req,
19    axiom_bitslice_get_range,
20    axiom_bitvec_len_bound,
21};
22
23} // verus!
24/// An id allocator implemented by the bitmap.
25/// The true bit implies that the id is allocated, and vice versa.
26///
27/// # Verified Invariant
28///
29/// `first_available_id == first_zero_index(self@)`: it is the index of the first
30/// free (`false`) bit, or the length when the bitmap is full. Consequently every
31/// bit before `first_available_id` is `true` and (unless full) the bit at
32/// `first_available_id` is `false`.
33#[derive(Clone)]
34#[verus_verify]
35pub struct IdAlloc {
36    bitset: BitVec<u8>,
37    first_available_id: usize,
38}
39
40verus! {
41
42impl View for IdAlloc {
43    type V = Seq<bool>;
44
45    closed spec fn view(&self) -> Seq<bool> {
46        bitvec_view(&self.bitset)
47    }
48}
49
50impl Inv for IdAlloc {
51    /// The well-formedness invariant: `first_available_id` is the first free bit.
52    closed spec fn inv(self) -> bool {
53        &&& 0 <= self.first_available_id <= self@.len()
54        &&& self.first_available_id == first_zero_index(self@)
55    }
56}
57
58} // verus!
59#[verus_verify]
60impl IdAlloc {
61    /// Constructs a new id allocator with a maximum capacity.
62    #[verus_spec(ret =>
63        requires
64            capacity <= usize::MAX / 8,
65        ensures
66            ret@ == Seq::new(capacity as nat, |i: int| false),
67            ret.inv(),
68    )]
69    pub fn with_capacity(capacity: usize) -> Self {
70        let mut bitset = BitVec::with_capacity(capacity);
71        bitset.resize(capacity, false);
72        Self {
73            bitset,
74            first_available_id: 0,
75        }
76    }
77
78    /// Allocates and returns a new `id`.
79    ///
80    /// If allocation is not possible, it returns `None`.
81    #[verus_spec(res =>
82        requires
83            old(self).inv(),
84        ensures
85            final(self).inv(),
86            res matches Some(id) ==> {
87                &&& id == first_zero_index(old(self)@)
88                &&& first_zero_index(old(self)@) < old(self)@.len()
89                &&& final(self)@ == old(self)@.update(first_zero_index(old(self)@), true)
90            },
91            res is None ==> {
92                &&& first_zero_index(old(self)@) == old(self)@.len()
93                &&& final(self)@ == old(self)@
94            },
95    )]
96    pub fn alloc(&mut self) -> Option<usize> {
97        if self.first_available_id < self.bitset.len() {
98            let id = self.first_available_id;
99            proof! {
100                lemma_first_zero_index_is_first_zero(self@);
101            }
102            self.bitset.set(id, true);
103            self.update_first_available_id(id + 1);
104            Some(id)
105        } else {
106            None
107        }
108    }
109
110    /// Allocates a consecutive range of new `id`s.
111    ///
112    /// The `count` is the number of consecutive `id`s to allocate. If it is 0, return `None`.
113    ///
114    /// If allocation is not possible, it returns `None`.
115    ///
116    /// TODO: Choose a more efficient strategy.
117    #[verus_spec(res =>
118        requires
119            old(self).inv(),
120        ensures
121            final(self).inv(),
122            res matches Some(r) ==> {
123                &&& r.end - r.start == count
124                &&& r.end <= old(self)@.len()
125                &&& (forall|i: int| #![trigger old(self)@[i]] r.start <= i < r.end ==> !old(self)@[i])
126                &&& (forall|i: int| #![trigger final(self)@[i]] r.start <= i < r.end ==> final(self)@[i])
127                &&& (forall|i: int| 0 <= i < final(self)@.len() && !(r.start <= i < r.end) ==> final(self)@[i] == old(self)@[i])
128                &&& final(self)@.len() == old(self)@.len()
129            },
130            res is None ==> final(self)@ == old(self)@
131    )]
132    pub fn alloc_consecutive(&mut self, count: usize) -> Option<Range<usize>> {
133        if count == 0 {
134            return None;
135        }
136
137        let end = self.first_available_id.checked_add(count)?;
138        if end > self.bitset.len() {
139            return None;
140        }
141
142        // Scan the bitmap from the position `first_available_id`
143        // for the first `count` number of consecutive 0's.
144        let allocated_range = {
145            // Invariance: all bits within `curr_range` are 0's
146            let mut curr_range = self.first_available_id..self.first_available_id + 1;
147            proof! {
148                lemma_first_zero_index_is_first_zero(self@);
149            }
150            #[verus_spec(invariant
151                count > 0,
152                self@ == old(self)@,
153                self.first_available_id == old(self).first_available_id,
154                self.first_available_id <= curr_range.start <= curr_range.end <= self@.len(),
155                0 <= curr_range.end - curr_range.start <= count,
156                forall|j: int| #![trigger self@[j]] curr_range.start <= j < curr_range.end ==> !self@[j],
157                decreases self@.len() - curr_range.end,
158            )]
159            while curr_range.len() < count && curr_range.end < self.bitset.len() {
160                if !self.is_allocated(curr_range.end) {
161                    curr_range.end += 1;
162                } else {
163                    curr_range = curr_range.end + 1..curr_range.end + 1;
164                }
165            }
166
167            if curr_range.len() < count {
168                return None;
169            }
170
171            curr_range
172        };
173
174        #[verus_spec(invariant
175            self@.len() == old(self)@.len(),
176            allocated_range.end <= self@.len(),
177            allocated_range.start <= id <= allocated_range.end,
178            forall|j: int| #![trigger self@[j]] allocated_range.start <= j < id ==> self@[j],
179            forall|j: int| 0 <= j < self@.len() && !(allocated_range.start <= j < id) ==> self@[j] == old(self)@[j],
180        )]
181        // Set every bit to 1 within the allocated range
182        for id in allocated_range.clone() {
183            self.bitset.set(id, true);
184        }
185
186        // In case we need to update first_available_id
187        if self.is_allocated(self.first_available_id) {
188            self.update_first_available_id(allocated_range.end);
189        }
190
191        proof! {
192            let faid = old(self).first_available_id as int;
193            if faid < allocated_range.start {
194                lemma_first_zero_index_is_first_zero(self@);
195            }
196        }
197
198        Some(allocated_range)
199    }
200
201    /// Releases the consecutive range of allocated `id`s.
202    ///
203    /// # Panics
204    ///
205    /// If the `range` is out of bounds, this method will panic.
206    #[verus_spec(
207        requires
208            old(self).inv(),
209            range.end <= self@.len(),
210            forall|i: int| range.start <= i < self@.len() && i < range.end ==> self@[i],
211        ensures
212            final(self)@.len() == old(self)@.len(),
213            forall|i: int| #![trigger final(self)@[i]] range.start <= i < range.end ==> !final(self)@[i],
214            forall|i: int|
215                0 <= i < final(self)@.len() && !(range.start <= i < range.end) ==> final(self)@[i] == old(self)@[i],
216            final(self).inv(),
217    )]
218    pub fn free_consecutive(&mut self, range: Range<usize>) {
219        if range.is_empty() {
220            return;
221        }
222
223        let range_start = range.start;
224        #[verus_spec(invariant
225            self@.len() == old(self)@.len(),
226            range.end <= self@.len(),
227            range.start <= id <= range.end,
228            forall|j: int| #![trigger self@[j]] range.start <= j < id ==> !self@[j],
229            forall|j: int| #![trigger self@[j]] id <= j < range.end ==> self@[j],
230            forall|j: int| 0 <= j < self@.len() && !(range.start <= j < id) ==> self@[j] == old(self)@[j],
231        )]
232        for id in range {
233            debug_assert!(self.is_allocated(id));
234            self.bitset.set(id, false);
235        }
236
237        if range_start < self.first_available_id {
238            self.first_available_id = range_start
239        }
240        proof! {
241            lemma_first_zero_index_clear_range(
242                old(self)@,
243                self@,
244                range.start as int,
245                range.end as int,
246            );
247        }
248    }
249
250    /// Releases the allocated `id`.
251    ///
252    /// # Panics
253    ///
254    /// If the `id` is out of bounds, this method will panic.
255    #[verus_spec(
256        requires
257            old(self).inv(),
258            id < self@.len(),
259            self@[id as int],
260        ensures
261            final(self)@ == old(self)@.update(id as int, false),
262            final(self).inv(),
263    )]
264    pub fn free(&mut self, id: usize) {
265        debug_assert!(self.is_allocated(id));
266
267        self.bitset.set(id, false);
268        proof! {
269            lemma_first_zero_index_clear(old(self)@, id as int);
270        }
271        if id < self.first_available_id {
272            self.first_available_id = id;
273        }
274    }
275
276    /// Allocates a specific ID.
277    ///
278    /// If the ID is already allocated, it returns `None`, otherwise it
279    /// returns the allocated ID.
280    ///
281    /// # Panics
282    ///
283    /// If the `id` is out of bounds, this method will panic.
284    #[verus_spec(res =>
285        requires
286            old(self).inv(),
287            id < self@.len(),
288        ensures
289            final(self).inv(),
290            res is Some ==> {
291                &&& final(self)@ == old(self)@.update(id as int, true)
292                &&& !old(self)@[id as int]
293                &&& res == Some(id)
294            },
295            res is None ==> {
296                &&& old(self)@[id as int]
297                &&& final(self)@ == old(self)@
298            },
299    )]
300    pub fn alloc_specific(&mut self, id: usize) -> Option<usize> {
301        if self.bitset[id] {
302            return None;
303        }
304        self.bitset.set(id, true);
305        if id == self.first_available_id {
306            proof! {
307                lemma_first_zero_index_is_first_zero(old(self)@);
308            }
309            self.update_first_available_id(id + 1);
310        }
311        proof! {
312            if id != old(self).first_available_id {
313                lemma_first_zero_index_is_first_zero(old(self)@);
314                lemma_first_zero_index_set_after_first_zero(old(self)@, id as int);
315            }
316        }
317        Some(id)
318    }
319
320    /// Returns true if the `id` is allocated.
321    ///
322    /// # Panics
323    ///
324    /// If the `id` is out of bounds, this method will panic.
325    #[verus_spec(
326        requires
327            id < self@.len(),
328        returns
329            self@[id as int],
330    )]
331    pub fn is_allocated(&self, id: usize) -> bool {
332        self.bitset[id]
333    }
334
335    /// Updates the `first_available_id` field to the first zero index at or after `start`.
336    #[verus_spec(
337        requires
338            0 <= self.first_available_id <= self@.len(),
339            0 <= start <= self@.len(),
340            forall|i: int| #![trigger self@[i]] 0 <= i < start ==> self@[i],
341        ensures
342            final(self)@ == old(self)@,
343            final(self).first_available_id == first_zero_index(final(self)@),
344            final(self).inv(),
345    )]
346    fn update_first_available_id(&mut self, start: usize) {
347        let len = self.bitset.len();
348        let bit_slice = self
349            .bitset
350            .get(start..len)
351            .expect("start is guaranteed to be valid by the caller");
352        self.first_available_id = bit_slice
353            .first_zero()
354            .map(
355                #[verus_spec(ret: usize =>
356                requires offset + start <= usize::MAX
357                ensures ret == start + offset
358            )]
359                |offset| start + offset,
360            )
361            .unwrap_or(len);
362        proof! {
363            lemma_first_zero_index_after_true_prefix(self@, start as int);
364            let tail = self@[start..];
365            lemma_first_zero_index_is_first_zero(self@);
366            assert(is_first_zero(bitslice_view(bit_slice), first_zero_index(tail)));
367        }
368    }
369}
370
371impl Debug for IdAlloc {
372    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
373        f.debug_struct("IdAlloc")
374            .field("len", &self.bitset.len())
375            .field("first_available_id", &self.first_available_id)
376            .finish()
377    }
378}
379
380#[cfg(test)]
381mod test {
382    use super::IdAlloc;
383
384    #[test]
385    fn bitmap_alloc_out_of_bounds() {
386        let capacity = 16;
387        let mut bitmap = IdAlloc::with_capacity(capacity);
388
389        for _ in 0..capacity {
390            assert!(bitmap.alloc().is_some());
391        }
392
393        // Allocating one more ID should fail since the
394        // bitmap's `first_available_id` + `count` is out of bounds.
395        assert!(bitmap.alloc_consecutive(1).is_none());
396    }
397}