1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//! [`Bag`] is a lock-free concurrent unordered instance container.
use super::ebr::Barrier;
use super::{LinkedList, Stack};
use std::mem::{needs_drop, MaybeUninit};
use std::ptr::drop_in_place;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::{Acquire, Relaxed, Release};
/// The length of the fixed-size array in a [`Bag`].
const STORAGE_LEN: u32 = usize::BITS / 2;
/// [`Bag`] is a lock-free concurrent unordered instance container.
///
/// [`Bag`] is a linearizable concurrent instance container where `usize::BITS / 2` instances are
/// stored in a fixed-size array, and the rest are managed by its backup container which makes a
/// [`Bag`] especially efficient if the expected number of instances does not exceed
/// `usize::BITS / 2`.
#[derive(Debug)]
pub struct Bag<T> {
/// Primary storage.
primary_storage: Storage<T>,
/// Fallback storage.
stack: Stack<Storage<T>>,
}
impl<T> Bag<T> {
/// Pushes an instance of `T`.
///
/// # Examples
///
/// ```
/// use scc::Bag;
///
/// let bag: Bag<usize> = Bag::default();
///
/// bag.push(11);
/// ```
#[inline]
pub fn push(&self, val: T) {
if let Some(val) = self.primary_storage.push(val, true) {
self.stack.peek(|e| {
if let Some(storage) = e {
if let Some(val) = storage.push(val, false) {
unsafe {
self.stack.push_unchecked(Storage::with_val(val));
}
}
} else {
unsafe {
self.stack.push_unchecked(Storage::with_val(val));
}
}
});
}
}
/// Pops an instance in the [`Bag`] if not empty.
///
/// # Examples
///
/// ```
/// use scc::Bag;
///
/// let bag: Bag<usize> = Bag::default();
///
/// bag.push(37);
///
/// assert_eq!(bag.pop(), Some(37));
/// assert!(bag.pop().is_none());
/// ```
#[inline]
pub fn pop(&self) -> Option<T> {
let barrier = Barrier::new();
self.stack.peek(|e| {
let mut current = e;
while let Some(storage) = current {
let (val_opt, empty) = storage.pop();
if empty {
storage.delete_self(Relaxed);
}
if let Some(val) = val_opt {
return Some(val);
}
current = storage.next_ptr(Acquire, &barrier).as_ref();
}
self.primary_storage.pop().0
})
}
/// Returns `true` if the [`Bag`] is empty.
///
/// # Examples
///
/// ```
/// use scc::Bag;
///
/// let bag: Bag<usize> = Bag::default();
/// assert!(bag.is_empty());
///
/// bag.push(7);
/// assert!(!bag.is_empty());
///
/// assert_eq!(bag.pop(), Some(7));
/// assert!(bag.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
if self.primary_storage.is_empty() {
self.stack.is_empty()
} else {
false
}
}
}
impl<T> Default for Bag<T> {
#[inline]
fn default() -> Self {
Self {
primary_storage: Storage::new(),
stack: Stack::default(),
}
}
}
impl<T> Drop for Bag<T> {
#[inline]
fn drop(&mut self) {
if needs_drop::<T>() {
// It needs to drop all the stored instances in-place.
while let Some(v) = self.pop() {
drop(v);
}
}
}
}
#[derive(Debug)]
struct Storage<T> {
/// Storage.
storage: [MaybeUninit<T>; STORAGE_LEN as usize],
/// Storage metadata.
///
/// The layout of the metadata is,
/// - Upper `usize::BITS / 2` bits = instantiation bitmap.
/// - Lower `usize::BITS / 2` bits = owned state bitmap.
///
/// The metadata represents four possible states of a storage slot.
/// - !instantiated && !owned: initial state.
/// - !instantiated && owned: owned for instantiating.
/// - instantiated && !owned: valid and reachable.
/// - instantiated && owned: owned for moving out the instance.
metadata: AtomicUsize,
}
impl<T> Storage<T> {
/// Creates a new [`Storage`].
fn new() -> Storage<T> {
#[allow(clippy::uninit_assumed_init)]
Storage {
storage: unsafe { MaybeUninit::uninit().assume_init() },
metadata: AtomicUsize::new(0),
}
}
/// Creates a new [`Storage`] with one inserted.
fn with_val(val: T) -> Storage<T> {
#[allow(clippy::uninit_assumed_init)]
let mut storage = Storage::<T> {
storage: unsafe { MaybeUninit::uninit().assume_init() },
metadata: AtomicUsize::new(1_usize << STORAGE_LEN),
};
unsafe {
storage.storage[0].as_mut_ptr().write(val);
}
storage
}
/// Pushes a new value.
fn push(&self, val: T, allow_empty: bool) -> Option<T> {
let mut metadata = self.metadata.load(Relaxed);
'after_read_metadata: loop {
// Looking for a free slot.
let mut instance_bitmap = Self::instance_bitmap(metadata);
if !allow_empty && instance_bitmap == 0 {
return Some(val);
}
let owned_bitmap = Self::owned_bitmap(metadata);
let mut index = instance_bitmap.trailing_ones();
while index != STORAGE_LEN {
debug_assert!(index < STORAGE_LEN);
if (owned_bitmap & (1_u32 << index)) == 0 {
// Mark the slot `owned`.
let new = metadata | (1_usize << index);
match self
.metadata
.compare_exchange(metadata, new, Acquire, Relaxed)
{
Ok(_) => {
// Now the free slot is owned by the thread.
unsafe {
(self.storage[index as usize].as_ptr() as *mut T).write(val);
}
let result = self.metadata.fetch_update(Release, Relaxed, |m| {
debug_assert_ne!(m & (1_usize << index), 0);
debug_assert_eq!(m & (1_usize << (index + STORAGE_LEN)), 0);
if !allow_empty && Self::instance_bitmap(m) == 0 {
// Disallowed to push a value into an empty array.
None
} else {
let new = (m & (!(1_usize << index)))
| (1_usize << (index + STORAGE_LEN));
Some(new)
}
});
if result.is_ok() {
return None;
}
// The array was empty, thus rolling back the change.
let val = unsafe { self.storage[index as usize].as_ptr().read() };
self.metadata.fetch_and(!(1_usize << index), Relaxed);
return Some(val);
}
Err(prev) => {
// Metadata has changed.
metadata = prev;
continue 'after_read_metadata;
}
}
}
// Looking for another free slot.
instance_bitmap |= 1_u32 << index;
index = instance_bitmap.trailing_ones();
}
// No free slots or all the entries are owned.
return Some(val);
}
}
/// Pops a value.
fn pop(&self) -> (Option<T>, bool) {
let mut metadata = self.metadata.load(Relaxed);
'after_read_metadata: loop {
// Looking for an instantiated, yet unowned entry.
let instance_bitmap = Self::instance_bitmap(metadata);
let owned_bitmap = Self::owned_bitmap(metadata);
let mut index = instance_bitmap.trailing_zeros();
while index != 32 {
debug_assert!(index < STORAGE_LEN);
if (owned_bitmap & (1_u32 << index)) == 0 {
// Mark the slot `owned`.
let new = metadata | (1_usize << index);
match self
.metadata
.compare_exchange(metadata, new, Acquire, Relaxed)
{
Ok(_) => {
// Now the desired slot is owned by the thread.
let inst = unsafe { self.storage[index as usize].as_ptr().read() };
let mut empty = false;
let result = self.metadata.fetch_update(Relaxed, Relaxed, |m| {
debug_assert_ne!(m & (1_usize << index), 0);
debug_assert_ne!(m & (1_usize << (index + STORAGE_LEN)), 0);
let new = m
& (!((1_usize << index) | (1_usize << (index + STORAGE_LEN))));
empty = Self::instance_bitmap(new) == 0;
Some(new)
});
debug_assert!(result.is_ok());
return (Some(inst), empty);
}
Err(prev) => {
// Metadata has changed.
metadata = prev;
continue 'after_read_metadata;
}
}
}
// Looking for another valid slot.
index = (instance_bitmap & (u32::MAX.wrapping_shl(index).wrapping_shl(1)))
.trailing_zeros();
}
// All the entries are vacant or owned.
return (None, instance_bitmap == 0);
}
}
/// Returns `true` if empty.
fn is_empty(&self) -> bool {
let metadata = self.metadata.load(Acquire);
Self::instance_bitmap(metadata) == 0
}
#[allow(clippy::cast_possible_truncation)]
fn instance_bitmap(metadata: usize) -> u32 {
metadata.wrapping_shr(STORAGE_LEN) as u32
}
#[allow(clippy::cast_possible_truncation)]
fn owned_bitmap(metadata: usize) -> u32 {
(metadata % (1_usize << STORAGE_LEN)) as u32
}
}
impl<T> Drop for Storage<T> {
#[inline]
fn drop(&mut self) {
if needs_drop::<T>() {
let mut instance_bitmap = Self::instance_bitmap(self.metadata.load(Acquire));
loop {
let index = instance_bitmap.trailing_zeros();
if index == 32 {
break;
}
instance_bitmap &= !(1_u32 << index);
unsafe { drop_in_place(self.storage[index as usize].as_mut_ptr()) };
}
}
}
}