once/grove/mod.rs
1mod block;
2
3use std::{
4 num::NonZero,
5 ops::{Index, IndexMut},
6};
7
8use block::Block;
9
10use crate::std_or_loom::sync::atomic::{AtomicI32, AtomicUsize, Ordering};
11
12const MAX_NUM_BLOCKS: usize = 32;
13
14/// A sparse vector with pinned elements and geometrically growing capacity.
15///
16/// `Grove` (a pun on "grow vec") is a specialized data structure that provides efficient storage
17/// for data with the following key features:
18///
19/// - **Thread Safety**: Safe for concurrent reads and writes from multiple threads
20/// - **Memory Efficiency**: Uses a block-based allocation strategy that grows geometrically
21/// - **Pinned Elements**: Once inserted, elements never move in memory
22/// - **Sparse Storage**: Efficiently handles sparse data with large gaps between indices
23///
24/// This data structure is primarily used as the backing store for other collections in this crate,
25/// such as [`OnceVec`](crate::OnceVec) and [`MultiIndexed`](crate::MultiIndexed).
26///
27/// # Implementation Details
28///
29/// `Grove` uses a series of fixed-size blocks to store elements. Each block's size is a power of 2,
30/// and the block number determines its size. This approach allows for efficient memory usage while
31/// still supporting large indices without allocating memory for all intermediate elements. We use
32/// distinct lazily-allocated blocks to avoid any reallocation, which would invalidate pointers held
33/// by other threads.
34///
35/// # Examples
36///
37/// ```
38/// use once::Grove;
39///
40/// let grove = Grove::<i32>::new();
41///
42/// // Insert elements at arbitrary indices
43/// grove.insert(0, 10);
44/// grove.insert(100, 20);
45/// grove.insert(1000, 30);
46///
47/// // Retrieve elements
48/// assert_eq!(grove.get(0), Some(&10));
49/// assert_eq!(grove.get(100), Some(&20));
50/// assert_eq!(grove.get(1000), Some(&30));
51/// assert_eq!(grove.get(50), None); // No element at this index
52/// ```
53pub struct Grove<T> {
54 blocks: [Block<T>; MAX_NUM_BLOCKS],
55 /// The maximum index that has been inserted into the `Grove` (exclusive).
56 max: AtomicUsize,
57}
58
59impl<T> Grove<T> {
60 /// Creates a new empty `Grove`.
61 ///
62 /// # Examples
63 ///
64 /// ```
65 /// use once::Grove;
66 ///
67 /// let grove = Grove::<i32>::new();
68 /// ```
69 pub fn new() -> Self {
70 Self {
71 blocks: std::array::from_fn(|_| Block::new()),
72 max: AtomicUsize::new(0),
73 }
74 }
75
76 /// Finds the block and offset within the block for the given index.
77 ///
78 /// This is an internal method used to determine which block contains the element
79 /// at the specified index and the offset within that block.
80 ///
81 /// # Parameters
82 ///
83 /// * `index`: The index to locate
84 ///
85 /// # Returns
86 ///
87 /// A tuple containing the block number and the offset within that block.
88 fn locate(&self, index: usize) -> (usize, usize) {
89 let block_num = (usize::BITS - 1 - (index + 1).leading_zeros()) as usize;
90 let block_offset = (index + 1) - (1 << block_num);
91 (block_num, block_offset)
92 }
93
94 /// Ensures that the specified block is initialized.
95 ///
96 /// This is an internal method that initializes a block if it hasn't been initialized yet.
97 /// It is called before any operation that needs to access a block.
98 ///
99 /// # Parameters
100 ///
101 /// * `block_num`: The block number to initialize
102 fn ensure_init(&self, block_num: usize) {
103 // Safety: `Block::init` is only ever called through this method, and every block has a
104 // well-defined `block_num`, and therefore a well-defined size.
105 unsafe { self.blocks[block_num].init(NonZero::new(1 << block_num).unwrap()) };
106 }
107
108 /// Inserts a value at the specified index.
109 ///
110 /// This operation is thread-safe and can be called from multiple threads. However, this method
111 /// panics if a value already exists at the specified index. Therefore, it should only be called
112 /// at most once for any given `index`.
113 ///
114 /// # Parameters
115 ///
116 /// * `index`: The index at which to insert the value
117 /// * `value`: The value to insert
118 ///
119 /// # Examples
120 ///
121 /// ```
122 /// use once::Grove;
123 ///
124 /// let grove = Grove::<i32>::new();
125 /// grove.insert(0, 10);
126 /// grove.insert(100, 20);
127 /// ```
128 pub fn insert(&self, index: usize, value: T) {
129 let (block_num, block_offset) = self.locate(index);
130 self.ensure_init(block_num);
131 // Safety: We just initialized the block, and `locate` only returns valid indices
132 unsafe { self.blocks[block_num].insert(block_offset, value) };
133 self.max.fetch_max(index + 1, Ordering::Release);
134 }
135
136 /// Attempts to insert a value at the specified index.
137 ///
138 /// This method will only insert the value if the index is not already occupied. If the index is
139 /// already occupied, the value is returned in the `Err` variant.
140 ///
141 /// # Parameters
142 ///
143 /// * `index`: The index at which to insert the value
144 /// * `value`: The value to insert
145 ///
146 /// # Returns
147 ///
148 /// * `Ok(())` if the value was successfully inserted
149 /// * `Err(value)` if the index was already occupied, returning the value that we tried to
150 /// insert
151 ///
152 /// # Examples
153 ///
154 /// ```
155 /// use once::Grove;
156 ///
157 /// let grove = Grove::<i32>::new();
158 /// assert_eq!(grove.try_insert(0, 10), Ok(()));
159 /// assert_eq!(grove.try_insert(0, 20), Err(20)); // Index already occupied
160 /// ```
161 pub fn try_insert(&self, index: usize, value: T) -> Result<(), T> {
162 let (block_num, block_offset) = self.locate(index);
163 self.ensure_init(block_num);
164 // Safety: We just initialized the block, and `locate` only returns valid indices
165 let ret = unsafe { self.blocks[block_num].try_insert(block_offset, value) };
166 if ret.is_ok() {
167 self.max.fetch_max(index + 1, Ordering::Release);
168 }
169 ret
170 }
171
172 /// Retrieves a reference to the value at the specified index, if it exists.
173 ///
174 /// # Parameters
175 ///
176 /// * `index`: The index of the value to retrieve
177 ///
178 /// # Returns
179 ///
180 /// * `Some(&T)` if a value exists at the specified index
181 /// * `None` if no value exists at the specified index
182 ///
183 /// # Examples
184 ///
185 /// ```
186 /// use once::Grove;
187 ///
188 /// let grove = Grove::<i32>::new();
189 /// grove.insert(0, 10);
190 ///
191 /// assert_eq!(grove.get(0), Some(&10));
192 /// assert_eq!(grove.get(1), None);
193 /// ```
194 pub fn get(&self, index: usize) -> Option<&T> {
195 let (block_num, block_offset) = self.locate(index);
196 if self.blocks[block_num].is_init() {
197 // Safety: We just observed that the block is initialized
198 unsafe { self.blocks[block_num].get(block_offset) }
199 } else {
200 None
201 }
202 }
203
204 /// Retrieves a mutable reference to the value at the specified index, if it exists.
205 ///
206 /// This method can only be called if we have an exclusive reference to self, which may not be
207 /// very common in practice. However, it is useful for `Drop` implementations.
208 ///
209 /// # Parameters
210 ///
211 /// * `index`: The index of the value to retrieve
212 ///
213 /// # Returns
214 ///
215 /// * `Some(&mut T)` if a value exists at the specified index
216 /// * `None` if no value exists at the specified index
217 ///
218 /// # Examples
219 ///
220 /// ```
221 /// use once::Grove;
222 ///
223 /// let mut grove = Grove::<i32>::new();
224 /// grove.insert(0, 10);
225 ///
226 /// if let Some(value) = grove.get_mut(0) {
227 /// *value = 20;
228 /// }
229 ///
230 /// assert_eq!(grove.get(0), Some(&20));
231 /// ```
232 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
233 let (block_num, block_offset) = self.locate(index);
234 self.blocks[block_num].get_mut(block_offset)
235 }
236
237 /// Retrieves a reference to the value at the specified index without checking that a value
238 /// exists.
239 ///
240 /// # Safety
241 ///
242 /// A value must have been previously inserted at the specified index.
243 pub unsafe fn get_unchecked(&self, index: usize) -> &T {
244 let (block_num, block_offset) = self.locate(index);
245 // We know that we already observed the block to be initialized, so we can get away with a
246 // relaxed load.
247 let data_ptr = self.blocks[block_num].data().load(Ordering::Relaxed);
248 unsafe { (*data_ptr.add(block_offset)).get_unchecked() }
249 }
250
251 /// Checks if a value exists at the specified index.
252 ///
253 /// # Parameters
254 ///
255 /// * `index`: The index to check
256 ///
257 /// # Returns
258 ///
259 /// `true` if a value exists at the specified index, `false` otherwise.
260 ///
261 /// # Examples
262 ///
263 /// ```
264 /// use once::Grove;
265 ///
266 /// let grove = Grove::<i32>::new();
267 /// grove.insert(0, 10);
268 ///
269 /// assert!(grove.is_set(0));
270 /// assert!(!grove.is_set(1));
271 /// ```
272 pub fn is_set(&self, index: usize) -> bool {
273 let (block_num, block_offset) = self.locate(index);
274 if self.blocks[block_num].is_init() {
275 // Safety: We just observed that the block is initialized
276 unsafe { self.blocks[block_num].is_set(block_offset) }
277 } else {
278 false
279 }
280 }
281
282 /// Returns the length of the `Grove`.
283 ///
284 /// The length is defined as the maximum index that has been inserted into the `Grove` plus one.
285 /// Note that this does not necessarily reflect the number of elements in the `Grove`, as there
286 /// may be gaps. Also, since this is a wait-free data structure, the return value may not be
287 /// accurate, but it will always be a lower bound for the true length from the perspective of
288 /// any thread.
289 ///
290 /// # Returns
291 ///
292 /// The length of the `Grove`.
293 ///
294 /// # Examples
295 ///
296 /// ```
297 /// use once::Grove;
298 ///
299 /// let grove = Grove::<i32>::new();
300 /// grove.insert(0, 10);
301 /// grove.insert(5, 20);
302 ///
303 /// assert_eq!(grove.len(), 6); // 5 + 1
304 /// ```
305 pub fn len(&self) -> usize {
306 self.max.load(Ordering::Acquire)
307 }
308
309 pub fn is_empty(&self) -> bool {
310 self.len() == 0
311 }
312
313 /// Creates a `Grove` from a `Vec`.
314 ///
315 /// The elements in the vector will be inserted into the `Grove` at their respective indices.
316 ///
317 /// # Parameters
318 ///
319 /// * `v`: The vector to convert
320 ///
321 /// # Returns
322 ///
323 /// A new `Grove` containing the elements from the vector.
324 ///
325 /// # Examples
326 ///
327 /// ```
328 /// use once::Grove;
329 ///
330 /// let vec = vec![10, 20, 30];
331 /// let grove = Grove::from_vec(vec);
332 ///
333 /// assert_eq!(grove.get(0), Some(&10));
334 /// assert_eq!(grove.get(1), Some(&20));
335 /// assert_eq!(grove.get(2), Some(&30));
336 /// ```
337 pub fn from_vec(v: Vec<T>) -> Self {
338 let grove = Self::new();
339 for (i, value) in v.into_iter().enumerate() {
340 grove.insert(i, value);
341 }
342 grove
343 }
344
345 /// Returns an iterator over the index-value pairs in the `Grove`.
346 ///
347 /// The iterator yields pairs in order of their indices, from 0 to `len() - 1`.
348 /// Indices that don't have a value are skipped.
349 ///
350 /// # Returns
351 ///
352 /// An iterator over `(usize, &T)` pairs in the `Grove`.
353 ///
354 /// # Examples
355 ///
356 /// ```
357 /// use once::Grove;
358 ///
359 /// let grove = Grove::<i32>::new();
360 /// grove.insert(0, 10);
361 /// grove.insert(2, 30);
362 ///
363 /// let entries: Vec<_> = grove.iter().collect();
364 /// assert_eq!(entries, vec![(0, &10), (2, &30)]);
365 /// ```
366 pub fn iter(&self) -> Iter<'_, T> {
367 Iter {
368 grove: self,
369 pos: 0,
370 len: self.len(),
371 }
372 }
373
374 pub fn iter_mut(&mut self) -> impl Iterator<Item = (usize, &mut T)> {
375 let ptr = self as *mut Self;
376 (0..self.len()).filter_map(move |i| {
377 // SAFETY: Each index maps to a unique (block, offset) pair, so the returned `&mut T`
378 // references are non-aliasing. We have `&mut self` so no other references exist.
379 unsafe { (*ptr).get_mut(i).map(|value| (i, value)) }
380 })
381 }
382
383 /// Returns an iterator over the values in the `Grove`.
384 ///
385 /// The iterator yields values in order of their indices, from 0 to `len() - 1`.
386 /// Indices that don't have a value are skipped.
387 ///
388 /// # Returns
389 ///
390 /// An iterator over the values in the `Grove`.
391 ///
392 /// # Examples
393 ///
394 /// ```
395 /// use once::Grove;
396 ///
397 /// let grove = Grove::<i32>::new();
398 /// grove.insert(0, 10);
399 /// grove.insert(2, 30);
400 ///
401 /// let values: Vec<_> = grove.values().collect();
402 /// assert_eq!(values, vec![&10, &30]);
403 /// ```
404 pub fn values(&self) -> Values<'_, T> {
405 Values(self.iter())
406 }
407}
408
409/// An iterator over the index-value pairs in a [`Grove`].
410///
411/// Created by [`Grove::iter`].
412pub struct Iter<'a, T> {
413 grove: &'a Grove<T>,
414 pos: usize,
415 len: usize,
416}
417
418impl<'a, T> Iterator for Iter<'a, T> {
419 type Item = (usize, &'a T);
420
421 fn next(&mut self) -> Option<Self::Item> {
422 while self.pos < self.len {
423 let i = self.pos;
424 self.pos += 1;
425 if let Some(value) = self.grove.get(i) {
426 return Some((i, value));
427 }
428 }
429 None
430 }
431
432 fn size_hint(&self) -> (usize, Option<usize>) {
433 // Grove is sparse, so we can't know the exact count without scanning.
434 (0, Some(self.len - self.pos))
435 }
436}
437
438/// An iterator over the values in a [`Grove`].
439///
440/// Created by [`Grove::values`].
441pub struct Values<'a, T>(Iter<'a, T>);
442
443impl<'a, T> Iterator for Values<'a, T> {
444 type Item = &'a T;
445
446 fn next(&mut self) -> Option<Self::Item> {
447 self.0.next().map(|(_, v)| v)
448 }
449
450 fn size_hint(&self) -> (usize, Option<usize>) {
451 self.0.size_hint()
452 }
453}
454
455impl<T> std::iter::FusedIterator for Iter<'_, T> {}
456
457impl<T> std::iter::FusedIterator for Values<'_, T> {}
458
459impl<'a, T> IntoIterator for &'a Grove<T> {
460 type IntoIter = Iter<'a, T>;
461 type Item = (usize, &'a T);
462
463 fn into_iter(self) -> Self::IntoIter {
464 self.iter()
465 }
466}
467
468impl<T> Default for Grove<T> {
469 fn default() -> Self {
470 Self::new()
471 }
472}
473
474impl<T: std::fmt::Debug> std::fmt::Debug for Grove<T> {
475 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476 let mut debug_map = f.debug_map();
477 for (i, val) in self.iter() {
478 debug_map.entry(&i, val);
479 }
480 debug_map.finish()
481 }
482}
483
484impl<T: Clone> Clone for Grove<T> {
485 fn clone(&self) -> Self {
486 let new_grove = Self::new();
487 for (i, value) in self.iter() {
488 new_grove.insert(i, value.clone());
489 }
490 new_grove
491 }
492}
493
494impl<T: PartialEq> PartialEq for Grove<T> {
495 fn eq(&self, other: &Self) -> bool {
496 self.iter().eq(other.iter())
497 }
498}
499
500impl<T: Eq> Eq for Grove<T> {}
501
502impl<T: std::hash::Hash> std::hash::Hash for Grove<T> {
503 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
504 for (i, value) in self.iter() {
505 i.hash(state);
506 value.hash(state);
507 }
508 }
509}
510
511impl<T> Index<usize> for Grove<T> {
512 type Output = T;
513
514 fn index(&self, index: usize) -> &Self::Output {
515 self.get(index)
516 .unwrap_or_else(|| panic!("no value at index {index:?}"))
517 }
518}
519
520impl<T> IndexMut<usize> for Grove<T> {
521 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
522 self.get_mut(index)
523 .unwrap_or_else(|| panic!("no value at index {index:?}"))
524 }
525}
526
527/// A bidirectional sparse vector that supports both positive and negative indices.
528///
529/// `TwoEndedGrove` extends the functionality of [`Grove`] by allowing elements to be indexed using
530/// both positive and negative integers. It maintains two separate `Grove` instances: one for
531/// non-negative indices and another for negative indices.
532///
533/// This data structure is primarily used as the backing store for the nodes in
534/// [`KdTrie`](crate::multiindexed::KdTrie).
535///
536/// # Examples
537///
538/// ```
539/// use once::TwoEndedGrove;
540///
541/// let grove = TwoEndedGrove::<i32>::new();
542///
543/// // Insert elements at both positive and negative indices
544/// grove.insert(-5, 10);
545/// grove.insert(0, 20);
546/// grove.insert(5, 30);
547///
548/// // Retrieve elements
549/// assert_eq!(grove.get(-5), Some(&10));
550/// assert_eq!(grove.get(0), Some(&20));
551/// assert_eq!(grove.get(5), Some(&30));
552/// assert_eq!(grove.get(-2), None); // No element at this index
553///
554/// // Get the range of valid indices
555/// assert_eq!(grove.range(), -5..6);
556/// ```
557pub struct TwoEndedGrove<T> {
558 non_neg: Grove<T>,
559 neg: Grove<T>,
560 min: AtomicI32,
561 max: AtomicI32,
562}
563
564impl<T> TwoEndedGrove<T> {
565 /// Creates a new empty `TwoEndedGrove`.
566 ///
567 /// # Examples
568 ///
569 /// ```
570 /// use once::TwoEndedGrove;
571 ///
572 /// let grove = TwoEndedGrove::<i32>::new();
573 /// ```
574 pub fn new() -> Self {
575 Self {
576 non_neg: Grove::new(),
577 neg: Grove::new(),
578 min: AtomicI32::new(i32::MAX),
579 max: AtomicI32::new(i32::MIN + 1),
580 }
581 }
582
583 /// Inserts a value at the specified index.
584 ///
585 /// This operation is thread-safe and can be called from multiple threads. This method panics if
586 /// a value already exists at the specified index.
587 ///
588 /// # Parameters
589 ///
590 /// * `idx`: The index at which to insert the value
591 /// * `value`: The value to insert
592 ///
593 /// # Examples
594 ///
595 /// ```
596 /// use once::TwoEndedGrove;
597 ///
598 /// let grove = TwoEndedGrove::<i32>::new();
599 /// grove.insert(-5, 10);
600 /// grove.insert(5, 20);
601 /// ```
602 pub fn insert(&self, idx: i32, value: T) {
603 if idx >= 0 {
604 self.non_neg.insert(idx as usize, value);
605 } else {
606 self.neg.insert((-idx) as usize, value);
607 }
608 self.max.fetch_max(idx + 1, Ordering::Relaxed);
609 self.min.fetch_min(idx, Ordering::Release);
610 }
611
612 /// Attempts to insert a value at the specified index.
613 ///
614 /// This method will only insert the value if the index is not already occupied. If the index is
615 /// already occupied, the value is returned in the `Err` variant.
616 ///
617 /// # Parameters
618 ///
619 /// * `idx`: The index at which to insert the value
620 /// * `value`: The value to insert
621 ///
622 /// # Returns
623 ///
624 /// * `Ok(())` if the value was successfully inserted
625 /// * `Err(value)` if the index was already occupied, returning the value that we tried to
626 /// insert
627 ///
628 /// # Examples
629 ///
630 /// ```
631 /// use once::TwoEndedGrove;
632 ///
633 /// let grove = TwoEndedGrove::<i32>::new();
634 /// assert_eq!(grove.try_insert(-5, 10), Ok(()));
635 /// assert_eq!(grove.try_insert(-5, 20), Err(20)); // Index already occupied
636 /// ```
637 pub fn try_insert(&self, idx: i32, value: T) -> Result<(), T> {
638 let ret = if idx >= 0 {
639 self.non_neg.try_insert(idx as usize, value)
640 } else {
641 self.neg.try_insert((-idx) as usize, value)
642 };
643 if ret.is_ok() {
644 self.max.fetch_max(idx + 1, Ordering::Relaxed);
645 self.min.fetch_min(idx, Ordering::Release);
646 }
647 ret
648 }
649
650 /// Retrieves a reference to the value at the specified index, if it exists.
651 ///
652 /// # Parameters
653 ///
654 /// * `idx`: The index of the value to retrieve
655 ///
656 /// # Returns
657 ///
658 /// * `Some(&T)` if a value exists at the specified index
659 /// * `None` if no value exists at the specified index
660 ///
661 /// # Examples
662 ///
663 /// ```
664 /// use once::TwoEndedGrove;
665 ///
666 /// let grove = TwoEndedGrove::<i32>::new();
667 /// grove.insert(-5, 10);
668 ///
669 /// assert_eq!(grove.get(-5), Some(&10));
670 /// assert_eq!(grove.get(0), None);
671 /// ```
672 pub fn get(&self, idx: i32) -> Option<&T> {
673 if idx >= 0 {
674 self.non_neg.get(idx as usize)
675 } else {
676 self.neg.get((-idx) as usize)
677 }
678 }
679
680 /// Retrieves a mutable reference to the value at the specified index, if it exists.
681 ///
682 /// This method can only be called if we have an exclusive reference to self, which may not be
683 /// very common in practice. It is mainly used for the `Drop` implementation of the
684 /// `MultiIndexed`, which allows to use non-atomic operations for performance.
685 ///
686 /// # Parameters
687 ///
688 /// * `idx`: The index of the value to retrieve
689 ///
690 /// # Returns
691 ///
692 /// * `Some(&mut T)` if a value exists at the specified index
693 /// * `None` if no value exists at the specified index
694 ///
695 /// # Examples
696 ///
697 /// ```
698 /// use once::TwoEndedGrove;
699 ///
700 /// let mut grove = TwoEndedGrove::<i32>::new();
701 /// grove.insert(-5, 10);
702 ///
703 /// if let Some(value) = grove.get_mut(-5) {
704 /// *value = 20;
705 /// }
706 ///
707 /// assert_eq!(grove.get(-5), Some(&20));
708 /// ```
709 pub fn get_mut(&mut self, idx: i32) -> Option<&mut T> {
710 if idx >= 0 {
711 self.non_neg.get_mut(idx as usize)
712 } else {
713 self.neg.get_mut((-idx) as usize)
714 }
715 }
716
717 /// Returns the range of indices that have values in the `TwoEndedGrove`.
718 ///
719 /// We return both the minimum and maximum indices at the same time to optimize memory
720 /// orderings.
721 ///
722 /// # Returns
723 ///
724 /// A [`Range`](std::ops::Range) representing the range of indices that have values in the
725 /// `TwoEndedGrove`. It is not guaranteed that all indices in the range have values. However, it
726 /// is guaranteed that only the indices in the range have values *if* the `TwoEndedGrove` is not
727 /// being concurrently modified.
728 ///
729 /// # Examples
730 ///
731 /// ```
732 /// use once::TwoEndedGrove;
733 ///
734 /// let grove = TwoEndedGrove::<i32>::new();
735 /// grove.insert(-5, 10);
736 /// grove.insert(0, 20);
737 /// grove.insert(5, 30);
738 ///
739 /// assert_eq!(grove.range(), -5..6);
740 /// ```
741 pub fn range(&self) -> std::ops::Range<i32> {
742 // We use a Relaxed max load because all insertion operations end with a release-store of
743 // the min. We have a chain of happens-before relationships:
744 // load max <- acquire-load min <- release-store min <- store max
745 self.min.load(Ordering::Acquire)..self.max.load(Ordering::Relaxed)
746 }
747
748 pub fn iter(&self) -> impl Iterator<Item = (i32, &T)> {
749 let non_negs = self
750 .non_neg
751 .iter()
752 .map(move |(idx, value)| (idx as i32, value));
753 let negs = self
754 .neg
755 .iter()
756 .map(move |(idx, value)| (-(idx as i32), value));
757 non_negs.chain(negs)
758 }
759
760 pub fn iter_mut(&mut self) -> impl Iterator<Item = (i32, &mut T)> {
761 let non_negs = self
762 .non_neg
763 .iter_mut()
764 .map(move |(idx, value)| (idx as i32, value));
765 let negs = self
766 .neg
767 .iter_mut()
768 .map(move |(idx, value)| (-(idx as i32), value));
769 non_negs.chain(negs)
770 }
771
772 pub fn values(&self) -> impl Iterator<Item = &T> {
773 self.iter().map(move |(_, value)| value)
774 }
775
776 pub fn values_mut(&mut self) -> impl Iterator<Item = &mut T> {
777 self.iter_mut().map(move |(_, value)| value)
778 }
779
780 /// Checks if a value exists at the specified index.
781 ///
782 /// # Parameters
783 ///
784 /// * `idx`: The index to check
785 ///
786 /// # Returns
787 ///
788 /// `true` if a value exists at the specified index, `false` otherwise.
789 ///
790 /// # Examples
791 ///
792 /// ```
793 /// use once::TwoEndedGrove;
794 ///
795 /// let grove = TwoEndedGrove::<i32>::new();
796 /// grove.insert(-5, 10);
797 ///
798 /// assert!(grove.is_set(-5));
799 /// assert!(!grove.is_set(0));
800 /// ```
801 pub fn is_set(&self, idx: i32) -> bool {
802 if idx >= 0 {
803 self.non_neg.is_set(idx as usize)
804 } else {
805 self.neg.is_set((-idx) as usize)
806 }
807 }
808}
809
810impl<T> Default for TwoEndedGrove<T> {
811 fn default() -> Self {
812 Self::new()
813 }
814}
815
816impl<T: std::fmt::Debug> std::fmt::Debug for TwoEndedGrove<T> {
817 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
818 let mut debug_map = f.debug_map();
819 for (i, val) in self.iter() {
820 debug_map.entry(&i, val);
821 }
822 debug_map.finish()
823 }
824}
825
826impl<T: Clone> Clone for TwoEndedGrove<T> {
827 fn clone(&self) -> Self {
828 let new_grove = Self::new();
829 for (i, value) in self.iter() {
830 new_grove.insert(i, value.clone());
831 }
832 new_grove
833 }
834}
835
836impl<T: PartialEq> PartialEq for TwoEndedGrove<T> {
837 fn eq(&self, other: &Self) -> bool {
838 self.iter().eq(other.iter())
839 }
840}
841
842impl<T: Eq> Eq for TwoEndedGrove<T> {}
843
844impl<T: std::hash::Hash> std::hash::Hash for TwoEndedGrove<T> {
845 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
846 for (i, value) in self.iter() {
847 i.hash(state);
848 value.hash(state);
849 }
850 }
851}
852
853impl<T> Index<i32> for TwoEndedGrove<T> {
854 type Output = T;
855
856 fn index(&self, index: i32) -> &Self::Output {
857 self.get(index)
858 .unwrap_or_else(|| panic!("no value at index {index:?}"))
859 }
860}
861
862impl<T> IndexMut<i32> for TwoEndedGrove<T> {
863 fn index_mut(&mut self, index: i32) -> &mut Self::Output {
864 self.get_mut(index)
865 .unwrap_or_else(|| panic!("no value at index {index:?}"))
866 }
867}
868
869#[cfg(test)]
870mod tests {
871 use std::{
872 sync::atomic::{AtomicUsize, Ordering},
873 thread,
874 };
875
876 use super::*;
877
878 #[test]
879 fn test_locate() {
880 let vec = Grove::<i32>::new();
881 assert_eq!(vec.locate(0), (0, 0));
882 assert_eq!(vec.locate(1), (1, 0));
883 assert_eq!(vec.locate(2), (1, 1));
884 assert_eq!(vec.locate(3), (2, 0));
885 assert_eq!(vec.locate(4), (2, 1));
886 assert_eq!(vec.locate(5), (2, 2));
887 assert_eq!(vec.locate(6), (2, 3));
888 assert_eq!(vec.locate(7), (3, 0));
889 assert_eq!(vec.locate(8), (3, 1));
890 assert_eq!(vec.locate(9), (3, 2));
891 assert_eq!(vec.locate(10), (3, 3));
892 assert_eq!(vec.locate(11), (3, 4));
893 assert_eq!(vec.locate(12), (3, 5));
894 assert_eq!(vec.locate(13), (3, 6));
895 assert_eq!(vec.locate(14), (3, 7));
896 assert_eq!(vec.locate(15), (4, 0));
897 assert_eq!(vec.locate(16), (4, 1));
898 assert_eq!(vec.locate(17), (4, 2));
899 // This should be good enough
900 }
901
902 #[test]
903 fn test_grove_insert_get() {
904 let v = Grove::<i32>::new();
905 assert!(v.get(42).is_none());
906 v.insert(42, 42);
907 assert_eq!(v.get(42), Some(&42));
908 }
909
910 #[test]
911 fn test_grove_debug() {
912 let v = Grove::<i32>::new();
913 v.insert(0, 1);
914 v.insert(100, 2);
915 v.insert(1000, 3);
916
917 expect_test::expect![[r#"
918 {
919 0: 1,
920 100: 2,
921 1000: 3,
922 }
923 "#]]
924 .assert_debug_eq(&v);
925 }
926
927 #[test]
928 fn test_grove_clone() {
929 let v = Grove::<i32>::new();
930 v.insert(0, 1);
931 v.insert(100, 2);
932 v.insert(1000, 3);
933
934 let v2 = v.clone();
935
936 assert_ne!(&raw const v, &raw const v2);
937 assert_eq!(v, v2);
938 }
939
940 #[test]
941 fn test_grove_requires_drop() {
942 use std::sync::Arc;
943
944 static ACTIVE_ALLOCS: AtomicUsize = AtomicUsize::new(0);
945
946 struct DropCounter;
947
948 impl DropCounter {
949 fn new() -> Self {
950 ACTIVE_ALLOCS.fetch_add(1, Ordering::Relaxed);
951 Self
952 }
953 }
954
955 impl Drop for DropCounter {
956 fn drop(&mut self) {
957 ACTIVE_ALLOCS.fetch_sub(1, Ordering::Relaxed);
958 }
959 }
960
961 let v = Arc::new(Grove::<DropCounter>::new());
962 assert_eq!(ACTIVE_ALLOCS.load(Ordering::Relaxed), 0);
963
964 let num_threads = crate::test_utils::num_threads();
965 let inserts_per_thread = crate::test_utils::values_per_thread();
966
967 thread::scope(|s| {
968 for thread_id in 0..num_threads {
969 let v = Arc::clone(&v);
970 s.spawn(move || {
971 for i in 0..inserts_per_thread {
972 v.insert(thread_id * inserts_per_thread + i, DropCounter::new());
973 }
974 });
975 }
976 });
977
978 assert_eq!(
979 ACTIVE_ALLOCS.load(Ordering::Relaxed),
980 num_threads * inserts_per_thread
981 );
982
983 drop(v);
984
985 assert_eq!(ACTIVE_ALLOCS.load(Ordering::Relaxed), 0);
986 }
987
988 fn grove_high_contention(num_threads: usize) {
989 use crate::std_or_loom::{sync::Arc, thread};
990
991 let vec = Arc::new(Grove::<usize>::new());
992
993 let handles: Vec<_> = (0..num_threads)
994 .map(|thread_id| {
995 let vec = Arc::clone(&vec);
996 thread::spawn(move || {
997 for i in 0..10 {
998 vec.insert(thread_id * 10 + i, thread_id);
999 }
1000 })
1001 })
1002 .collect();
1003
1004 for h in handles {
1005 h.join().unwrap();
1006 }
1007
1008 for thread_id in 0..num_threads {
1009 for i in 0..10 {
1010 assert_eq!(
1011 vec.get(thread_id * 10 + i),
1012 Some(&thread_id),
1013 "Value mismatch at index {}",
1014 thread_id * 10 + i
1015 );
1016 }
1017 }
1018 }
1019
1020 #[test]
1021 fn test_grove_high_contention() {
1022 grove_high_contention(crate::test_utils::num_threads());
1023 }
1024
1025 #[cfg(loom)]
1026 #[test]
1027 fn loom_grove_contention() {
1028 loom::model(|| grove_high_contention(2));
1029 }
1030
1031 // TwoEndedGrove tests
1032
1033 #[test]
1034 fn test_two_ended_grove_basic() {
1035 let grove = TwoEndedGrove::<i32>::new();
1036
1037 // Insert values at positive and negative indices
1038 grove.insert(-5, 10);
1039 grove.insert(-2, 20);
1040 grove.insert(0, 30);
1041 grove.insert(3, 40);
1042 grove.insert(5, 50);
1043
1044 // Check values
1045 assert_eq!(grove.get(-5), Some(&10));
1046 assert_eq!(grove.get(-2), Some(&20));
1047 assert_eq!(grove.get(0), Some(&30));
1048 assert_eq!(grove.get(3), Some(&40));
1049 assert_eq!(grove.get(5), Some(&50));
1050
1051 // Check non-existent values
1052 assert_eq!(grove.get(-10), None);
1053 assert_eq!(grove.get(-3), None);
1054 assert_eq!(grove.get(1), None);
1055 assert_eq!(grove.get(10), None);
1056
1057 // Check min and max
1058 assert_eq!(grove.range(), -5..6);
1059 }
1060
1061 #[test]
1062 fn test_two_ended_grove_try_insert() {
1063 let grove = TwoEndedGrove::<i32>::new();
1064
1065 // Insert values
1066 assert!(grove.try_insert(-5, 10).is_ok());
1067 assert!(grove.try_insert(5, 20).is_ok());
1068
1069 // Try to insert at the same indices
1070 assert!(grove.try_insert(-5, 30).is_err());
1071 assert!(grove.try_insert(5, 40).is_err());
1072
1073 // Check values
1074 assert_eq!(grove.get(-5), Some(&10));
1075 assert_eq!(grove.get(5), Some(&20));
1076 }
1077
1078 #[test]
1079 fn test_two_ended_grove_is_set() {
1080 let grove = TwoEndedGrove::<i32>::new();
1081
1082 // Insert values
1083 grove.insert(-5, 10);
1084 grove.insert(5, 20);
1085
1086 // Check is_set
1087 assert!(grove.is_set(-5));
1088 assert!(grove.is_set(5));
1089 assert!(!grove.is_set(-10));
1090 assert!(!grove.is_set(0));
1091 assert!(!grove.is_set(10));
1092 }
1093
1094 #[test]
1095 fn test_two_ended_grove_get_mut() {
1096 let mut grove = TwoEndedGrove::<i32>::new();
1097
1098 // Insert values
1099 grove.insert(-5, 10);
1100 grove.insert(5, 20);
1101
1102 // Modify values
1103 if let Some(value) = grove.get_mut(-5) {
1104 *value = 30;
1105 }
1106 if let Some(value) = grove.get_mut(5) {
1107 *value = 40;
1108 }
1109
1110 // Check values
1111 assert_eq!(grove.get(-5), Some(&30));
1112 assert_eq!(grove.get(5), Some(&40));
1113 }
1114
1115 #[test]
1116 fn test_two_ended_grove_concurrent() {
1117 use std::sync::Arc;
1118
1119 let grove = Arc::new(TwoEndedGrove::<i32>::new());
1120 let num_threads = crate::test_utils::num_threads() as i32;
1121 let values_per_thread = crate::test_utils::values_per_thread() as i32;
1122
1123 let handles: Vec<_> = (0..num_threads)
1124 .map(|thread_id| {
1125 let grove = Arc::clone(&grove);
1126 thread::spawn(move || {
1127 for i in (-values_per_thread / 2)..(values_per_thread / 2) {
1128 let value = thread_id * values_per_thread + i;
1129 grove.insert(value, value);
1130 }
1131 })
1132 })
1133 .collect();
1134
1135 for handle in handles {
1136 handle.join().unwrap();
1137 }
1138
1139 // Verify values
1140 for thread_id in 0..num_threads {
1141 for i in (-values_per_thread / 2)..(values_per_thread / 2) {
1142 let value = thread_id * values_per_thread + i;
1143 assert_eq!(grove.get(value), Some(&value));
1144 }
1145 }
1146 }
1147
1148 #[test]
1149 fn test_two_ended_grove_positive_min() {
1150 let grove = TwoEndedGrove::<i32>::new();
1151
1152 // Insert values
1153 grove.insert(3, 30);
1154 grove.insert(5, 50);
1155
1156 // Check min
1157 assert_eq!(grove.range(), 3..6);
1158 }
1159
1160 #[test]
1161 fn test_grove_iter_mut_no_aliasing() {
1162 let mut grove = Grove::<i32>::new();
1163 grove.insert(0, 10);
1164 grove.insert(1, 20);
1165 grove.insert(3, 30);
1166 grove.insert(7, 40);
1167
1168 let mut it = grove.iter_mut();
1169 let (_, a) = it.next().unwrap();
1170 let (_, b) = it.next().unwrap();
1171 let (_, c) = it.next().unwrap();
1172 let (_, d) = it.next().unwrap();
1173
1174 // Miri detects borrow-model violations if any of the references alias.
1175 *a += 1;
1176 *b += 2;
1177 *c += 3;
1178 *d += 4;
1179 drop(it);
1180
1181 assert_eq!(grove.get(0), Some(&11));
1182 assert_eq!(grove.get(1), Some(&22));
1183 assert_eq!(grove.get(3), Some(&33));
1184 assert_eq!(grove.get(7), Some(&44));
1185 }
1186
1187 #[test]
1188 fn test_two_ended_grove_iter_mut_no_aliasing() {
1189 let mut grove = TwoEndedGrove::<i32>::new();
1190 grove.insert(-3, 10);
1191 grove.insert(-1, 20);
1192 grove.insert(0, 30);
1193 grove.insert(5, 40);
1194
1195 // Hold all four &mut references simultaneously.
1196 let mut it = grove.iter_mut();
1197 let (i0, a) = it.next().unwrap();
1198 let (i1, b) = it.next().unwrap();
1199 let (i2, c) = it.next().unwrap();
1200 let (i3, d) = it.next().unwrap();
1201
1202 *a += 1;
1203 *b += 2;
1204 *c += 3;
1205 *d += 4;
1206 drop(it);
1207
1208 // Verify using the indices returned by the iterator (order is non-neg then neg).
1209 assert_eq!(grove.get(i0), Some(&31));
1210 assert_eq!(grove.get(i1), Some(&42));
1211 assert_eq!(grove.get(i2), Some(&23));
1212 assert_eq!(grove.get(i3), Some(&14));
1213 }
1214
1215 #[test]
1216 fn test_two_ended_grove_negative_max() {
1217 let grove = TwoEndedGrove::<i32>::new();
1218
1219 // Insert values
1220 grove.insert(-3, 30);
1221 grove.insert(-5, 50);
1222
1223 // Check max
1224 assert_eq!(grove.range(), -5..-2);
1225 }
1226}