|
| 1 | +use std::alloc::Layout; |
| 2 | +use std::marker::PhantomData; |
| 3 | +use std::mem::MaybeUninit; |
| 4 | +use std::ptr::NonNull; |
| 5 | +use std::sync::Mutex; |
| 6 | +use std::sync::atomic::{AtomicPtr, AtomicU8, Ordering}; |
| 7 | + |
| 8 | +/// Provides a singly-settable Vec. |
| 9 | +/// |
| 10 | +/// This provides amortized, concurrent O(1) access to &T, expecting a densely numbered key space |
| 11 | +/// (all value slots are allocated up to the highest key inserted). |
| 12 | +pub struct OnceVec<T> { |
| 13 | + // Provide storage for up to 2^35 elements, which we expect to be enough in practice -- but can |
| 14 | + // be increased if needed. We may want to make the `slabs` list dynamic itself, likely by |
| 15 | + // indirecting through one more pointer to reduce space consumption of OnceVec if this grows |
| 16 | + // much larger. |
| 17 | + // |
| 18 | + // None of the code makes assumptions based on this size so bumping it up is easy. |
| 19 | + slabs: [Slab<T>; 36], |
| 20 | +} |
| 21 | + |
| 22 | +impl<T> Default for OnceVec<T> { |
| 23 | + fn default() -> Self { |
| 24 | + OnceVec { slabs: [const { Slab::new() }; 36] } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +unsafe impl<#[may_dangle] T> Drop for OnceVec<T> { |
| 29 | + fn drop(&mut self) { |
| 30 | + for (idx, slab) in self.slabs.iter_mut().enumerate() { |
| 31 | + unsafe { slab.deallocate(1 << idx) } |
| 32 | + } |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +impl<T> OnceVec<T> { |
| 37 | + #[inline] |
| 38 | + fn to_slab_args(idx: usize) -> (usize, usize, usize) { |
| 39 | + let slab_idx = (idx + 1).ilog2() as usize; |
| 40 | + let cap = 1 << slab_idx; |
| 41 | + let idx_in_slab = idx - (cap - 1); |
| 42 | + (slab_idx, cap, idx_in_slab) |
| 43 | + } |
| 44 | + |
| 45 | + pub fn insert(&self, idx: usize, value: T) -> Result<(), T> { |
| 46 | + let (slab_idx, cap, idx_in_slab) = Self::to_slab_args(idx); |
| 47 | + self.slabs[slab_idx].insert(cap, idx_in_slab, value) |
| 48 | + } |
| 49 | + |
| 50 | + pub fn get(&self, idx: usize) -> Option<&T> { |
| 51 | + let (slab_idx, cap, idx_in_slab) = Self::to_slab_args(idx); |
| 52 | + self.slabs[slab_idx].get(cap, idx_in_slab) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +struct Slab<T> { |
| 57 | + // If non-zero, points to a contiguously allocated block which starts with a bitset |
| 58 | + // (two bits per value, one for whether a value is present and the other for whether a value is |
| 59 | + // currently being written) and then `[V]` (some of which may be missing). |
| 60 | + // |
| 61 | + // The capacity is implicit and passed with all accessors. |
| 62 | + v: AtomicPtr<u8>, |
| 63 | + _phantom: PhantomData<[T; 1]>, |
| 64 | +} |
| 65 | + |
| 66 | +impl<T> Slab<T> { |
| 67 | + const fn new() -> Slab<T> { |
| 68 | + Slab { v: AtomicPtr::new(std::ptr::null_mut()), _phantom: PhantomData } |
| 69 | + } |
| 70 | + |
| 71 | + fn initialize(&self, cap: usize) -> NonNull<u8> { |
| 72 | + static LOCK: Mutex<()> = Mutex::new(()); |
| 73 | + |
| 74 | + if let Some(ptr) = NonNull::new(self.v.load(Ordering::Acquire)) { |
| 75 | + return ptr; |
| 76 | + } |
| 77 | + |
| 78 | + // If we are initializing the bucket, then acquire a global lock. |
| 79 | + // |
| 80 | + // This path is quite cold, so it's cheap to use a global lock. This ensures that we never |
| 81 | + // have multiple allocations for the same bucket. |
| 82 | + let _allocator_guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); |
| 83 | + |
| 84 | + // Check the lock again, sicne we might have been initialized while waiting on the lock. |
| 85 | + if let Some(ptr) = NonNull::new(self.v.load(Ordering::Acquire)) { |
| 86 | + return ptr; |
| 87 | + } |
| 88 | + |
| 89 | + let layout = Self::layout(cap).0; |
| 90 | + assert!(layout.size() > 0); |
| 91 | + |
| 92 | + // SAFETY: Checked above that layout is non-zero sized. |
| 93 | + let Some(allocation) = NonNull::new(unsafe { std::alloc::alloc_zeroed(layout) }) else { |
| 94 | + std::alloc::handle_alloc_error(layout); |
| 95 | + }; |
| 96 | + |
| 97 | + self.v.store(allocation.as_ptr(), Ordering::Release); |
| 98 | + |
| 99 | + allocation |
| 100 | + } |
| 101 | + |
| 102 | + fn bitset(ptr: NonNull<u8>, cap: usize) -> NonNull<[AtomicU8]> { |
| 103 | + NonNull::slice_from_raw_parts(ptr.cast(), cap.div_ceil(4)) |
| 104 | + } |
| 105 | + |
| 106 | + // SAFETY: Must be called on a `initialize`d `ptr` for this capacity. |
| 107 | + unsafe fn slice(ptr: NonNull<u8>, cap: usize) -> NonNull<[MaybeUninit<T>]> { |
| 108 | + let offset = Self::layout(cap).1; |
| 109 | + // SAFETY: Passed up to caller. |
| 110 | + NonNull::slice_from_raw_parts(unsafe { ptr.add(offset).cast() }, cap) |
| 111 | + } |
| 112 | + |
| 113 | + // idx is already compacted to within this slab |
| 114 | + fn get(&self, cap: usize, idx: usize) -> Option<&T> { |
| 115 | + // avoid initializing for get queries |
| 116 | + let Some(ptr) = NonNull::new(self.v.load(Ordering::Acquire)) else { |
| 117 | + return None; |
| 118 | + }; |
| 119 | + |
| 120 | + let bitset = unsafe { Self::bitset(ptr, cap).as_ref() }; |
| 121 | + |
| 122 | + // Check if the entry is initialized. |
| 123 | + // |
| 124 | + // Bottom 4 bits are the "is initialized" bits, top 4 bits are used for "is initializing" |
| 125 | + // lock. |
| 126 | + let word = bitset[idx / 4].load(Ordering::Acquire); |
| 127 | + if word & (1 << (idx % 4)) == 0 { |
| 128 | + return None; |
| 129 | + } |
| 130 | + |
| 131 | + // Avoid as_ref() since we don't want to assert shared refs to all slots (some are being |
| 132 | + // concurrently updated). |
| 133 | + // |
| 134 | + // SAFETY: `ptr` is only written by `initialize`, so this is safe. |
| 135 | + let slice = unsafe { Self::slice(ptr, cap) }; |
| 136 | + assert!(idx < slice.len()); |
| 137 | + // SAFETY: assertion above checks that we're in-bounds. |
| 138 | + let slot = unsafe { slice.cast::<T>().add(idx) }; |
| 139 | + |
| 140 | + // SAFETY: We checked `bitset` and this value was initialized. Our Acquire load |
| 141 | + // establishes the memory ordering with the release store which set the bit, so we're safe |
| 142 | + // to read it. |
| 143 | + Some(unsafe { slot.as_ref() }) |
| 144 | + } |
| 145 | + |
| 146 | + // idx is already compacted to within this slab |
| 147 | + fn insert(&self, cap: usize, idx: usize, value: T) -> Result<(), T> { |
| 148 | + // avoid initializing for get queries |
| 149 | + let ptr = self.initialize(cap); |
| 150 | + let bitset = unsafe { Self::bitset(ptr, cap).as_ref() }; |
| 151 | + |
| 152 | + // Check if the entry is initialized, and lock it for writing. |
| 153 | + let word = bitset[idx / 4].fetch_or(1 << (4 + idx % 4), Ordering::AcqRel); |
| 154 | + if word & (1 << (idx % 4)) != 0 { |
| 155 | + // Already fully initialized prior to us setting the "is writing" bit. |
| 156 | + return Err(value); |
| 157 | + } |
| 158 | + if word & (1 << (4 + idx % 4)) != 0 { |
| 159 | + // Someone else already acquired the lock for writing. |
| 160 | + return Err(value); |
| 161 | + } |
| 162 | + |
| 163 | + let slice = unsafe { Self::slice(ptr, cap) }; |
| 164 | + assert!(idx < slice.len()); |
| 165 | + // SAFETY: assertion above checks that we're in-bounds. |
| 166 | + let slot = unsafe { slice.cast::<T>().add(idx) }; |
| 167 | + |
| 168 | + // SAFETY: We locked this slot for writing with the fetch_or above, and were the first to do |
| 169 | + // so (checked in 2nd `if` above). |
| 170 | + unsafe { |
| 171 | + slot.write(value); |
| 172 | + } |
| 173 | + |
| 174 | + // Set the is-present bit, indicating that we have finished writing this value. |
| 175 | + // Acquire ensures we don't break synchronizes-with relationships in other bits (unclear if |
| 176 | + // strictly necessary but definitely doesn't hurt). |
| 177 | + bitset[idx / 4].fetch_or(1 << (idx % 4), Ordering::AcqRel); |
| 178 | + |
| 179 | + Ok(()) |
| 180 | + } |
| 181 | + |
| 182 | + /// Returns the layout for a Slab with capacity for `cap` elements, and the offset into the |
| 183 | + /// allocation at which the T slice starts. |
| 184 | + fn layout(cap: usize) -> (Layout, usize) { |
| 185 | + Layout::array::<AtomicU8>(cap.div_ceil(4)) |
| 186 | + .unwrap() |
| 187 | + .extend(Layout::array::<T>(cap).unwrap()) |
| 188 | + .unwrap() |
| 189 | + } |
| 190 | + |
| 191 | + // Drop, except passing the capacity |
| 192 | + unsafe fn deallocate(&mut self, cap: usize) { |
| 193 | + // avoid initializing just to Drop |
| 194 | + let Some(ptr) = NonNull::new(self.v.load(Ordering::Acquire)) else { |
| 195 | + return; |
| 196 | + }; |
| 197 | + |
| 198 | + if std::mem::needs_drop::<T>() { |
| 199 | + // SAFETY: `ptr` is only written by `initialize`, and zero-init'd so AtomicU8 is present in |
| 200 | + // the bitset range. |
| 201 | + let bitset = unsafe { Self::bitset(ptr, cap).as_ref() }; |
| 202 | + // SAFETY: `ptr` is only written by `initialize`, so satisfies slice precondition. |
| 203 | + let slice = unsafe { Self::slice(ptr, cap).cast::<T>() }; |
| 204 | + |
| 205 | + for (word_idx, word) in bitset.iter().enumerate() { |
| 206 | + let word = word.load(Ordering::Acquire); |
| 207 | + for word_offset in 0..4 { |
| 208 | + if word & (1 << word_offset) != 0 { |
| 209 | + // Was initialized, need to drop the value. |
| 210 | + let idx = word_idx * 4 + word_offset; |
| 211 | + unsafe { |
| 212 | + std::ptr::drop_in_place(slice.add(idx).as_ptr()); |
| 213 | + } |
| 214 | + } |
| 215 | + } |
| 216 | + } |
| 217 | + } |
| 218 | + |
| 219 | + let layout = Self::layout(cap).0; |
| 220 | + |
| 221 | + // SAFETY: Allocated with `alloc` and the same layout. |
| 222 | + unsafe { |
| 223 | + std::alloc::dealloc(ptr.as_ptr(), layout); |
| 224 | + } |
| 225 | + } |
| 226 | +} |
| 227 | + |
| 228 | +#[cfg(test)] |
| 229 | +mod test; |
0 commit comments