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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//! [`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};
/// [`Bag`] is a lock-free concurrent unordered instance container.
///
/// [`Bag`] is a linearizable concurrent instance container where `ARRAY_LEN` instances are stored
/// in a fixed-size array, and the rest are managed by its backup container; this makes a [`Bag`]
/// especially efficient if the expected number of instances does not exceed `ARRAY_LEN`.
///
/// The maximum value of `ARRAY_LEN` is limited to `usize::MAX / 2` which is the default value, and
/// if a larger value is specified, [`Bag::new`] panics.
#[derive(Debug)]
pub struct Bag<T, const ARRAY_LEN: usize = DEFAULT_ARRAY_LEN> {
/// Primary storage.
primary_storage: Storage<T, ARRAY_LEN>,
/// Fallback storage.
stack: Stack<Storage<T, ARRAY_LEN>>,
}
/// The default length of the fixed-size array in a [`Bag`].
const DEFAULT_ARRAY_LEN: usize = usize::BITS as usize / 2;
impl<T, const ARRAY_LEN: usize> Bag<T, ARRAY_LEN> {
/// Creates a new [`Bag`].
///
/// # Panics
///
/// Panics if the specified `ARRAY_LEN` value is larger than `usize::BITS / 2`.
///
/// # Examples
///
/// ```
/// use scc::Bag;
///
/// let bag: Bag<usize, 16> = Bag::new();
/// ```
#[inline]
#[must_use]
pub fn new() -> Bag<T, ARRAY_LEN> {
assert!(ARRAY_LEN <= DEFAULT_ARRAY_LEN);
Self {
primary_storage: Storage::new(),
stack: Stack::default(),
}
}
/// 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, DEFAULT_ARRAY_LEN> {
#[inline]
fn default() -> Self {
Self {
primary_storage: Storage::new(),
stack: Stack::default(),
}
}
}
impl<T, const ARRAY_LEN: usize> Drop for Bag<T, ARRAY_LEN> {
#[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, const ARRAY_LEN: usize> {
/// Storage.
storage: [MaybeUninit<T>; ARRAY_LEN],
/// 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, const ARRAY_LEN: usize> Storage<T, ARRAY_LEN> {
/// Creates a new [`Storage`].
fn new() -> Storage<T, ARRAY_LEN> {
#[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, ARRAY_LEN> {
#[allow(clippy::uninit_assumed_init)]
let mut storage = Storage::<T, ARRAY_LEN> {
storage: unsafe { MaybeUninit::uninit().assume_init() },
metadata: AtomicUsize::new(1_usize << ARRAY_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() as usize;
while index < ARRAY_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_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 + ARRAY_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 + ARRAY_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_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() as usize;
}
// 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() as usize;
while index < ARRAY_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_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 + ARRAY_LEN)), 0);
let new =
m & (!((1_usize << index) | (1_usize << (index + ARRAY_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.
{
#![allow(clippy::cast_possible_truncation)]
index = (instance_bitmap
& (u32::MAX.wrapping_shl(index as u32).wrapping_shl(1)))
.trailing_zeros() as usize;
}
}
// 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(ARRAY_LEN as u32) as u32
}
#[allow(clippy::cast_possible_truncation)]
fn owned_bitmap(metadata: usize) -> u32 {
(metadata % (1_usize << ARRAY_LEN)) as u32
}
}
impl<T, const ARRAY_LEN: usize> Drop for Storage<T, ARRAY_LEN> {
#[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()) };
}
}
}
}