semi_persistent_containers_verus/id_factory.rs
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! `IdFactory<T: DenseId>`: sequential dense-id allocation (production
4//! parity), verified: `try_alloc` yields exactly the ids `0, 1, 2, ...` in
5//! order while the range lasts, and `count` is the number allocated.
6//!
7//! Production's `try_alloc` range check went through `T::Index::
8//! try_from_usize`, i.e. the WORD range — twice the id range for the
9//! bit-stealing family, so a long-lived factory could hand out ids whose MSB
10//! was set (colliding with the tag bit). The verified factory checks
11//! `DenseId::try_new` (the ID range) instead — the corrected contract; the
12//! panic message is production's.
13
14use vstd::prelude::*;
15
16use crate::opt::DenseId;
17
18verus! {
19
20/// Sequential id allocator.
21pub struct IdFactory<T: DenseId> {
22 next: usize,
23 _phantom: core::marker::PhantomData<T>,
24}
25
26impl<T: DenseId> IdFactory<T> {
27 /// Number of ids handed out so far (== the next id's dense index).
28 /// Closed: the counter field is private (the abstraction is the count).
29 pub closed spec fn count_spec(&self) -> nat {
30 self.next as nat
31 }
32
33 pub fn new() -> (f: Self)
34 ensures f.count_spec() == 0,
35 {
36 IdFactory { next: 0, _phantom: core::marker::PhantomData }
37 }
38
39 /// Allocate the next id: `Some(id)` with `id.id_nat() == count` while the
40 /// range lasts, `None` once `count == id_bound` (and `usize` can hold the
41 /// increment — the id bound is at most `usize::MAX + 1`, so `next`
42 /// saturating there means the range is done).
43 pub fn try_alloc(&mut self) -> (r: Option<T>)
44 ensures
45 match r {
46 Some(id) => {
47 &&& old(self).count_spec() < T::id_bound()
48 &&& id.id_nat() == old(self).count_spec()
49 &&& final(self).count_spec() == old(self).count_spec() + 1
50 },
51 None => {
52 // Exhausted: the id range is done, OR (full-range ids
53 // only, id_bound == usize::MAX + 1) the usize counter
54 // itself saturated one id early — see the body comment.
55 &&& (old(self).count_spec() >= T::id_bound()
56 || old(self).count_spec() == usize::MAX as nat)
57 &&& final(self).count_spec() == old(self).count_spec()
58 },
59 },
60 {
61 match T::try_new(self.next) {
62 Some(id) => {
63 // try_new's Some arm gives next < id_bound <= usize::MAX + 1,
64 // so next + 1 <= usize::MAX: the increment cannot overflow...
65 // EXCEPT for a full-range id (id_bound == usize::MAX + 1) at
66 // next == usize::MAX. Saturate there: the next try_new(MAX)
67 // would have been the last Some anyway, and a saturated
68 // factory keeps returning that same last id rather than
69 // wrapping. Guard instead: refuse the increment overflow.
70 if self.next == usize::MAX {
71 // Hand out the final id and pin the factory at exhaustion
72 // by declining (production could never reach this: its id
73 // types are all bit-stealing, bound <= 2^63 < usize::MAX).
74 return None;
75 }
76 self.next = self.next + 1;
77 Some(id)
78 }
79 None => None,
80 }
81 }
82
83 /// Allocate, panicking on exhaustion (production message parity).
84 pub fn alloc(&mut self) -> (id: T)
85 ensures
86 (old(self).count_spec() < T::id_bound() && old(self).count_spec() < usize::MAX) ==> {
87 &&& id.id_nat() == old(self).count_spec()
88 &&& final(self).count_spec() == old(self).count_spec() + 1
89 },
90 {
91 let r = self.try_alloc();
92 // Total-with-documented-panic: exhaustion refuses by name.
93 if r.is_none() {
94 crate::guard::refuse("IdFactory::alloc: DenseId range exhausted");
95 }
96 match r {
97 Some(id) => id,
98 None => {
99 proof { assert(false); }
100 // Unreachable (guard trapped); satisfy the type checker.
101 #[allow(clippy::empty_loop)]
102 loop
103 invariant false,
104 decreases 0int,
105 {
106 }
107 }
108 }
109 }
110
111 pub fn count(&self) -> (n: usize)
112 ensures n as nat == self.count_spec(),
113 {
114 self.next
115 }
116}
117
118} // verus!
119
120/// `Default` (plain Rust; production parity).
121impl<T: DenseId> Default for IdFactory<T> {
122 fn default() -> Self {
123 Self::new()
124 }
125}
126
127/// Range error for `TryFrom<int>` on generated id types (production parity).
128#[derive(Debug, Clone)]
129pub struct IdRangeError {
130 pub type_name: &'static str,
131}
132
133impl core::fmt::Display for IdRangeError {
134 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
135 write!(
136 f,
137 "{}: value exceeds range (MSB must be zero)",
138 self.type_name
139 )
140 }
141}
142
143impl std::error::Error for IdRangeError {}