1/*!
2This module defines a sparse set data structure. Its most interesting
3properties are:
45* They preserve insertion order.
6* Set membership testing is done in constant time.
7* Set insertion is done in constant time.
8* Clearing the set is done in constant time.
910The cost for doing this is that the capacity of the set needs to be known up
11front, and the elements in the set are limited to state identifiers.
1213These sets are principally used when traversing an NFA state graph. This
14happens at search time, for example, in the PikeVM. It also happens during DFA
15determinization.
16*/
1718use alloc::{vec, vec::Vec};
1920use crate::util::primitives::StateID;
2122/// A pair of sparse sets.
23///
24/// This is useful when one needs to compute NFA epsilon closures from a
25/// previous set of states derived from an epsilon closure. One set can be the
26/// starting states where as the other set can be the destination states after
27/// following the transitions for a particular byte of input.
28///
29/// There is no significance to 'set1' or 'set2'. They are both sparse sets of
30/// the same size.
31///
32/// The members of this struct are exposed so that callers may borrow 'set1'
33/// and 'set2' individually without being force to borrow both at the same
34/// time.
35#[derive(#[automatically_derived]
impl ::core::clone::Clone for SparseSets {
#[inline]
fn clone(&self) -> SparseSets {
SparseSets {
set1: ::core::clone::Clone::clone(&self.set1),
set2: ::core::clone::Clone::clone(&self.set2),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for SparseSets {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "SparseSets",
"set1", &self.set1, "set2", &&self.set2)
}
}Debug)]
36pub(crate) struct SparseSets {
37pub(crate) set1: SparseSet,
38pub(crate) set2: SparseSet,
39}
4041impl SparseSets {
42/// Create a new pair of sparse sets where each set has the given capacity.
43 ///
44 /// This panics if the capacity given is bigger than `StateID::LIMIT`.
45pub(crate) fn new(capacity: usize) -> SparseSets {
46SparseSets {
47 set1: SparseSet::new(capacity),
48 set2: SparseSet::new(capacity),
49 }
50 }
5152/// Resizes these sparse sets to have the new capacity given.
53 ///
54 /// The sets are automatically cleared.
55 ///
56 /// This panics if the capacity given is bigger than `StateID::LIMIT`.
57#[inline]
58pub(crate) fn resize(&mut self, new_capacity: usize) {
59self.set1.resize(new_capacity);
60self.set2.resize(new_capacity);
61 }
6263/// Clear both sparse sets.
64pub(crate) fn clear(&mut self) {
65self.set1.clear();
66self.set2.clear();
67 }
6869/// Swap set1 with set2.
70pub(crate) fn swap(&mut self) {
71 core::mem::swap(&mut self.set1, &mut self.set2);
72 }
7374/// Returns the memory usage, in bytes, used by this pair of sparse sets.
75pub(crate) fn memory_usage(&self) -> usize {
76self.set1.memory_usage() + self.set2.memory_usage()
77 }
78}
7980/// A sparse set used for representing ordered NFA states.
81///
82/// This supports constant time addition and membership testing. Clearing an
83/// entire set can also be done in constant time. Iteration yields elements
84/// in the order in which they were inserted.
85///
86/// The data structure is based on: https://research.swtch.com/sparse
87/// Note though that we don't actually use uninitialized memory. We generally
88/// reuse sparse sets, so the initial allocation cost is bearable. However, its
89/// other properties listed above are extremely useful.
90#[derive(#[automatically_derived]
impl ::core::clone::Clone for SparseSet {
#[inline]
fn clone(&self) -> SparseSet {
SparseSet {
len: ::core::clone::Clone::clone(&self.len),
dense: ::core::clone::Clone::clone(&self.dense),
sparse: ::core::clone::Clone::clone(&self.sparse),
}
}
}Clone)]
91pub(crate) struct SparseSet {
92/// The number of elements currently in this set.
93len: usize,
94/// Dense contains the ids in the order in which they were inserted.
95dense: Vec<StateID>,
96/// Sparse maps ids to their location in dense.
97 ///
98 /// A state ID is in the set if and only if
99 /// sparse[id] < len && id == dense[sparse[id]].
100 ///
101 /// Note that these are indices into 'dense'. It's a little weird to use
102 /// StateID here, but we know our length can never exceed the bounds of
103 /// StateID (enforced by 'resize') and StateID will be at most 4 bytes
104 /// where as a usize is likely double that in most cases.
105sparse: Vec<StateID>,
106}
107108impl SparseSet {
109/// Create a new sparse set with the given capacity.
110 ///
111 /// Sparse sets have a fixed size and they cannot grow. Attempting to
112 /// insert more distinct elements than the total capacity of the set will
113 /// result in a panic.
114 ///
115 /// This panics if the capacity given is bigger than `StateID::LIMIT`.
116#[inline]
117pub(crate) fn new(capacity: usize) -> SparseSet {
118let mut set = SparseSet { len: 0, dense: ::alloc::vec::Vec::new()vec![], sparse: ::alloc::vec::Vec::new()vec![] };
119set.resize(capacity);
120set121 }
122123/// Resizes this sparse set to have the new capacity given.
124 ///
125 /// This set is automatically cleared.
126 ///
127 /// This panics if the capacity given is bigger than `StateID::LIMIT`.
128#[inline]
129pub(crate) fn resize(&mut self, new_capacity: usize) {
130if !(new_capacity <= StateID::LIMIT) {
{
::core::panicking::panic_fmt(format_args!("sparse set capacity cannot exceed {0:?}",
StateID::LIMIT));
}
};assert!(
131 new_capacity <= StateID::LIMIT,
132"sparse set capacity cannot exceed {:?}",
133 StateID::LIMIT
134 );
135self.clear();
136self.dense.resize(new_capacity, StateID::ZERO);
137self.sparse.resize(new_capacity, StateID::ZERO);
138 }
139140/// Returns the capacity of this set.
141 ///
142 /// The capacity represents a fixed limit on the number of distinct
143 /// elements that are allowed in this set. The capacity cannot be changed.
144#[inline]
145pub(crate) fn capacity(&self) -> usize {
146self.dense.len()
147 }
148149/// Returns the number of elements in this set.
150#[inline]
151pub(crate) fn len(&self) -> usize {
152self.len
153 }
154155/// Returns true if and only if this set is empty.
156#[inline]
157pub(crate) fn is_empty(&self) -> bool {
158self.len() == 0
159}
160161/// Insert the state ID value into this set and return true if the given
162 /// state ID was not previously in this set.
163 ///
164 /// This operation is idempotent. If the given value is already in this
165 /// set, then this is a no-op.
166 ///
167 /// If more than `capacity` ids are inserted, then this panics.
168 ///
169 /// This is marked as inline(always) since the compiler won't inline it
170 /// otherwise, and it's a fairly hot piece of code in DFA determinization.
171#[cfg_attr(feature = "perf-inline", inline(always))]
172pub(crate) fn insert(&mut self, id: StateID) -> bool {
173if self.contains(id) {
174return false;
175 }
176177let i = self.len();
178if !(i < self.capacity()) {
{
::core::panicking::panic_fmt(format_args!("{0:?} exceeds capacity of {1:?} when inserting {2:?}",
i, self.capacity(), id));
}
};assert!(
179 i < self.capacity(),
180"{:?} exceeds capacity of {:?} when inserting {:?}",
181 i,
182self.capacity(),
183 id,
184 );
185// OK since i < self.capacity() and self.capacity() is guaranteed to
186 // be <= StateID::LIMIT.
187let index = StateID::new_unchecked(i);
188self.dense[index] = id;
189self.sparse[id] = index;
190self.len += 1;
191true
192}
193194/// Returns true if and only if this set contains the given value.
195#[inline]
196pub(crate) fn contains(&self, id: StateID) -> bool {
197let index = self.sparse[id];
198index.as_usize() < self.len() && self.dense[index] == id199 }
200201/// Clear this set such that it has no members.
202#[inline]
203pub(crate) fn clear(&mut self) {
204self.len = 0;
205 }
206207#[inline]
208pub(crate) fn iter(&self) -> SparseSetIter<'_> {
209SparseSetIter(self.dense[..self.len()].iter())
210 }
211212/// Returns the heap memory usage, in bytes, used by this sparse set.
213#[inline]
214pub(crate) fn memory_usage(&self) -> usize {
215self.dense.len() * StateID::SIZE + self.sparse.len() * StateID::SIZE216 }
217}
218219impl core::fmt::Debugfor SparseSet {
220fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
221let elements: Vec<StateID> = self.iter().collect();
222f.debug_tuple("SparseSet").field(&elements).finish()
223 }
224}
225226/// An iterator over all elements in a sparse set.
227///
228/// The lifetime `'a` refers to the lifetime of the set being iterated over.
229#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for SparseSetIter<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "SparseSetIter",
&&self.0)
}
}Debug)]
230pub(crate) struct SparseSetIter<'a>(core::slice::Iter<'a, StateID>);
231232impl<'a> Iteratorfor SparseSetIter<'a> {
233type Item = StateID;
234235#[cfg_attr(feature = "perf-inline", inline(always))]
236fn next(&mut self) -> Option<StateID> {
237self.0.next().copied()
238 }
239}