Debian Codegraph @

lib/src/default_index/bit_set.rs

raw
1 // Copyright 2023 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of 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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::cmp::min;
16
17 use super::composite::CompositeCommitIndex;
18 use super::entry::GlobalCommitPosition;
19
20 /// Unit of buffer allocation, which is 4kB.
21 const PAGE_SIZE_IN_BITS: u32 = 4096 * 8;
22 const PAGE_SIZE_IN_WORDS: u32 = PAGE_SIZE_IN_BITS / u64::BITS;
23
24 /// Bit set of [`GlobalCommitPosition`]s.
25 #[derive(Clone, Debug)]
26 pub(super) struct PositionsBitSet {
27 data: Vec<u64>,
28 bitset_len: u32,
29 }
30
31 impl PositionsBitSet {
32 /// Creates bit set of the specified capacity.
33 pub fn with_capacity(len: u32) -> Self {
34 Self {
35 data: vec![],
36 bitset_len: u32::div_ceil(len, u64::BITS),
37 }
38 }
39
40 /// Creates bit set with the maximum position.
41 pub fn with_max_pos(max_pos: GlobalCommitPosition) -> Self {
42 assert_ne!(max_pos, GlobalCommitPosition::MAX);
43 Self::with_capacity(max_pos.0 + 1)
44 }
45
46 fn ensure_data(&mut self, bitset_pos: u32) {
47 if usize::try_from(bitset_pos).unwrap() < self.data.len() {
48 return;
49 }
50
51 // Do not pre-allocate large buffer which might not be used. We could
52 // manage buffer chunks as Vec<Vec<u64>>, but the extra indirection
53 // appeared to make get() slow.
54 let new_len = usize::try_from(min(
55 u32::div_ceil(bitset_pos + 1, PAGE_SIZE_IN_WORDS) * PAGE_SIZE_IN_WORDS,
56 self.bitset_len,
57 ))
58 .unwrap();
59 if self.data.is_empty() {
60 self.data = vec![0; new_len]; // request zeroed page
61 } else {
62 self.data.resize(new_len, 0); // realloc + copy
63 }
64 }
65
66 fn to_global_pos(&self, (bitset_pos, bit_pos): (u32, u32)) -> GlobalCommitPosition {
67 let bitset_rev_pos = u32::checked_sub(self.bitset_len, bitset_pos + 1)
68 .expect("bitset_pos < self.bitset_len");
69 GlobalCommitPosition(bitset_rev_pos * u64::BITS + bit_pos)
70 }
71
72 fn to_bitset_pos(&self, pos: GlobalCommitPosition) -> (u32, u32) {
73 let bitset_rev_pos = pos.0 / u64::BITS;
74 let bit_pos = pos.0 % u64::BITS;
75 let bitset_pos = u32::checked_sub(self.bitset_len, bitset_rev_pos + 1)
76 .expect("bitset_rev_pos < self.bitset_len");
77 (bitset_pos, bit_pos)
78 }
79
80 /// Returns `true` if the given `pos` is set.
81 ///
82 /// Panics if the `pos` exceeds the capacity.
83 pub fn get(&self, pos: GlobalCommitPosition) -> bool {
84 self.get_bit(self.to_bitset_pos(pos))
85 }
86
87 fn get_bit(&self, (bitset_pos, bit_pos): (u32, u32)) -> bool {
88 let bit = 1_u64 << bit_pos;
89 match self.data.get(usize::try_from(bitset_pos).unwrap()) {
90 Some(word) => *word & bit != 0,
91 None => false,
92 }
93 }
94
95 /// Sets `pos` to true.
96 ///
97 /// Panics if the `pos` exceeds the capacity.
98 pub fn set(&mut self, pos: GlobalCommitPosition) {
99 self.set_bit(self.to_bitset_pos(pos));
100 }
101
102 fn set_bit(&mut self, (bitset_pos, bit_pos): (u32, u32)) {
103 self.ensure_data(bitset_pos);
104 let bit = 1_u64 << bit_pos;
105 self.data[usize::try_from(bitset_pos).unwrap()] |= bit;
106 }
107
108 /// Sets `pos` to true. Returns `true` if the old value was set.
109 ///
110 /// Panics if the `pos` exceeds the capacity.
111 pub fn get_set(&mut self, pos: GlobalCommitPosition) -> bool {
112 self.get_set_bit(self.to_bitset_pos(pos))
113 }
114
115 fn get_set_bit(&mut self, (bitset_pos, bit_pos): (u32, u32)) -> bool {
116 self.ensure_data(bitset_pos);
117 let bit = 1_u64 << bit_pos;
118 let word = &mut self.data[usize::try_from(bitset_pos).unwrap()];
119 let old = *word & bit != 0;
120 *word |= bit;
121 old
122 }
123 }
124
125 /// Computes ancestors set lazily.
126 ///
127 /// This is similar to `RevWalk` functionality-wise, but implemented with the
128 /// different design goals:
129 ///
130 /// * optimized for dense ancestors set
131 /// * optimized for testing set membership
132 /// * no iterator API (which could be implemented on top)
133 #[derive(Clone, Debug)]
134 pub(super) struct AncestorsBitSet {
135 bitset: PositionsBitSet,
136 next_bitset_pos_to_visit: u32,
137 }
138
139 impl AncestorsBitSet {
140 /// Creates bit set of the specified capacity.
141 pub fn with_capacity(len: u32) -> Self {
142 let bitset = PositionsBitSet::with_capacity(len);
143 let next_bitset_pos_to_visit = bitset.bitset_len;
144 Self {
145 bitset,
146 next_bitset_pos_to_visit,
147 }
148 }
149
150 /// Adds head `pos` to the set.
151 ///
152 /// Panics if the `pos` exceeds the capacity.
153 pub fn add_head(&mut self, pos: GlobalCommitPosition) {
154 let (bitset_pos, bit_pos) = self.bitset.to_bitset_pos(pos);
155 self.bitset.set_bit((bitset_pos, bit_pos));
156 self.next_bitset_pos_to_visit = min(self.next_bitset_pos_to_visit, bitset_pos);
157 }
158
159 /// Returns `true` if the given `pos` is ancestors of the heads.
160 ///
161 /// Panics if the `pos` exceeds the capacity or has not been visited yet.
162 pub fn contains(&self, pos: GlobalCommitPosition) -> bool {
163 let (bitset_pos, bit_pos) = self.bitset.to_bitset_pos(pos);
164 assert!(bitset_pos < self.next_bitset_pos_to_visit);
165 self.bitset.get_bit((bitset_pos, bit_pos))
166 }
167
168 /// Updates set by visiting ancestors until the given `to_visit_pos`.
169 pub fn visit_until(
170 &mut self,
171 index: &CompositeCommitIndex,
172 to_visit_pos: GlobalCommitPosition,
173 ) {
174 let (last_bitset_pos_to_visit, _) = self.bitset.to_bitset_pos(to_visit_pos);
175 if last_bitset_pos_to_visit < self.next_bitset_pos_to_visit {
176 return;
177 }
178 self.bitset.ensure_data(last_bitset_pos_to_visit);
179 for visiting_bitset_pos in self.next_bitset_pos_to_visit..=last_bitset_pos_to_visit {
180 let mut unvisited_bits =
181 self.bitset.data[usize::try_from(visiting_bitset_pos).unwrap()];
182 while unvisited_bits != 0 {
183 let bit_pos = u64::BITS - unvisited_bits.leading_zeros() - 1; // from MSB
184 unvisited_bits ^= 1_u64 << bit_pos;
185 let current_pos = self.bitset.to_global_pos((visiting_bitset_pos, bit_pos));
186 for parent_pos in index.entry_by_pos(current_pos).parent_positions() {
187 assert!(parent_pos < current_pos);
188 let (parent_bitset_pos, parent_bit_pos) = self.bitset.to_bitset_pos(parent_pos);
189 self.bitset.ensure_data(parent_bitset_pos);
190 let bit = 1_u64 << parent_bit_pos;
191 self.bitset.data[usize::try_from(parent_bitset_pos).unwrap()] |= bit;
192 if visiting_bitset_pos == parent_bitset_pos {
193 unvisited_bits |= bit;
194 }
195 }
196 }
197 }
198 self.next_bitset_pos_to_visit = last_bitset_pos_to_visit + 1;
199 }
200 }
201
202 #[cfg(test)]
203 mod tests {
204 use super::super::composite::AsCompositeIndex as _;
205 use super::super::mutable::DefaultMutableIndex;
206 use super::super::readonly::FieldLengths;
207 use super::*;
208 use crate::backend::ChangeId;
209 use crate::backend::CommitId;
210 use crate::tests::TestResult;
211
212 /// Generator of unique 16-byte CommitId excluding root id
213 fn commit_id_generator() -> impl FnMut() -> CommitId {
214 let mut iter = (1_u128..).map(|n| CommitId::new(n.to_le_bytes().into()));
215 move || iter.next().unwrap()
216 }
217
218 /// Generator of unique 16-byte ChangeId excluding root id
219 fn change_id_generator() -> impl FnMut() -> ChangeId {
220 let mut iter = (1_u128..).map(|n| ChangeId::new(n.to_le_bytes().into()));
221 move || iter.next().unwrap()
222 }
223
224 #[test]
225 fn test_positions_bit_set() {
226 // Create with empty capacity, which is useless, but shouldn't panic
227 let _set = PositionsBitSet::with_capacity(0);
228
229 let mut set = PositionsBitSet::with_capacity(128);
230 assert!(!set.get(GlobalCommitPosition(0)));
231 assert!(!set.get(GlobalCommitPosition(127)));
232 set.set(GlobalCommitPosition(0));
233 assert!(set.get(GlobalCommitPosition(0)));
234 assert!(!set.get(GlobalCommitPosition(1)));
235 assert!(!set.get(GlobalCommitPosition(127)));
236 let old = set.get_set(GlobalCommitPosition(127));
237 assert!(!old);
238 assert!(!set.get(GlobalCommitPosition(63)));
239 assert!(!set.get(GlobalCommitPosition(64)));
240 assert!(set.get(GlobalCommitPosition(127)));
241 let old = set.get_set(GlobalCommitPosition(127));
242 assert!(old);
243 }
244
245 #[test]
246 fn test_positions_bit_set_allocation() -> TestResult {
247 let page_size_in_words = usize::try_from(PAGE_SIZE_IN_WORDS)?;
248 // Exactly one page
249 let mut set = PositionsBitSet::with_capacity(PAGE_SIZE_IN_BITS);
250 assert!(set.data.is_empty());
251 assert!(!set.get(GlobalCommitPosition(0)));
252 assert!(!set.get(GlobalCommitPosition(PAGE_SIZE_IN_BITS - 1)));
253 assert!(set.data.is_empty());
254 set.set(GlobalCommitPosition(0));
255 assert_eq!(set.data.len(), page_size_in_words);
256 set.set(GlobalCommitPosition(PAGE_SIZE_IN_BITS - 1));
257 assert_eq!(set.data.len(), page_size_in_words);
258 assert!(set.get(GlobalCommitPosition(0)));
259 assert!(set.get(GlobalCommitPosition(PAGE_SIZE_IN_BITS - 1)));
260
261 // Two pages
262 let mut set = PositionsBitSet::with_capacity(PAGE_SIZE_IN_BITS + 1);
263 assert!(set.data.is_empty());
264 set.set(GlobalCommitPosition(u64::BITS));
265 set.set(GlobalCommitPosition(PAGE_SIZE_IN_BITS));
266 assert_eq!(set.data.len(), page_size_in_words);
267 let old = set.get_set(GlobalCommitPosition(u64::BITS - 1));
268 assert!(!old);
269 assert_eq!(set.data.len(), usize::try_from(PAGE_SIZE_IN_WORDS + 1)?);
270 assert!(set.get(GlobalCommitPosition(u64::BITS - 1)));
271 assert!(set.get(GlobalCommitPosition(u64::BITS)));
272 assert!(set.get(GlobalCommitPosition(PAGE_SIZE_IN_BITS)));
273
274 // Exactly three pages
275 let mut set = PositionsBitSet::with_capacity(PAGE_SIZE_IN_BITS * 3);
276 assert!(set.data.is_empty());
277 set.set(GlobalCommitPosition(PAGE_SIZE_IN_BITS * 2));
278 assert_eq!(set.data.len(), page_size_in_words);
279 set.set(GlobalCommitPosition(PAGE_SIZE_IN_BITS));
280 assert_eq!(set.data.len(), usize::try_from(PAGE_SIZE_IN_WORDS * 2)?);
281 set.set(GlobalCommitPosition(0));
282 assert_eq!(set.data.len(), usize::try_from(PAGE_SIZE_IN_WORDS * 3)?);
283 assert!(set.get(GlobalCommitPosition(0)));
284 assert!(set.get(GlobalCommitPosition(PAGE_SIZE_IN_BITS)));
285 assert!(set.get(GlobalCommitPosition(PAGE_SIZE_IN_BITS * 2)));
286 Ok(())
287 }
288
289 #[test]
290 fn test_ancestors_bit_set() {
291 let mut new_commit_id = commit_id_generator();
292 let mut new_change_id = change_id_generator();
293 let mut mutable_index = DefaultMutableIndex::full(FieldLengths {
294 commit_id: 16,
295 change_id: 16,
296 });
297
298 // F F = 256
299 // |\ E = 193,194,195,..,254
300 // E | D D = 192,255
301 // | |/ C = 66,68,70,..,190
302 // B C B = 65,67,69,..,189,191
303 // |/ A = 0,1,2,..,64
304 // A
305 let id_a0 = new_commit_id();
306 mutable_index.add_commit_data(id_a0.clone(), new_change_id(), &[]);
307 let id_a64 = (1..=64).fold(id_a0.clone(), |parent_id, i| {
308 assert_eq!(mutable_index.num_commits(), i);
309 let id = new_commit_id();
310 mutable_index.add_commit_data(id.clone(), new_change_id(), &[parent_id]);
311 id
312 });
313 let (id_b189, id_c190) = (65..=190).step_by(2).fold(
314 (id_a64.clone(), id_a64.clone()),
315 |(parent_id_b, parent_id_c), i| {
316 assert_eq!(mutable_index.num_commits(), i);
317 let id_b = new_commit_id();
318 let id_c = new_commit_id();
319 mutable_index.add_commit_data(id_b.clone(), new_change_id(), &[parent_id_b]);
320 mutable_index.add_commit_data(id_c.clone(), new_change_id(), &[parent_id_c]);
321 (id_b, id_c)
322 },
323 );
324 let id_b191 = new_commit_id();
325 mutable_index.add_commit_data(id_b191.clone(), new_change_id(), &[id_b189]);
326 let id_d192 = new_commit_id();
327 mutable_index.add_commit_data(
328 id_d192.clone(),
329 new_change_id(),
330 std::slice::from_ref(&id_c190),
331 );
332 let id_e254 = (193..=254).fold(id_b191.clone(), |parent_id, i| {
333 assert_eq!(mutable_index.num_commits(), i);
334 let id = new_commit_id();
335 mutable_index.add_commit_data(id.clone(), new_change_id(), &[parent_id]);
336 id
337 });
338 let id_d255 = new_commit_id();
339 mutable_index.add_commit_data(
340 id_d255.clone(),
341 new_change_id(),
342 std::slice::from_ref(&id_d192),
343 );
344 let id_f256 = new_commit_id();
345 mutable_index.add_commit_data(
346 id_f256.clone(),
347 new_change_id(),
348 &[id_c190.clone(), id_e254.clone()],
349 );
350 assert_eq!(mutable_index.num_commits(), 257);
351
352 let index = mutable_index.as_composite().commits();
353 let to_pos = |id: &CommitId| index.commit_id_to_pos(id).unwrap();
354 let new_ancestors_set = |heads: &[&CommitId]| {
355 let mut set = AncestorsBitSet::with_capacity(index.num_commits());
356 for &id in heads {
357 set.add_head(to_pos(id));
358 }
359 set
360 };
361
362 // Nothing reachable
363 let set = new_ancestors_set(&[]);
364 assert_eq!(set.next_bitset_pos_to_visit, 5);
365 for pos in (0..=256).map(GlobalCommitPosition) {
366 assert!(!set.contains(pos), "{pos:?} should be unreachable");
367 }
368
369 // All reachable
370 let mut set = new_ancestors_set(&[&id_f256, &id_d255]);
371 assert_eq!(set.next_bitset_pos_to_visit, 0);
372 set.visit_until(index, to_pos(&id_f256));
373 assert_eq!(set.next_bitset_pos_to_visit, 1);
374 assert!(set.contains(to_pos(&id_f256)));
375 set.visit_until(index, to_pos(&id_d192));
376 assert_eq!(set.next_bitset_pos_to_visit, 2);
377 assert!(set.contains(to_pos(&id_e254)));
378 assert!(set.contains(to_pos(&id_d255)));
379 assert!(set.contains(to_pos(&id_d192)));
380 set.visit_until(index, to_pos(&id_a0));
381 assert_eq!(set.next_bitset_pos_to_visit, 5);
382 set.visit_until(index, to_pos(&id_f256)); // should be noop
383 assert_eq!(set.next_bitset_pos_to_visit, 5);
384 for pos in (0..=256).map(GlobalCommitPosition) {
385 assert!(set.contains(pos), "{pos:?} should be reachable");
386 }
387
388 // A, B, C, E, F are reachable
389 let mut set = new_ancestors_set(&[&id_f256]);
390 assert_eq!(set.next_bitset_pos_to_visit, 0);
391 set.visit_until(index, to_pos(&id_f256));
392 assert_eq!(set.next_bitset_pos_to_visit, 1);
393 assert!(set.contains(to_pos(&id_f256)));
394 set.visit_until(index, to_pos(&id_d192));
395 assert_eq!(set.next_bitset_pos_to_visit, 2);
396 assert!(!set.contains(to_pos(&id_d255)));
397 assert!(!set.contains(to_pos(&id_d192)));
398 set.visit_until(index, to_pos(&id_c190));
399 assert_eq!(set.next_bitset_pos_to_visit, 3);
400 assert!(set.contains(to_pos(&id_c190)));
401 set.visit_until(index, to_pos(&id_a64));
402 assert_eq!(set.next_bitset_pos_to_visit, 4);
403 assert!(set.contains(to_pos(&id_b191)));
404 assert!(set.contains(to_pos(&id_a64)));
405 set.visit_until(index, to_pos(&id_a0));
406 assert_eq!(set.next_bitset_pos_to_visit, 5);
407 assert!(set.contains(to_pos(&id_a0)));
408
409 // A, C, D are reachable
410 let mut set = new_ancestors_set(&[&id_d255]);
411 assert_eq!(set.next_bitset_pos_to_visit, 1);
412 assert!(!set.contains(to_pos(&id_f256)));
413 set.visit_until(index, to_pos(&id_e254));
414 assert_eq!(set.next_bitset_pos_to_visit, 2);
415 assert!(!set.contains(to_pos(&id_e254)));
416 set.visit_until(index, to_pos(&id_d255));
417 assert_eq!(set.next_bitset_pos_to_visit, 2);
418 assert!(set.contains(to_pos(&id_d255)));
419 set.visit_until(index, to_pos(&id_b191));
420 assert_eq!(set.next_bitset_pos_to_visit, 3);
421 assert!(!set.contains(to_pos(&id_b191)));
422 set.visit_until(index, to_pos(&id_c190));
423 assert_eq!(set.next_bitset_pos_to_visit, 3);
424 assert!(set.contains(to_pos(&id_c190)));
425 set.visit_until(index, to_pos(&id_a0));
426 assert_eq!(set.next_bitset_pos_to_visit, 5);
427 assert!(set.contains(to_pos(&id_a64)));
428 assert!(set.contains(to_pos(&id_a0)));
429 }
430
431 #[test]
432 fn test_ancestors_bit_set_allocation() -> TestResult {
433 let page_size_in_words = usize::try_from(PAGE_SIZE_IN_WORDS)?;
434 let mut new_commit_id = commit_id_generator();
435 let mut new_change_id = change_id_generator();
436 let mut mutable_index = DefaultMutableIndex::full(FieldLengths {
437 commit_id: 16,
438 change_id: 16,
439 });
440 // Linear history of two-page size
441 let id_0 = new_commit_id();
442 mutable_index.add_commit_data(id_0.clone(), new_change_id(), &[]);
443 (1..=PAGE_SIZE_IN_BITS).fold(id_0.clone(), |parent_id, i| {
444 assert_eq!(mutable_index.num_commits(), i);
445 let id = new_commit_id();
446 mutable_index.add_commit_data(id.clone(), new_change_id(), &[parent_id]);
447 id
448 });
449 let index = mutable_index.as_composite().commits();
450
451 let mut set = AncestorsBitSet::with_capacity(index.num_commits());
452 assert_eq!(set.next_bitset_pos_to_visit, PAGE_SIZE_IN_WORDS + 1);
453
454 // Mark the head commit
455 set.add_head(GlobalCommitPosition(PAGE_SIZE_IN_BITS));
456 assert_eq!(set.next_bitset_pos_to_visit, 0);
457 assert_eq!(set.bitset.data.len(), page_size_in_words);
458
459 set.visit_until(index, GlobalCommitPosition(PAGE_SIZE_IN_BITS));
460 assert_eq!(set.next_bitset_pos_to_visit, 1);
461 assert_eq!(set.bitset.data.len(), page_size_in_words);
462 assert!(set.contains(GlobalCommitPosition(PAGE_SIZE_IN_BITS)));
463
464 set.visit_until(index, GlobalCommitPosition(PAGE_SIZE_IN_BITS - 1));
465 assert_eq!(set.next_bitset_pos_to_visit, 2);
466 assert_eq!(set.bitset.data.len(), page_size_in_words);
467 assert!(set.contains(GlobalCommitPosition(PAGE_SIZE_IN_BITS - 1)));
468
469 // Parent link across page boundary
470 set.visit_until(index, GlobalCommitPosition(u64::BITS));
471 assert_eq!(set.next_bitset_pos_to_visit, PAGE_SIZE_IN_WORDS);
472 assert_eq!(
473 set.bitset.data.len(),
474 usize::try_from(PAGE_SIZE_IN_WORDS + 1)?
475 );
476 assert!(set.contains(GlobalCommitPosition(u64::BITS)));
477
478 set.visit_until(index, GlobalCommitPosition(0));
479 assert_eq!(set.next_bitset_pos_to_visit, PAGE_SIZE_IN_WORDS + 1);
480 assert_eq!(
481 set.bitset.data.len(),
482 usize::try_from(PAGE_SIZE_IN_WORDS + 1)?
483 );
484 assert!(set.contains(GlobalCommitPosition(0)));
485 Ok(())
486 }
487 }