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
use std::mem::{transmute, size_of, transmute_copy, forget};
use std::ops::Deref;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::marker::PhantomData;
use std::marker::Sync;
use std::cell::Cell;
#[cfg(target_pointer_width = "32")]
const PTR_SIZE: usize = 4;
#[cfg(target_pointer_width = "64")]
const PTR_SIZE: usize = 8;
const MAX_WEIGHT_EXP: u8 = PTR_SIZE as u8 * 8 - 1;
const MAX_WEIGHT: usize = 1usize << MAX_WEIGHT_EXP;
pub struct Orc<'a, T: 'a> {
pointer_data: [u8; PTR_SIZE - 1],
weight_exp: Cell<u8>,
lifetime_and_type: PhantomData<&'a T>,
}
unsafe impl<'a, T> Sync for Orc<'a, T> {}
impl<'a, T> Drop for Orc<'a, T> {
fn drop(&mut self) {
let slot = construct_pointer::<T>(self.pointer_data, 0);
let weight = two_two_the(self.weight_exp.get());
slot.weight.fetch_sub(weight, Ordering::Release);
}
}
impl<'a, T> Clone for Orc<'a, T> {
fn clone(&self) -> Orc<'a, T> {
if self.weight_exp.get() > 1 {
self.weight_exp.set(self.weight_exp.get() - 1);
return Orc {
weight_exp: Cell::new(self.weight_exp.get()),
pointer_data: self.pointer_data,
lifetime_and_type: PhantomData,
};
}
panic!("not implemented yet");
}
}
impl<'a, T> Deref for Orc<'a, T> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &T {
let slot = construct_pointer::<T>(self.pointer_data, 0);
match slot.data {
Some(ref d) => d,
None => unreachable!(),
}
}
}
struct OrcInner<T> {
weight: AtomicUsize,
data: Option<T>,
}
pub struct OrcHeap<T> {
heap: Vec<OrcInner<T>>,
}
unsafe impl<'a, T> Sync for OrcHeap<T> {}
impl<'a, T> OrcHeap<T> {
pub fn new() -> OrcHeap<T> {
const DEFAULT_HEAP_SIZE: usize = 16;
OrcHeap::<T>::with_capacity(DEFAULT_HEAP_SIZE)
}
pub fn with_capacity(capacity: usize) -> OrcHeap<T> {
let mut heap = Vec::with_capacity(capacity);
for _ in 0..capacity {
heap.push(OrcInner {
weight: AtomicUsize::new(0),
data: None,
});
}
let (_, weight) = deconstruct_pointer(heap.iter().nth(capacity - 1).unwrap());
assert_eq!(weight, 0);
OrcHeap::<T> { heap: heap }
}
pub fn alloc(&'a self, value: T) -> Result<Orc<T>, &'static str> {
let mut position = 0;
loop {
unsafe {
let slot = self.heap.get_unchecked(position);
if slot.weight.compare_and_swap(0, MAX_WEIGHT, Ordering::Relaxed) == 0 {
let ref data: Option<T> = slot.data;
let mut_data: *mut Option<T> = hack_transmute(data);
*mut_data = Some(value);
let (pointer_data, _) = deconstruct_pointer(slot);
return Ok(Orc::<'a, T> {
pointer_data: pointer_data,
weight_exp: Cell::new(MAX_WEIGHT_EXP),
lifetime_and_type: PhantomData,
});
}
}
position += 1;
if position == self.heap.capacity() {
position = 0;
break;
}
}
Err("Out of memory")
}
pub fn collect(&'a self) {
for position in 0..self.heap.capacity() {
unsafe {
let slot = self.heap.get_unchecked(position);
if slot.weight.compare_and_swap(0, MAX_WEIGHT, Ordering::Relaxed) == 0 {
let ref data: Option<T> = slot.data;
let mut_data: *mut Option<T> = hack_transmute(data);
*mut_data = None;
}
}
}
}
}
#[inline(always)]
fn deconstruct_pointer<T>(p: &OrcInner<T>) -> ([u8; PTR_SIZE - 1], u8) {
unsafe {
let p: usize = transmute(p);
transmute(usize::from_le(p))
}
}
#[inline(always)]
fn construct_pointer<'a, T>(pointer: [u8; PTR_SIZE - 1], weight: u8) -> &'a OrcInner<T> {
unsafe {
let p: usize = transmute((pointer, weight));
transmute(usize::from_le(p))
}
}
#[inline(always)]
fn two_two_the(exp: u8) -> usize {
1usize << exp
}
#[inline(always)]
unsafe fn hack_transmute<T, U>(x: T) -> U {
debug_assert_eq!(size_of::<T>(), size_of::<U>());
let y = transmute_copy(&x);
forget(x);
y
}
#[test]
fn test_two_two_the() {
assert_eq!(two_two_the(0), 1);
assert_eq!(two_two_the(1), 2);
assert_eq!(two_two_the(8), 256);
}
#[cfg(test)]
mod test_drop {
use OrcHeap;
use std::cell::Cell;
struct DropTest<'a>(&'a Cell<usize>);
impl<'a> Drop for DropTest<'a> {
fn drop(&mut self) {
let v = self.0.get();
self.0.set(v - 1);
}
}
#[test]
#[allow(unused_variables)]
fn test_drop() {
let test_size = 1000;
let values_in_existence = Cell::new(test_size);
let heap = OrcHeap::with_capacity(test_size);
for _ in 0..test_size {
let o = heap.alloc(DropTest(&values_in_existence)).unwrap();
}
heap.collect();
assert_eq!(values_in_existence.get(), 0);
}
#[test]
#[allow(unused_variables)]
fn test_heap_freed() {
let test_size = 2;
let values_in_existence = Cell::new(5);
let heap = OrcHeap::with_capacity(test_size);
{
let a = heap.alloc(DropTest(&values_in_existence)).unwrap();
let b = heap.alloc(DropTest(&values_in_existence)).unwrap();
}
let c = heap.alloc(DropTest(&values_in_existence)).unwrap();
let d = heap.alloc(DropTest(&values_in_existence)).unwrap();
assert_eq!(values_in_existence.get(), 3);
assert!(heap.alloc(DropTest(&values_in_existence)).is_err())
}
}
#[cfg(test)]
mod test_concurrency {
extern crate crossbeam;
use OrcHeap;
#[test]
fn test_concurrency() {
extern crate crossbeam;
let test_size = 1000;
let heap = OrcHeap::with_capacity(test_size * 10);
crossbeam::scope(|scope| {
for _ in 0..test_size {
scope.spawn(|| {
for j in 0..test_size {
if let Ok(v) = heap.alloc(j) {
assert_eq!(*v, j);
}
}
});
}
});
}
}