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
use crate::block::Block;
use crossbeam_utils::atomic::AtomicCell;
use std::{ptr::null_mut, sync::atomic::AtomicUsize};
#[derive(Clone)]
pub struct AllBlockList {
head: *mut Block,
}
impl AllBlockList {
pub fn new() -> Self {
Self { head: null_mut() }
}
pub fn push(&mut self, block: *mut Block) {
unsafe {
(*block).all_next = self.head;
self.head = block;
}
}
pub fn pop(&mut self) -> *mut Block {
unsafe {
if self.head.is_null() {
return null_mut();
}
let head = self.head;
self.head = (*head).all_next;
head
}
}
pub fn is_empty(&self) -> bool {
self.head.is_null()
}
}
#[derive(Clone)]
pub struct BlockList {
head: *mut Block,
}
impl BlockList {
pub fn new() -> Self {
Self { head: null_mut() }
}
pub fn for_each(&self, mut visitor: impl FnMut(*mut Block)) {
unsafe {
let mut head = self.head;
while !head.is_null() {
visitor(head);
head = (*head).next;
}
}
}
pub fn push(&mut self, block: *mut Block) {
unsafe {
(*block).next = self.head;
self.head = block;
}
}
pub fn pop(&mut self) -> *mut Block {
unsafe {
if self.head.is_null() {
return null_mut();
}
let head = self.head;
self.head = (*head).next;
head
}
}
pub fn is_empty(&self) -> bool {
self.head.is_null()
}
}
pub struct AtomicBlockList {
next: AtomicCell<*mut Block>,
count: AtomicUsize,
}
impl Clone for AtomicBlockList {
fn clone(&self) -> Self {
Self {
next: AtomicCell::new(null_mut()),
count: AtomicUsize::new(0),
}
}
}
impl AtomicBlockList {
pub fn new() -> Self {
Self {
count: AtomicUsize::new(0),
next: AtomicCell::new(null_mut()),
}
}
pub fn head(&self) -> *mut Block {
self.next.load()
}
pub unsafe fn add_free(&self, free: *mut Block) {
let new_slot = free;
let mut next = self.next.load();
loop {
debug_assert_ne!(new_slot, next);
(*new_slot).next = next;
match self.next.compare_exchange(next, new_slot) {
Ok(_) => {
self.count.fetch_add(1, atomic::Ordering::AcqRel);
return;
}
Err(actual_next) => {
next = actual_next;
}
}
}
}
#[inline]
pub fn take_free(&self) -> *mut Block {
loop {
unsafe {
let next_free = match self.next.load() {
x if x.is_null() => return null_mut(),
x => x,
};
debug_assert_ne!(next_free, (*next_free).next);
if self
.next
.compare_exchange(next_free, (*next_free).next)
.is_err()
{
continue;
}
self.count.fetch_sub(1, atomic::Ordering::AcqRel);
return next_free;
}
}
}
#[inline]
pub fn count(&self) -> usize {
self.count.load(atomic::Ordering::Acquire)
}
}