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
use super::*;
use core::convert::TryInto;
use core::sync::atomic::AtomicU32;
use std::sync::atomic::Ordering;
pub unsafe trait VTableMetaDropInPlace: VTableMeta {
unsafe fn drop_in_place(vtable: &Self::VTable, ptr: *mut u8) -> vrc::Layout;
unsafe fn dealloc(vtable: &Self::VTable, ptr: *mut u8, layout: vrc::Layout);
}
pub struct Dyn(());
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Layout {
pub size: usize,
pub align: usize,
}
impl From<core::alloc::Layout> for Layout {
fn from(layout: core::alloc::Layout) -> Self {
Self { size: layout.size(), align: layout.align() }
}
}
impl core::convert::TryFrom<Layout> for core::alloc::Layout {
type Error = core::alloc::LayoutError;
fn try_from(value: Layout) -> Result<Self, Self::Error> {
Self::from_size_align(value.size, value.align)
}
}
#[repr(C)]
struct VRcInner<'vt, VTable: VTableMeta, X> {
vtable: &'vt VTable::VTable,
strong_ref: AtomicU32,
weak_ref: AtomicU32,
data_offset: u16,
data: X,
}
impl<'vt, VTable: VTableMeta, X> VRcInner<'vt, VTable, X> {
fn data_ptr(&self) -> *const X {
let ptr = self as *const Self as *const u8;
unsafe { ptr.add(self.data_offset as usize) as *const X }
}
fn as_ref(&self) -> &X {
let ptr = self as *const Self as *const u8;
unsafe { &*(ptr.add(self.data_offset as usize) as *const X) }
}
}
#[repr(transparent)]
pub struct VRc<VTable: VTableMetaDropInPlace + 'static, X = Dyn> {
inner: NonNull<VRcInner<'static, VTable, X>>,
}
impl<VTable: VTableMetaDropInPlace + 'static, X> Drop for VRc<VTable, X> {
fn drop(&mut self) {
unsafe {
let inner = self.inner.as_ref();
if inner.strong_ref.fetch_sub(1, Ordering::SeqCst) == 1 {
let data = inner.data_ptr() as *const _ as *const u8 as *mut u8;
let mut layout = VTable::drop_in_place(inner.vtable, data);
layout = core::alloc::Layout::new::<VRcInner<VTable, ()>>()
.extend(layout.try_into().unwrap())
.unwrap()
.0
.pad_to_align()
.into();
if inner.weak_ref.load(Ordering::SeqCst) > 1 {
self.inner.cast::<VRcInner<VTable, Layout>>().as_mut().data = layout;
}
if inner.weak_ref.fetch_sub(1, Ordering::SeqCst) == 1 {
let vtable = inner.vtable;
VTable::dealloc(vtable, self.inner.cast().as_ptr(), layout);
}
}
}
}
}
impl<VTable: VTableMetaDropInPlace, X: HasStaticVTable<VTable>> VRc<VTable, X> {
pub fn new(data: X) -> Self {
let layout = core::alloc::Layout::new::<VRcInner<VTable, X>>().pad_to_align();
let layout_with_layout = core::alloc::Layout::new::<VRcInner<VTable, Layout>>();
let layout = core::alloc::Layout::from_size_align(
layout.size().max(layout_with_layout.size()),
layout.align().max(layout_with_layout.align()),
)
.unwrap();
let mem = unsafe { std::alloc::alloc(layout) as *mut VRcInner<VTable, X> };
let inner = NonNull::new(mem).unwrap();
assert!(!mem.is_null());
unsafe {
mem.write(VRcInner {
vtable: X::static_vtable(),
strong_ref: AtomicU32::new(1),
weak_ref: AtomicU32::new(1),
data_offset: 0,
data,
});
(*mem).data_offset =
(&(*mem).data as *const _ as usize - mem as *const _ as usize) as u16;
VRc { inner }
}
}
pub fn into_dyn(this: Self) -> VRc<VTable, Dyn>
where
Self: 'static,
{
unsafe { core::mem::transmute(this) }
}
}
impl<VTable: VTableMetaDropInPlace, X> VRc<VTable, X> {
pub fn as_pin_ref(&self) -> Pin<&X> {
unsafe { Pin::new_unchecked(&*self) }
}
pub fn borrow(this: &Self) -> VRef<'_, VTable> {
unsafe {
let inner = this.inner.cast::<VRcInner<VTable, u8>>();
VRef::from_raw(
NonNull::from(inner.as_ref().vtable),
NonNull::from(&*inner.as_ref().data_ptr()),
)
}
}
pub fn borrow_pin<'b>(this: &'b Self) -> Pin<VRef<'b, VTable>> {
unsafe { Pin::new_unchecked(Self::borrow(this)) }
}
pub fn downgrade(this: &Self) -> VWeak<VTable, X> {
let inner = unsafe { this.inner.as_ref() };
inner.weak_ref.fetch_add(1, Ordering::SeqCst);
VWeak { inner: Some(this.inner) }
}
pub fn strong_count(this: &Self) -> usize {
unsafe { this.inner.as_ref().strong_ref.load(Ordering::SeqCst) as usize }
}
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
this.inner == other.inner
}
}
impl<VTable: VTableMetaDropInPlace + 'static, X> Clone for VRc<VTable, X> {
fn clone(&self) -> Self {
let inner = unsafe { self.inner.as_ref() };
inner.strong_ref.fetch_add(1, Ordering::SeqCst);
Self { inner: self.inner }
}
}
impl<VTable: VTableMetaDropInPlace, X > Deref for VRc<VTable, X> {
type Target = X;
fn deref(&self) -> &Self::Target {
let inner = unsafe { self.inner.as_ref() };
inner.as_ref()
}
}
unsafe impl<VTable: VTableMetaDropInPlace + 'static, X: Send + Sync> Send for VRc<VTable, X> {}
unsafe impl<VTable: VTableMetaDropInPlace + 'static, X: Send + Sync> Sync for VRc<VTable, X> {}
#[repr(transparent)]
pub struct VWeak<VTable: VTableMetaDropInPlace + 'static, X = Dyn> {
inner: Option<NonNull<VRcInner<'static, VTable, X>>>,
}
impl<VTable: VTableMetaDropInPlace + 'static, X> Default for VWeak<VTable, X> {
fn default() -> Self {
Self { inner: None }
}
}
impl<VTable: VTableMetaDropInPlace + 'static, X> Clone for VWeak<VTable, X> {
fn clone(&self) -> Self {
if let Some(inner) = self.inner {
let inner = unsafe { inner.as_ref() };
inner.weak_ref.fetch_add(1, Ordering::SeqCst);
}
VWeak { inner: self.inner }
}
}
impl<T: VTableMetaDropInPlace + 'static, X> Drop for VWeak<T, X> {
fn drop(&mut self) {
if let Some(i) = self.inner {
let inner = unsafe { i.as_ref() };
if inner.weak_ref.fetch_sub(1, Ordering::SeqCst) == 1 {
let vtable = inner.vtable;
unsafe {
let layout = i.cast::<VRcInner<T, Layout>>().as_ref().data;
T::dealloc(vtable, i.cast().as_ptr(), layout);
}
}
}
}
}
impl<VTable: VTableMetaDropInPlace + 'static, X> VWeak<VTable, X> {
pub fn upgrade(&self) -> Option<VRc<VTable, X>> {
if let Some(i) = self.inner {
let inner = unsafe { i.as_ref() };
if inner.strong_ref.load(Ordering::SeqCst) == 0 {
None
} else {
inner.strong_ref.fetch_add(1, Ordering::SeqCst);
Some(VRc { inner: i })
}
} else {
None
}
}
}
impl<VTable: VTableMetaDropInPlace + 'static, X: HasStaticVTable<VTable> + 'static>
VWeak<VTable, X>
{
pub fn into_dyn(self) -> VWeak<VTable, Dyn> {
unsafe { core::mem::transmute(self) }
}
}