stable_alloc_shim/core_alloc.rs
1use core::alloc::Layout;
2use core::fmt;
3use core::ptr;
4use core::ptr::NonNull;
5
6use crate::nonnull_as_mut_ptr;
7use crate::nonnull_len;
8
9/// The `AllocError` error indicates an allocation failure
10/// that may be due to resource exhaustion or to
11/// something wrong when combining the given input arguments with this
12/// allocator.
13#[derive(Copy, Clone, PartialEq, Eq, Debug)]
14pub struct AllocError;
15
16// (we need this for downstream impl of trait Error)
17impl fmt::Display for AllocError {
18 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19 f.write_str("memory allocation failed")
20 }
21}
22
23/// An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of
24/// data described via [`Layout`][].
25///
26/// `Allocator` is designed to be implemented on ZSTs, references, or smart pointers because having
27/// an allocator like `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the
28/// allocated memory.
29///
30/// Unlike [`GlobalAlloc`][], zero-sized allocations are allowed in `Allocator`. If an underlying
31/// allocator does not support this (like jemalloc) or return a null pointer (such as
32/// `libc::malloc`), this must be caught by the implementation.
33///
34/// ### Currently allocated memory
35///
36/// Some of the methods require that a memory block be *currently allocated* via an allocator. This
37/// means that:
38///
39/// * the starting address for that memory block was previously returned by [`allocate`], [`grow`], or
40/// [`shrink`], and
41///
42/// * the memory block has not been subsequently deallocated, where blocks are either deallocated
43/// directly by being passed to [`deallocate`] or were changed by being passed to [`grow`] or
44/// [`shrink`] that returns `Ok`. If `grow` or `shrink` have returned `Err`, the passed pointer
45/// remains valid.
46///
47/// [`allocate`]: Allocator::allocate
48/// [`grow`]: Allocator::grow
49/// [`shrink`]: Allocator::shrink
50/// [`deallocate`]: Allocator::deallocate
51///
52/// ### Memory fitting
53///
54/// Some of the methods require that a layout *fit* a memory block. What it means for a layout to
55/// "fit" a memory block means (or equivalently, for a memory block to "fit" a layout) is that the
56/// following conditions must hold:
57///
58/// * The block must be allocated with the same alignment as [`layout.align()`], and
59///
60/// * The provided [`layout.size()`] must fall in the range `min ..= max`, where:
61/// - `min` is the size of the layout most recently used to allocate the block, and
62/// - `max` is the latest actual size returned from [`allocate`], [`grow`], or [`shrink`].
63///
64/// [`layout.align()`]: Layout::align
65/// [`layout.size()`]: Layout::size
66///
67/// # Safety
68///
69/// * Memory blocks returned from an allocator must point to valid memory and retain their validity
70/// until the instance and all of its clones are dropped,
71///
72/// * cloning or moving the allocator must not invalidate memory blocks returned from this
73/// allocator. A cloned allocator must behave like the same allocator, and
74///
75/// * any pointer to a memory block which is [*currently allocated*] may be passed to any other
76/// method of the allocator.
77///
78/// [*currently allocated*]: #currently-allocated-memory
79pub unsafe trait Allocator {
80 /// Attempts to allocate a block of memory.
81 ///
82 /// On success, returns a [`NonNull<[u8]>`][NonNull] meeting the size and alignment guarantees of `layout`.
83 ///
84 /// The returned block may have a larger size than specified by `layout.size()`, and may or may
85 /// not have its contents initialized.
86 ///
87 /// # Errors
88 ///
89 /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
90 /// allocator's size or alignment constraints.
91 ///
92 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
93 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
94 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
95 ///
96 /// Clients wishing to abort computation in response to an allocation error are encouraged to
97 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
98 ///
99 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
100 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
101
102 /// Behaves like `allocate`, but also ensures that the returned memory is zero-initialized.
103 ///
104 /// # Errors
105 ///
106 /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
107 /// allocator's size or alignment constraints.
108 ///
109 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
110 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
111 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
112 ///
113 /// Clients wishing to abort computation in response to an allocation error are encouraged to
114 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
115 ///
116 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
117 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
118 let ptr = self.allocate(layout)?;
119 // SAFETY: `alloc` returns a valid memory block
120 unsafe { nonnull_as_mut_ptr(ptr).write_bytes(0, nonnull_len(ptr)) }
121 Ok(ptr)
122 }
123
124 /// Deallocates the memory referenced by `ptr`.
125 ///
126 /// # Safety
127 ///
128 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator, and
129 /// * `layout` must [*fit*] that block of memory.
130 ///
131 /// [*currently allocated*]: #currently-allocated-memory
132 /// [*fit*]: #memory-fitting
133 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
134
135 /// Attempts to extend the memory block.
136 ///
137 /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
138 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
139 /// this, the allocator may extend the allocation referenced by `ptr` to fit the new layout.
140 ///
141 /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
142 /// transferred to this allocator. The memory may or may not have been freed, and should be
143 /// considered unusable.
144 ///
145 /// If this method returns `Err`, then ownership of the memory block has not been transferred to
146 /// this allocator, and the contents of the memory block are unaltered.
147 ///
148 /// # Safety
149 ///
150 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
151 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
152 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
153 ///
154 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
155 ///
156 /// [*currently allocated*]: #currently-allocated-memory
157 /// [*fit*]: #memory-fitting
158 ///
159 /// # Errors
160 ///
161 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
162 /// constraints of the allocator, or if growing otherwise fails.
163 ///
164 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
165 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
166 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
167 ///
168 /// Clients wishing to abort computation in response to an allocation error are encouraged to
169 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
170 ///
171 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
172 unsafe fn grow(
173 &self,
174 ptr: NonNull<u8>,
175 old_layout: Layout,
176 new_layout: Layout,
177 ) -> Result<NonNull<[u8]>, AllocError> {
178 debug_assert!(
179 new_layout.size() >= old_layout.size(),
180 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
181 );
182
183 let new_ptr = self.allocate(new_layout)?;
184
185 // SAFETY: because `new_layout.size()` must be greater than or equal to
186 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
187 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
188 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
189 // safe. The safety contract for `dealloc` must be upheld by the caller.
190 unsafe {
191 ptr::copy_nonoverlapping(ptr.as_ptr(), nonnull_as_mut_ptr(new_ptr), old_layout.size());
192 self.deallocate(ptr, old_layout);
193 }
194
195 Ok(new_ptr)
196 }
197
198 /// Behaves like `grow`, but also ensures that the new contents are set to zero before being
199 /// returned.
200 ///
201 /// The memory block will contain the following contents after a successful call to
202 /// `grow_zeroed`:
203 /// * Bytes `0..old_layout.size()` are preserved from the original allocation.
204 /// * Bytes `old_layout.size()..old_size` will either be preserved or zeroed, depending on
205 /// the allocator implementation. `old_size` refers to the size of the memory block prior
206 /// to the `grow_zeroed` call, which may be larger than the size that was originally
207 /// requested when it was allocated.
208 /// * Bytes `old_size..new_size` are zeroed. `new_size` refers to the size of the memory
209 /// block returned by the `grow_zeroed` call.
210 ///
211 /// # Safety
212 ///
213 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
214 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
215 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
216 ///
217 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
218 ///
219 /// [*currently allocated*]: #currently-allocated-memory
220 /// [*fit*]: #memory-fitting
221 ///
222 /// # Errors
223 ///
224 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
225 /// constraints of the allocator, or if growing otherwise fails.
226 ///
227 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
228 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
229 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
230 ///
231 /// Clients wishing to abort computation in response to an allocation error are encouraged to
232 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
233 ///
234 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
235 unsafe fn grow_zeroed(
236 &self,
237 ptr: NonNull<u8>,
238 old_layout: Layout,
239 new_layout: Layout,
240 ) -> Result<NonNull<[u8]>, AllocError> {
241 debug_assert!(
242 new_layout.size() >= old_layout.size(),
243 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
244 );
245
246 let new_ptr = self.allocate_zeroed(new_layout)?;
247
248 // SAFETY: because `new_layout.size()` must be greater than or equal to
249 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
250 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
251 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
252 // safe. The safety contract for `dealloc` must be upheld by the caller.
253 unsafe {
254 ptr::copy_nonoverlapping(ptr.as_ptr(), nonnull_as_mut_ptr(new_ptr), old_layout.size());
255 self.deallocate(ptr, old_layout);
256 }
257
258 Ok(new_ptr)
259 }
260
261 /// Attempts to shrink the memory block.
262 ///
263 /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
264 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
265 /// this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout.
266 ///
267 /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
268 /// transferred to this allocator. The memory may or may not have been freed, and should be
269 /// considered unusable.
270 ///
271 /// If this method returns `Err`, then ownership of the memory block has not been transferred to
272 /// this allocator, and the contents of the memory block are unaltered.
273 ///
274 /// # Safety
275 ///
276 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
277 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
278 /// * `new_layout.size()` must be smaller than or equal to `old_layout.size()`.
279 ///
280 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
281 ///
282 /// [*currently allocated*]: #currently-allocated-memory
283 /// [*fit*]: #memory-fitting
284 ///
285 /// # Errors
286 ///
287 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
288 /// constraints of the allocator, or if shrinking otherwise fails.
289 ///
290 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
291 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
292 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
293 ///
294 /// Clients wishing to abort computation in response to an allocation error are encouraged to
295 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
296 ///
297 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
298 unsafe fn shrink(
299 &self,
300 ptr: NonNull<u8>,
301 old_layout: Layout,
302 new_layout: Layout,
303 ) -> Result<NonNull<[u8]>, AllocError> {
304 debug_assert!(
305 new_layout.size() <= old_layout.size(),
306 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
307 );
308
309 let new_ptr = self.allocate(new_layout)?;
310
311 // SAFETY: because `new_layout.size()` must be lower than or equal to
312 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
313 // writes for `new_layout.size()` bytes. Also, because the old allocation wasn't yet
314 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
315 // safe. The safety contract for `dealloc` must be upheld by the caller.
316 unsafe {
317 ptr::copy_nonoverlapping(ptr.as_ptr(), nonnull_as_mut_ptr(new_ptr), new_layout.size());
318 self.deallocate(ptr, old_layout);
319 }
320
321 Ok(new_ptr)
322 }
323
324 /// Creates a "by reference" adapter for this instance of `Allocator`.
325 ///
326 /// The returned adapter also implements `Allocator` and will simply borrow this.
327 #[inline(always)]
328 fn by_ref(&self) -> &Self
329 where
330 Self: Sized,
331 {
332 self
333 }
334}
335
336unsafe impl<A> Allocator for &A
337where
338 A: Allocator + ?Sized,
339{
340 #[inline]
341 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
342 (**self).allocate(layout)
343 }
344
345 #[inline]
346 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
347 (**self).allocate_zeroed(layout)
348 }
349
350 #[inline]
351 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
352 // SAFETY: the safety contract must be upheld by the caller
353 unsafe { (**self).deallocate(ptr, layout) }
354 }
355
356 #[inline]
357 unsafe fn grow(
358 &self,
359 ptr: NonNull<u8>,
360 old_layout: Layout,
361 new_layout: Layout,
362 ) -> Result<NonNull<[u8]>, AllocError> {
363 // SAFETY: the safety contract must be upheld by the caller
364 unsafe { (**self).grow(ptr, old_layout, new_layout) }
365 }
366
367 #[inline]
368 unsafe fn grow_zeroed(
369 &self,
370 ptr: NonNull<u8>,
371 old_layout: Layout,
372 new_layout: Layout,
373 ) -> Result<NonNull<[u8]>, AllocError> {
374 // SAFETY: the safety contract must be upheld by the caller
375 unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
376 }
377
378 #[inline]
379 unsafe fn shrink(
380 &self,
381 ptr: NonNull<u8>,
382 old_layout: Layout,
383 new_layout: Layout,
384 ) -> Result<NonNull<[u8]>, AllocError> {
385 // SAFETY: the safety contract must be upheld by the caller
386 unsafe { (**self).shrink(ptr, old_layout, new_layout) }
387 }
388}