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
use crate::loom::*;
use std::{
borrow::Borrow,
fmt::{Debug, Display, Formatter, Pointer, Result},
hash::{Hash, Hasher},
intrinsics::drop_in_place,
ops::Deref,
ptr::NonNull,
};
pub(crate) type RemovePtr<T> = fn(*const (), *const Interned<T>);
#[repr(C)]
struct RefCounted<T: ?Sized> {
refs: AtomicUsize,
remover: AtomicPtr<RemovePtr<T>>,
value: T,
}
impl<T: ?Sized> RefCounted<T> {
fn from_box(value: Box<T>) -> NonNull<Self> {
let layout = Layout::new::<RefCounted<()>>()
.extend(Layout::for_value(value.as_ref()))
.unwrap()
.0
.pad_to_align();
unsafe {
let ptr = alloc(layout);
let b = Box::leak(value) as *mut T;
let ptr = {
let mut temp = b as *mut Self;
std::ptr::write(&mut temp as *mut _ as *mut *mut u8, ptr);
temp
};
(*ptr).refs = AtomicUsize::new(1);
(*ptr).remover = AtomicPtr::new(std::ptr::null_mut());
let num_bytes = std::mem::size_of_val(&*b);
if num_bytes > 0 {
std::ptr::copy_nonoverlapping(
b as *const u8,
&mut (*ptr).value as *mut _ as *mut u8,
num_bytes,
);
#[cfg(not(loom))]
dealloc(b as *mut u8, Layout::for_value(&*b));
#[cfg(loom)]
std::alloc::dealloc(b as *mut u8, Layout::for_value(&*b));
}
NonNull::new_unchecked(ptr)
}
}
fn from_sized(value: T) -> NonNull<Self>
where
T: Sized,
{
let b = Box::new(Self {
refs: AtomicUsize::new(1),
remover: AtomicPtr::new(std::ptr::null_mut()),
value,
});
NonNull::from(Box::leak(b))
}
}
pub struct Interned<T: ?Sized> {
inner: NonNull<RefCounted<T>>,
}
unsafe impl<T: ?Sized + Sync + Send> Send for Interned<T> {}
unsafe impl<T: ?Sized + Sync + Send> Sync for Interned<T> {}
impl<T: ?Sized> Interned<T> {
pub fn ref_count(&self) -> usize {
self.inner().refs.load(Relaxed)
}
fn inner(&self) -> &RefCounted<T> {
unsafe { self.inner.as_ref() }
}
pub(crate) fn from_box(value: Box<T>) -> Self {
Self {
inner: RefCounted::from_box(value),
}
}
pub(crate) fn from_sized(value: T) -> Self
where
T: Sized,
{
Self {
inner: RefCounted::from_sized(value),
}
}
pub(crate) fn make_hot(&mut self, map: *mut RemovePtr<T>) -> bool {
let result =
self.inner()
.remover
.compare_exchange(std::ptr::null_mut(), map, Release, Relaxed);
#[cfg(test)]
{
if let Err(e) = result {
if e as *mut u8 == TAKEN {
println!("{:?} spurious make_hot for {:p}", current().id(), *self);
}
}
}
result.is_ok()
}
}
const MAX_REFCOUNT: usize = usize::MAX - 2;
const TAKEN: *mut u8 = std::mem::align_of::<RemovePtr<()>>() as *mut _;
impl<T: ?Sized> Clone for Interned<T> {
fn clone(&self) -> Self {
if self.inner().refs.fetch_add(1, Relaxed) >= MAX_REFCOUNT {
panic!("either you are running on an 8086 or you are leaking Interned values at a phantastic rate");
}
let ret = Self { inner: self.inner };
#[cfg(feature = "println")]
println!("{:?} clone {:p}", current().id(), *self);
ret
}
}
impl<T: ?Sized> Drop for Interned<T> {
fn drop(&mut self) {
#[cfg(feature = "println")]
println!("{:?} dropping {:p} {:p}", current().id(), self, *self);
let read = self.inner().refs.fetch_sub(1, Release);
#[cfg(feature = "println")]
println!("{:?} read {} {:p} {:p}", current().id(), read, self, *self);
if read > 2 {
return;
}
if read == 2 {
let remove_ptr = self.inner().remover.swap(TAKEN as *mut _, Acquire);
if remove_ptr as *mut u8 != TAKEN {
#[cfg(feature = "println")]
println!("{:?} remover {:p} {:p}", current().id(), self, *self);
let raw_arc = remove_ptr as *const ();
let remover = unsafe { *remove_ptr };
remover(raw_arc, self);
#[cfg(feature = "println")]
println!("{:?} removed {:p}", current().id(), self);
} else {
#[cfg(feature = "println")]
println!("{:?} second {:p}", current().id(), self);
}
} else if read == 1 {
let mut spin_count = 0;
loop {
let p = self.inner().remover.load(Relaxed) as *mut u8;
if p == TAKEN || p.is_null() {
break;
}
spin_count += 1;
if spin_count < 100 {
spin_loop_hint();
} else {
yield_now();
}
}
#[cfg(feature = "println")]
println!("{:?} drop {:p} {:p}", current().id(), self, *self);
assert!(self.inner().refs.load(Acquire) == 0);
let layout = Layout::for_value(self.inner());
unsafe {
drop_in_place(self.inner.as_ptr());
dealloc(self.inner.as_ptr() as *mut u8, layout);
}
}
#[cfg(feature = "println")]
println!("{:?} dropend {:p}", current().id(), self);
}
}
impl<T: ?Sized + PartialEq> PartialEq for Interned<T> {
fn eq(&self, other: &Self) -> bool {
self.inner().value.eq(&other.inner().value)
}
}
impl<T: ?Sized + Eq> Eq for Interned<T> {}
impl<T: ?Sized + PartialOrd> PartialOrd for Interned<T> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.inner().value.partial_cmp(&other.inner().value)
}
}
impl<T: ?Sized + Ord> Ord for Interned<T> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.inner().value.cmp(&other.inner().value)
}
}
impl<T: ?Sized + Hash> Hash for Interned<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.inner().value.hash(state)
}
}
impl<T: ?Sized> Borrow<T> for Interned<T> {
fn borrow(&self) -> &T {
&self.inner().value
}
}
impl<T: ?Sized> Deref for Interned<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.borrow()
}
}
impl<T: ?Sized> AsRef<T> for Interned<T> {
fn as_ref(&self) -> &T {
self.deref()
}
}
impl<T: ?Sized + Debug> Debug for Interned<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(f, "Interned({:?})", &*self)
}
}
impl<T: ?Sized + Display> Display for Interned<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
self.deref().fmt(f)
}
}
impl<T: ?Sized> Pointer for Interned<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
Pointer::fmt(&(&**self as *const T), f)
}
}
#[cfg(all(test, not(loom)))]
mod tests {
use crate::InternOrd;
#[test]
fn pointer() {
let interner = InternOrd::new();
let i = interner.intern_sized(42);
let i2 = i.clone();
assert_eq!(format!("{:p}", i), format!("{:p}", i2));
}
}