-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathboxcar.rs
597 lines (527 loc) · 19.5 KB
/
boxcar.rs
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! Adapted from the `boxcar` crate at <https://github.com/ibraheemdev/boxcar/blob/master/src/raw.rs>
//! under MIT licenes:
//!
//! Copyright (c) 2022 Ibraheem Ahmed
//!
//! Permission is hereby granted, free of charge, to any person obtaining a copy
//! of this software and associated documentation files (the "Software"), to deal
//! in the Software without restriction, including without limitation the rights
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//! copies of the Software, and to permit persons to whom the Software is
//! furnished to do so, subject to the following conditions:
//!
//! The above copyright notice and this permission notice shall be included in all
//! copies or substantial portions of the Software.
//!
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//! SOFTWARE.
use std::alloc::Layout;
use std::cell::UnsafeCell;
use std::mem::MaybeUninit;
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering};
use std::{ptr, slice};
use crate::{Item, Utf32String};
const BUCKETS: u32 = u32::BITS - SKIP_BUCKET;
const MAX_ENTRIES: u32 = u32::MAX - SKIP;
/// A lock-free, append-only vector.
pub(crate) struct Vec<T> {
/// a counter used to retrieve a unique index to push to.
///
/// this value may be more than the true length as it will
/// be incremented before values are actually stored.
inflight: AtomicU64,
/// buckets of length 32, 64 .. 2^31
buckets: [Bucket<T>; BUCKETS as usize],
/// the number of matcher columns in this vector, its absolutely critical that
/// this remains constant and after initilaziaton (safety invariant) since
/// it is used to calculate the Entry layout
columns: u32,
}
impl<T> Vec<T> {
/// Constructs a new, empty `Vec<T>` with the specified capacity and matcher columns.
pub fn with_capacity(capacity: u32, columns: u32) -> Vec<T> {
assert_ne!(columns, 0, "there must be atleast one matcher column");
let init = match capacity {
0 => 0,
// initialize enough buckets for `capacity` elements
n => Location::of(n).bucket,
};
let mut buckets = [ptr::null_mut(); BUCKETS as usize];
for (i, bucket) in buckets[..=init as usize].iter_mut().enumerate() {
let len = Location::bucket_len(i as u32);
*bucket = unsafe { Bucket::alloc(len, columns) };
}
Vec {
buckets: buckets.map(Bucket::new),
inflight: AtomicU64::new(0),
columns,
}
}
pub fn columns(&self) -> u32 {
self.columns
}
/// Returns the number of elements in the vector.
#[inline]
pub fn count(&self) -> u32 {
self.inflight
.load(Ordering::Acquire)
.min(MAX_ENTRIES as u64) as u32
}
// Returns a reference to the element at the given index.
//
// # Safety
//
// Entry at `index` must be initialized.
#[inline]
pub unsafe fn get_unchecked(&self, index: u32) -> Item<'_, T> {
let location = Location::of(index);
unsafe {
let entries = self
.buckets
.get_unchecked(location.bucket as usize)
.entries
.load(Ordering::Relaxed);
debug_assert!(!entries.is_null());
let entry = Bucket::<T>::get(entries, location.entry, self.columns);
// this looks odd but is necessary to ensure cross
// thread synchronization (essentially acting as a memory barrier)
// since the caller must only guarantee that he has observed active on any thread
// but the current thread might still have an old value cached (although unlikely)
let _ = (*entry).active.load(Ordering::Acquire);
Entry::read(entry, self.columns)
}
}
/// Returns a reference to the element at the given index.
pub fn get(&self, index: u32) -> Option<Item<'_, T>> {
let location = Location::of(index);
unsafe {
// safety: `location.bucket` is always in bounds
let entries = self
.buckets
.get_unchecked(location.bucket as usize)
.entries
.load(Ordering::Relaxed);
// bucket is uninitialized
if entries.is_null() {
return None;
}
// safety: `location.entry` is always in bounds for it's bucket
let entry = Bucket::<T>::get(entries, location.entry, self.columns);
// safety: the entry is active
(*entry)
.active
.load(Ordering::Acquire)
.then(|| Entry::read(entry, self.columns))
}
}
/// Appends an element to the back of the vector.
pub fn push(&self, value: T, fill_columns: impl FnOnce(&T, &mut [Utf32String])) -> u32 {
let index = self.inflight.fetch_add(1, Ordering::Release);
// the inflight counter is a `u64` to catch overflows of the vector'scapacity
let index: u32 = index.try_into().expect("overflowed maximum capacity");
let location = Location::of(index);
// eagerly allocate the next bucket if we are close to the end of this one
if index == (location.bucket_len - (location.bucket_len >> 3)) {
if let Some(next_bucket) = self.buckets.get(location.bucket as usize + 1) {
Vec::get_or_alloc(next_bucket, location.bucket_len << 1, self.columns);
}
}
// safety: `location.bucket` is always in bounds
let bucket = unsafe { self.buckets.get_unchecked(location.bucket as usize) };
let mut entries = bucket.entries.load(Ordering::Acquire);
// the bucket has not been allocated yet
if entries.is_null() {
entries = Vec::get_or_alloc(bucket, location.bucket_len, self.columns);
}
unsafe {
// safety: `location.entry` is always in bounds for it's bucket
let entry = Bucket::get(entries, location.entry, self.columns);
// safety: we have unique access to this entry.
//
// 1. it is impossible for another thread to attempt a `push`
// to this location as we retrieved it from `inflight.fetch_add`
//
// 2. any thread trying to `get` this entry will see `active == false`,
// and will not try to access it
for col in Entry::matcher_cols_raw(entry, self.columns) {
col.get().write(MaybeUninit::new(Utf32String::default()))
}
fill_columns(&value, Entry::matcher_cols_mut(entry, self.columns));
(*entry).slot.get().write(MaybeUninit::new(value));
// let other threads know that this entry is active
(*entry).active.store(true, Ordering::Release);
}
index
}
/// race to initialize a bucket
fn get_or_alloc(bucket: &Bucket<T>, len: u32, cols: u32) -> *mut Entry<T> {
let entries = unsafe { Bucket::alloc(len, cols) };
match bucket.entries.compare_exchange(
ptr::null_mut(),
entries,
Ordering::Release,
Ordering::Acquire,
) {
Ok(_) => entries,
Err(found) => unsafe {
Bucket::dealloc(entries, len, cols);
found
},
}
}
/// Returns an iterator over the vector starting at `start`
/// the iterator is deterministically sized and will not grow
/// as more elements are pushed
pub unsafe fn snapshot(&self, start: u32) -> Iter<'_, T> {
let end = self
.inflight
.load(Ordering::Acquire)
.min(MAX_ENTRIES as u64) as u32;
assert!(start <= end, "index {start} is out of bounds!");
Iter {
location: Location::of(start),
vec: self,
idx: start,
end,
}
}
/// Returns an iterator over the vector starting at `start`
/// the iterator is deterministically sized and will not grow
/// as more elements are pushed
pub unsafe fn par_snapshot(&self, start: u32) -> ParIter<'_, T> {
let end = self
.inflight
.load(Ordering::Acquire)
.min(MAX_ENTRIES as u64) as u32;
assert!(start <= end, "index {start} is out of bounds!");
ParIter {
start,
end,
vec: self,
}
}
}
impl<T> Drop for Vec<T> {
fn drop(&mut self) {
for (i, bucket) in self.buckets.iter_mut().enumerate() {
let entries = *bucket.entries.get_mut();
if entries.is_null() {
break;
}
let len = Location::bucket_len(i as u32);
// safety: in drop
unsafe { Bucket::dealloc(entries, len, self.columns) }
}
}
}
type SnapshotItem<'v, T> = (u32, Option<Item<'v, T>>);
pub struct Iter<'v, T> {
location: Location,
idx: u32,
end: u32,
vec: &'v Vec<T>,
}
impl<T> Iter<'_, T> {
pub fn end(&self) -> u32 {
self.end
}
}
impl<'v, T> Iterator for Iter<'v, T> {
type Item = SnapshotItem<'v, T>;
fn size_hint(&self) -> (usize, Option<usize>) {
(
(self.end - self.idx) as usize,
Some((self.end - self.idx) as usize),
)
}
fn next(&mut self) -> Option<SnapshotItem<'v, T>> {
if self.end == self.idx {
return None;
}
debug_assert!(self.idx < self.end, "huh {} {}", self.idx, self.end);
debug_assert!(self.end as u64 <= self.vec.inflight.load(Ordering::Relaxed));
loop {
let entries = unsafe {
self.vec
.buckets
.get_unchecked(self.location.bucket as usize)
.entries
.load(Ordering::Relaxed)
};
debug_assert!(self.location.bucket < BUCKETS);
if self.location.entry < self.location.bucket_len {
if entries.is_null() {
// we still want to yield these
let index = self.idx;
self.location.entry += 1;
self.idx += 1;
return Some((index, None));
}
// safety: bounds and null checked above
let entry = unsafe { Bucket::get(entries, self.location.entry, self.vec.columns) };
let index = self.idx;
self.location.entry += 1;
self.idx += 1;
let entry = unsafe {
(*entry)
.active
.load(Ordering::Acquire)
.then(|| Entry::read(entry, self.vec.columns))
};
return Some((index, entry));
}
self.location.entry = 0;
self.location.bucket += 1;
if self.location.bucket < BUCKETS {
self.location.bucket_len = Location::bucket_len(self.location.bucket);
}
}
}
}
impl<T> ExactSizeIterator for Iter<'_, T> {}
impl<T> DoubleEndedIterator for Iter<'_, T> {
fn next_back(&mut self) -> Option<Self::Item> {
unimplemented!()
}
}
pub struct ParIter<'v, T> {
end: u32,
start: u32,
vec: &'v Vec<T>,
}
impl<T> ParIter<'_, T> {
pub fn end(&self) -> u32 {
self.end
}
}
impl<'v, T: Send + Sync> rayon::iter::ParallelIterator for ParIter<'v, T> {
type Item = SnapshotItem<'v, T>;
fn drive_unindexed<C>(self, consumer: C) -> C::Result
where
C: rayon::iter::plumbing::UnindexedConsumer<Self::Item>,
{
rayon::iter::plumbing::bridge(self, consumer)
}
fn opt_len(&self) -> Option<usize> {
Some((self.end - self.start) as usize)
}
}
impl<T: Send + Sync> rayon::iter::IndexedParallelIterator for ParIter<'_, T> {
fn len(&self) -> usize {
(self.end - self.start) as usize
}
fn drive<C: rayon::iter::plumbing::Consumer<Self::Item>>(self, consumer: C) -> C::Result {
rayon::iter::plumbing::bridge(self, consumer)
}
fn with_producer<CB>(self, callback: CB) -> CB::Output
where
CB: rayon::iter::plumbing::ProducerCallback<Self::Item>,
{
callback.callback(ParIterProducer {
start: self.start,
end: self.end,
vec: self.vec,
})
}
}
struct ParIterProducer<'v, T: Send> {
start: u32,
end: u32,
vec: &'v Vec<T>,
}
impl<'v, T: 'v + Send + Sync> rayon::iter::plumbing::Producer for ParIterProducer<'v, T> {
type Item = SnapshotItem<'v, T>;
type IntoIter = Iter<'v, T>;
fn into_iter(self) -> Self::IntoIter {
debug_assert!(self.start <= self.end);
Iter {
location: Location::of(self.start),
idx: self.start,
end: self.end,
vec: self.vec,
}
}
fn split_at(self, index: usize) -> (Self, Self) {
assert!(index <= (self.end - self.start) as usize);
let index = index as u32;
(
ParIterProducer {
start: self.start,
end: self.start + index,
vec: self.vec,
},
ParIterProducer {
start: self.start + index,
end: self.end,
vec: self.vec,
},
)
}
}
struct Bucket<T> {
entries: AtomicPtr<Entry<T>>,
}
impl<T> Bucket<T> {
fn layout(len: u32, layout: Layout) -> Layout {
Layout::from_size_align(layout.size() * len as usize, layout.align())
.expect("exceeded maximum allocation size")
}
unsafe fn alloc(len: u32, cols: u32) -> *mut Entry<T> {
let layout = Entry::<T>::layout(cols);
let arr_layout = Self::layout(len, layout);
let entries = std::alloc::alloc(arr_layout);
if entries.is_null() {
std::alloc::handle_alloc_error(arr_layout)
}
for i in 0..len {
let active = entries.add(i as usize * layout.size()) as *mut AtomicBool;
active.write(AtomicBool::new(false))
}
entries as *mut Entry<T>
}
unsafe fn dealloc(entries: *mut Entry<T>, len: u32, cols: u32) {
let layout = Entry::<T>::layout(cols);
let arr_layout = Self::layout(len, layout);
for i in 0..len {
let entry = Bucket::get(entries, i, cols);
if *(*entry).active.get_mut() {
ptr::drop_in_place((*(*entry).slot.get()).as_mut_ptr());
for matcher_col in Entry::matcher_cols_raw(entry, cols) {
ptr::drop_in_place((*matcher_col.get()).as_mut_ptr());
}
}
}
std::alloc::dealloc(entries as *mut u8, arr_layout)
}
unsafe fn get(entries: *mut Entry<T>, idx: u32, cols: u32) -> *mut Entry<T> {
let layout = Entry::<T>::layout(cols);
let ptr = entries as *mut u8;
ptr.add(layout.size() * idx as usize) as *mut Entry<T>
}
fn new(entries: *mut Entry<T>) -> Bucket<T> {
Bucket {
entries: AtomicPtr::new(entries),
}
}
}
#[repr(C)]
struct Entry<T> {
active: AtomicBool,
slot: UnsafeCell<MaybeUninit<T>>,
tail: [UnsafeCell<MaybeUninit<Utf32String>>; 0],
}
impl<T> Entry<T> {
fn layout(cols: u32) -> Layout {
let head = Layout::new::<Self>();
let tail = Layout::array::<Utf32String>(cols as usize).expect("invalid memory layout");
head.extend(tail)
.expect("invalid memory layout")
.0
.pad_to_align()
}
unsafe fn matcher_cols_raw<'a>(
ptr: *mut Entry<T>,
cols: u32,
) -> &'a [UnsafeCell<MaybeUninit<Utf32String>>] {
// this whole thing looks weird. The reason we do this is that
// we must make sure the pointer retains its provenance which may (or may not?)
// be lost if we used tail.as_ptr()
let tail = std::ptr::addr_of!((*ptr).tail) as *const u8;
let offset = tail.offset_from(ptr as *mut u8) as usize;
let ptr = (ptr as *mut u8).add(offset) as *mut _;
slice::from_raw_parts(ptr, cols as usize)
}
unsafe fn matcher_cols_mut<'a>(ptr: *mut Entry<T>, cols: u32) -> &'a mut [Utf32String] {
// this whole thing looks weird. The reason we do this is that
// we must make sure the pointer retains its provenance which may (or may not?)
// be lost if we used tail.as_ptr()
let tail = std::ptr::addr_of!((*ptr).tail) as *const u8;
let offset = tail.offset_from(ptr as *mut u8) as usize;
let ptr = (ptr as *mut u8).add(offset) as *mut _;
slice::from_raw_parts_mut(ptr, cols as usize)
}
// # Safety
//
// Value must be initialized.
unsafe fn read<'a>(ptr: *mut Entry<T>, cols: u32) -> Item<'a, T> {
// this whole thing looks weird. The reason we do this is that
// we must make sure the pointer retains its provenance which may (or may not?)
// be lost if we used tail.as_ptr()
let data = (*(*ptr).slot.get()).assume_init_ref();
let tail = std::ptr::addr_of!((*ptr).tail) as *const u8;
let offset = tail.offset_from(ptr as *mut u8) as usize;
let ptr = (ptr as *mut u8).add(offset) as *mut _;
let matcher_columns = slice::from_raw_parts(ptr, cols as usize);
Item {
data,
matcher_columns,
}
}
}
#[derive(Debug)]
struct Location {
// the index of the bucket
bucket: u32,
// the length of `bucket`
bucket_len: u32,
// the index of the entry in `bucket`
entry: u32,
}
// skip the shorter buckets to avoid unnecessary allocations.
// this also reduces the maximum capacity of a vector.
const SKIP: u32 = 32;
const SKIP_BUCKET: u32 = (u32::BITS - SKIP.leading_zeros()) - 1;
impl Location {
fn of(index: u32) -> Location {
let skipped = index.checked_add(SKIP).expect("exceeded maximum length");
let bucket = u32::BITS - skipped.leading_zeros();
let bucket = bucket - (SKIP_BUCKET + 1);
let bucket_len = Location::bucket_len(bucket);
let entry = skipped ^ bucket_len;
Location {
bucket,
bucket_len,
entry,
}
}
fn bucket_len(bucket: u32) -> u32 {
1 << (bucket + SKIP_BUCKET)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn location() {
assert_eq!(Location::bucket_len(0), 32);
for i in 0..32 {
let loc = Location::of(i);
assert_eq!(loc.bucket_len, 32);
assert_eq!(loc.bucket, 0);
assert_eq!(loc.entry, i);
}
assert_eq!(Location::bucket_len(1), 64);
for i in 33..96 {
let loc = Location::of(i);
assert_eq!(loc.bucket_len, 64);
assert_eq!(loc.bucket, 1);
assert_eq!(loc.entry, i - 32);
}
assert_eq!(Location::bucket_len(2), 128);
for i in 96..224 {
let loc = Location::of(i);
assert_eq!(loc.bucket_len, 128);
assert_eq!(loc.bucket, 2);
assert_eq!(loc.entry, i - 96);
}
let max = Location::of(MAX_ENTRIES);
assert_eq!(max.bucket, BUCKETS - 1);
assert_eq!(max.bucket_len, 1 << 31);
assert_eq!(max.entry, (1 << 31) - 1);
}
}