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
use std::{mem, ops, ptr, slice};
use crate::alloc::{self, array};
/// Owns a completely initialized array and its exact allocation extent.
#[must_use]
#[derive(Debug)]
#[repr(C)]
pub struct Block<T, E: alloc::raw::Extent, S = ()> {
pub(in crate::alloc::array) extent: E,
pub(in crate::alloc::array) state: S,
pub(in crate::alloc::array) pointer: ptr::NonNull<T>,
}
impl<T, E: alloc::raw::Extent, S> Block<mem::MaybeUninit<T>, E, S> {
pub fn try_new(extent: E, state: S) -> Result<Self, alloc::Error> {
Ok(array::Plan::try_new(extent)?.try_allocate(state)?)
}
/// Initializes the entire unpublished backing and transfers its ownership.
pub fn init(mut self, make: impl FnMut(usize) -> T) -> Block<T, E, S> {
alloc::raw::init(&mut self, make);
// SAFETY: the complete owned extent now contains initialized elements.
unsafe { self.assume_init() }
}
/// Initializes each element at its final address. On failure, drops the
/// completed prefix and releases the backing and state.
pub fn try_init<F>(
self,
mut make: impl FnMut(ptr::NonNull<T>) -> Result<T, F>,
) -> Result<Block<T, E, S>, F> {
let base = self.pointer.cast::<T>();
let values = (0..self.extent.len()).map(move |index| {
// SAFETY: each index names a final position in the live backing.
make(unsafe { base.add(index) })
});
// SAFETY: the range covers exactly the extent of this backing.
unsafe { self.try_fill(values) }
}
/// Initializes every element without requiring its storage index.
pub fn repeat_with(self, mut make: impl FnMut() -> T) -> Block<T, E, S> {
self.init(|_| make())
}
}
impl<T, E: alloc::raw::Extent, S> Block<T, E, S> {
pub const fn empty(extent: alloc::raw::Empty<E>, state: S) -> Self {
Self {
extent: extent.into_inner(),
state,
pointer: ptr::NonNull::dangling(),
}
}
pub const fn extent(&self) -> &E {
&self.extent
}
pub const fn state(&self) -> &S {
&self.state
}
pub fn state_mut(&mut self) -> &mut S {
&mut self.state
}
pub const fn as_ptr(&self) -> *const T {
self.pointer.as_ptr()
}
pub fn as_mut_ptr(&mut self) -> *mut T {
self.pointer.as_ptr()
}
/// Exclusively borrows the state and its disjoint initialized backing.
pub fn parts_mut(&mut self) -> (&mut S, &mut [T]) {
// SAFETY: admission proves this exact array layout, and construction
// initializes every T; the backing is disjoint from the inline state.
let values = unsafe { slice::from_raw_parts_mut(self.pointer.as_ptr(), self.extent.len()) };
(&mut self.state, values)
}
}
impl<T> Block<T, usize, ()> {
/// Clones an exact slice in order through a fallible element factory.
pub fn try_clone(
source: &[T],
make: impl FnMut(&T) -> Result<T, alloc::Exhausted>,
) -> Result<Self, alloc::Exhausted> {
let block = array::Plan::from_slice(source).try_allocate(())?;
// SAFETY: the retained slice supplies exactly the same element type,
// count and order as the allocation planned from this source.
unsafe { block.try_fill(source.iter().map(make)) }
}
/// Transfers the initialized allocation without copying its elements.
pub fn into_vec(self) -> Vec<T> {
let block = mem::ManuallyDrop::new(self);
let len = *block.extent();
// SAFETY: the consumed block owns exactly len initialized T values in
// the standard allocator's matching array layout. Its unit state has
// no drop obligation; empty and zero-sized arrays retain aligned storage.
unsafe { Vec::from_raw_parts(block.pointer.as_ptr(), len, len) }
}
}
impl<T, E: alloc::raw::Extent, S> ops::Deref for Block<T, E, S> {
type Target = [T];
fn deref(&self) -> &Self::Target {
// SAFETY: construction proves that every element is initialized and
// owned under this exact immutable extent and validated layout.
unsafe { slice::from_raw_parts(self.pointer.as_ptr(), self.extent.len()) }
}
}
impl<T, E: alloc::raw::Extent, S> ops::DerefMut for Block<T, E, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.parts_mut().1
}
}
impl<T, E: alloc::raw::Extent, S> Drop for Block<T, E, S> {
fn drop(&mut self) {
// SAFETY: this owner transfers its initialized slice and exact standard allocation once.
unsafe {
drop(Box::from_raw(ptr::slice_from_raw_parts_mut(
self.pointer.as_ptr(),
self.extent.len(),
)));
}
}
}
impl<T, E: alloc::raw::Extent, S> Block<mem::MaybeUninit<T>, E, S> {
/// # Safety
/// Every element is initialized and this owner retains its exact drop obligation.
pub unsafe fn assume_init(self) -> Block<T, E, S> {
let block = mem::ManuallyDrop::new(self);
Block {
extent: block.extent,
// SAFETY: the consumed owner transfers its state once without running Drop.
state: unsafe { ptr::read(&block.state) },
pointer: block.pointer.cast(),
}
}
}
impl<T, E: alloc::raw::Extent, S> Block<mem::MaybeUninit<T>, E, S> {
/// # Safety
/// Runs fit disjoint allocations and transfer all initialization exactly once.
/// Spare has no borrows or destructors; restore indices before reusing the owner.
pub unsafe fn relocate<const N: usize>(
&mut self,
mut spare: Block<mem::MaybeUninit<T>, E>,
runs: [(usize, usize, usize); N],
) {
for (start, target, len) in runs {
if len != 0 && mem::size_of::<T>() != 0 {
// SAFETY: the retained relocation admits these complete disjoint runs.
unsafe {
ptr::copy_nonoverlapping(
self.as_mut_ptr().add(start),
spare.as_mut_ptr().add(target),
len,
);
}
}
}
mem::swap(&mut self.extent, &mut spare.extent);
mem::swap(&mut self.pointer, &mut spare.pointer);
}
/// # Safety
/// Every successful prefix fits this extent; completion fills it exactly.
/// Failure drops the initialized prefix before releasing the source and backing.
pub unsafe fn try_fill<F>(
mut self,
source: impl Iterator<Item = Result<T, F>>,
) -> Result<Block<T, E, S>, F> {
let pointer = self.as_mut_ptr().cast::<T>();
let mut filled = 0;
for item in source {
match item {
Ok(value) => {
// SAFETY: this success admits one more element in the exact allocation.
unsafe { pointer.add(filled).write(value) };
filled += 1;
}
Err(error) => {
// SAFETY: only the first `filled` elements have been initialized.
unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(pointer, filled)) };
return Err(error);
}
}
}
// SAFETY: terminal iteration completed exactly the retained extent.
Ok(unsafe { self.assume_init() })
}
}