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
use super::traits::{Storage, StorageMut};
/// Aligned, owned array storage allocated via the Mnemosyne systems allocator.
pub struct MnemosyneStorage<T> {
ptr: *mut T,
len: usize,
layout: std::alloc::Layout,
}
impl<T> MnemosyneStorage<T> {
fn allocate_raw(len: usize) -> Self {
use std::alloc::{GlobalAlloc, Layout as AllocLayout};
let size = len
.checked_mul(std::mem::size_of::<T>())
.expect("MnemosyneStorage allocation size overflow");
let align = std::mem::align_of::<T>();
let layout = AllocLayout::from_size_align(size, align)
.expect("Invalid layout construction for MnemosyneStorage");
if size == 0 {
return Self {
ptr: std::ptr::NonNull::<T>::dangling().as_ptr(),
len,
layout,
};
}
// SAFETY: `layout` is constructible and verified above.
let ptr = unsafe { mnemosyne::Mnemosyne.alloc(layout) } as *mut T;
if ptr.is_null() {
panic!("Mnemosyne allocation failed");
}
Self { ptr, len, layout }
}
}
struct MnemosyneInitGuard<T> {
ptr: *mut T,
initialized: usize,
layout: std::alloc::Layout,
}
impl<T> Drop for MnemosyneInitGuard<T> {
fn drop(&mut self) {
if self.initialized > 0 && std::mem::needs_drop::<T>() {
for idx in 0..self.initialized {
// SAFETY: indices below `initialized` were written exactly once
// by the guarded constructor and have not yet been dropped.
unsafe {
std::ptr::drop_in_place(self.ptr.add(idx));
}
}
}
if self.layout.size() > 0 {
use std::alloc::GlobalAlloc;
// SAFETY: the guard exclusively owns the allocation after a
// constructor panic and deallocates it with its original layout.
unsafe {
mnemosyne::Mnemosyne.dealloc(self.ptr as *mut u8, self.layout);
}
}
}
}
impl<T: Default> MnemosyneStorage<T> {
/// Allocate storage via Mnemosyne and initialize each element with `T::default()`.
///
/// # Panics
///
/// Panics when the allocation size overflows, Mnemosyne cannot allocate the
/// requested storage, or `T::default()` panics. A default panic drops the
/// initialized prefix and releases the allocation.
pub fn new(len: usize) -> Self {
Self::from_fn(len, |_| T::default())
}
}
impl<T> MnemosyneStorage<T> {
pub(crate) fn from_fn<F>(len: usize, mut generate: F) -> Self
where
F: FnMut(usize) -> T,
{
let storage = std::mem::ManuallyDrop::new(Self::allocate_raw(len));
let mut guard = MnemosyneInitGuard {
ptr: storage.ptr,
initialized: 0,
layout: storage.layout,
};
for index in 0..len {
let value = generate(index);
// SAFETY: `index < len`; this slot is in the exclusive allocation
// and has not previously been initialized.
unsafe {
guard.ptr.add(index).write(value);
}
guard.initialized += 1;
}
let initialized = Self {
ptr: guard.ptr,
len,
layout: guard.layout,
};
std::mem::forget(guard);
initialized
}
/// Allocate storage and copy elements from a slice.
pub fn from_slice(slice: &[T]) -> Self
where
T: Copy,
{
let storage = Self::allocate_raw(slice.len());
if !storage.ptr.is_null() {
// SAFETY: source and destination are valid for `slice.len()` non-overlapping elements.
unsafe {
std::ptr::copy_nonoverlapping(slice.as_ptr(), storage.ptr, slice.len());
}
}
storage
}
/// Allocate storage via Mnemosyne and move elements from a vector.
pub fn from_vec(vec: Vec<T>) -> Self {
let len = vec.len();
let capacity = vec.capacity();
let storage = Self::allocate_raw(len);
let mut vec = std::mem::ManuallyDrop::new(vec);
if !storage.ptr.is_null() && len > 0 {
// SAFETY: source has `len` initialized elements, destination has
// room for `len` elements, and the regions do not overlap.
unsafe {
std::ptr::copy_nonoverlapping(vec.as_ptr(), storage.ptr, len);
}
}
// SAFETY: the elements were moved into Mnemosyne storage above. The
// reconstructed vector has length zero, so it releases only capacity.
unsafe {
let _ = Vec::from_raw_parts(vec.as_mut_ptr(), 0, capacity);
}
storage
}
/// Move initialized elements from Mnemosyne storage into a vector.
pub fn into_vec(self) -> Vec<T> {
let mut vec = Vec::with_capacity(self.len);
let storage = std::mem::ManuallyDrop::new(self);
if !storage.ptr.is_null() && storage.len > 0 {
// SAFETY: source has `len` initialized elements, destination has
// capacity for `len` elements, and the regions do not overlap.
unsafe {
std::ptr::copy_nonoverlapping(storage.ptr, vec.as_mut_ptr(), storage.len);
vec.set_len(storage.len);
}
}
if storage.layout.size() > 0 {
use std::alloc::GlobalAlloc;
// SAFETY: `storage.ptr` was allocated by Mnemosyne with this layout.
unsafe {
mnemosyne::Mnemosyne.dealloc(storage.ptr as *mut u8, storage.layout);
}
}
vec
}
}
impl<T> Drop for MnemosyneStorage<T> {
#[inline]
fn drop(&mut self) {
if !self.ptr.is_null() {
if std::mem::needs_drop::<T>() {
for index in 0..self.len {
// SAFETY: all public constructors initialize every element.
unsafe {
std::ptr::drop_in_place(self.ptr.add(index));
}
}
}
if self.layout.size() > 0 {
use std::alloc::GlobalAlloc;
// SAFETY: `self.ptr` was previously allocated with this layout.
unsafe {
mnemosyne::Mnemosyne.dealloc(self.ptr as *mut u8, self.layout);
}
}
}
}
}
unsafe impl<T: Send> Send for MnemosyneStorage<T> {}
unsafe impl<T: Sync> Sync for MnemosyneStorage<T> {}
impl<T> Storage<T> for MnemosyneStorage<T> {
#[inline]
fn as_slice(&self) -> &[T] {
if self.len == 0 {
&[]
} else {
// SAFETY: `self.ptr` points to valid memory of `self.len` elements.
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
}
}
}
impl<T> StorageMut<T> for MnemosyneStorage<T> {
#[inline]
fn as_mut_slice(&mut self) -> &mut [T] {
if self.len == 0 {
&mut []
} else {
// SAFETY: `self.ptr` points to valid mutable memory of `self.len` elements.
unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
}
}
}