bumpalo/alloc.rs
1// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11#![allow(unstable_name_collisions)]
12#![allow(dead_code)]
13
14//! Memory allocation APIs
15
16use core::cmp;
17use core::fmt;
18use core::mem;
19use core::ptr::{self, NonNull};
20use core::usize;
21
22pub use core::alloc::{Layout, LayoutErr};
23
24fn new_layout_err() -> LayoutErr {
25 Layout::from_size_align(1, 3).unwrap_err()
26}
27
28pub fn handle_alloc_error(layout: Layout) -> ! {
29 panic!("encountered allocation error: {:?}", layout)
30}
31
32pub trait UnstableLayoutMethods {
33 fn padding_needed_for(&self, align: usize) -> usize;
34 fn repeat(&self, n: usize) -> Result<(Layout, usize), LayoutErr>;
35 fn array<T>(n: usize) -> Result<Layout, LayoutErr>;
36}
37
38impl UnstableLayoutMethods for Layout {
39 fn padding_needed_for(&self, align: usize) -> usize {
40 let len = self.size();
41
42 // Rounded up value is:
43 // len_rounded_up = (len + align - 1) & !(align - 1);
44 // and then we return the padding difference: `len_rounded_up - len`.
45 //
46 // We use modular arithmetic throughout:
47 //
48 // 1. align is guaranteed to be > 0, so align - 1 is always
49 // valid.
50 //
51 // 2. `len + align - 1` can overflow by at most `align - 1`,
52 // so the &-mask wth `!(align - 1)` will ensure that in the
53 // case of overflow, `len_rounded_up` will itself be 0.
54 // Thus the returned padding, when added to `len`, yields 0,
55 // which trivially satisfies the alignment `align`.
56 //
57 // (Of course, attempts to allocate blocks of memory whose
58 // size and padding overflow in the above manner should cause
59 // the allocator to yield an error anyway.)
60
61 let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
62 len_rounded_up.wrapping_sub(len)
63 }
64
65 fn repeat(&self, n: usize) -> Result<(Layout, usize), LayoutErr> {
66 let padded_size = self
67 .size()
68 .checked_add(self.padding_needed_for(self.align()))
69 .ok_or_else(new_layout_err)?;
70 let alloc_size = padded_size.checked_mul(n).ok_or_else(new_layout_err)?;
71
72 unsafe {
73 // self.align is already known to be valid and alloc_size has been
74 // padded already.
75 Ok((
76 Layout::from_size_align_unchecked(alloc_size, self.align()),
77 padded_size,
78 ))
79 }
80 }
81
82 fn array<T>(n: usize) -> Result<Layout, LayoutErr> {
83 Layout::new::<T>().repeat(n).map(|(k, offs)| {
84 debug_assert!(offs == mem::size_of::<T>());
85 k
86 })
87 }
88}
89
90/// Represents the combination of a starting address and
91/// a total capacity of the returned block.
92// #[unstable(feature = "allocator_api", issue = "32838")]
93#[derive(Debug)]
94pub struct Excess(pub NonNull<u8>, pub usize);
95
96fn size_align<T>() -> (usize, usize) {
97 (mem::size_of::<T>(), mem::align_of::<T>())
98}
99
100/// The `AllocErr` error indicates an allocation failure
101/// that may be due to resource exhaustion or to
102/// something wrong when combining the given input arguments with this
103/// allocator.
104// #[unstable(feature = "allocator_api", issue = "32838")]
105#[derive(Clone, PartialEq, Eq, Debug)]
106pub struct AllocErr;
107
108// (we need this for downstream impl of trait Error)
109// #[unstable(feature = "allocator_api", issue = "32838")]
110impl fmt::Display for AllocErr {
111 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
112 f.write_str("memory allocation failed")
113 }
114}
115
116/// The `CannotReallocInPlace` error is used when `grow_in_place` or
117/// `shrink_in_place` were unable to reuse the given memory block for
118/// a requested layout.
119// #[unstable(feature = "allocator_api", issue = "32838")]
120#[derive(Clone, PartialEq, Eq, Debug)]
121pub struct CannotReallocInPlace;
122
123// #[unstable(feature = "allocator_api", issue = "32838")]
124impl CannotReallocInPlace {
125 pub fn description(&self) -> &str {
126 "cannot reallocate allocator's memory in place"
127 }
128}
129
130// (we need this for downstream impl of trait Error)
131// #[unstable(feature = "allocator_api", issue = "32838")]
132impl fmt::Display for CannotReallocInPlace {
133 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134 write!(f, "{}", self.description())
135 }
136}
137
138/// An implementation of `Alloc` can allocate, reallocate, and
139/// deallocate arbitrary blocks of data described via `Layout`.
140///
141/// Some of the methods require that a memory block be *currently
142/// allocated* via an allocator. This means that:
143///
144/// * the starting address for that memory block was previously
145/// returned by a previous call to an allocation method (`alloc`,
146/// `alloc_zeroed`, `alloc_excess`, `alloc_one`, `alloc_array`) or
147/// reallocation method (`realloc`, `realloc_excess`, or
148/// `realloc_array`), and
149///
150/// * the memory block has not been subsequently deallocated, where
151/// blocks are deallocated either by being passed to a deallocation
152/// method (`dealloc`, `dealloc_one`, `dealloc_array`) or by being
153/// passed to a reallocation method (see above) that returns `Ok`.
154///
155/// A note regarding zero-sized types and zero-sized layouts: many
156/// methods in the `Alloc` trait state that allocation requests
157/// must be non-zero size, or else undefined behavior can result.
158///
159/// * However, some higher-level allocation methods (`alloc_one`,
160/// `alloc_array`) are well-defined on zero-sized types and can
161/// optionally support them: it is left up to the implementor
162/// whether to return `Err`, or to return `Ok` with some pointer.
163///
164/// * If an `Alloc` implementation chooses to return `Ok` in this
165/// case (i.e. the pointer denotes a zero-sized inaccessible block)
166/// then that returned pointer must be considered "currently
167/// allocated". On such an allocator, *all* methods that take
168/// currently-allocated pointers as inputs must accept these
169/// zero-sized pointers, *without* causing undefined behavior.
170///
171/// * In other words, if a zero-sized pointer can flow out of an
172/// allocator, then that allocator must likewise accept that pointer
173/// flowing back into its deallocation and reallocation methods.
174///
175/// Some of the methods require that a layout *fit* a memory block.
176/// What it means for a layout to "fit" a memory block means (or
177/// equivalently, for a memory block to "fit" a layout) is that the
178/// following two conditions must hold:
179///
180/// 1. The block's starting address must be aligned to `layout.align()`.
181///
182/// 2. The block's size must fall in the range `[use_min, use_max]`, where:
183///
184/// * `use_min` is `self.usable_size(layout).0`, and
185///
186/// * `use_max` is the capacity that was (or would have been)
187/// returned when (if) the block was allocated via a call to
188/// `alloc_excess` or `realloc_excess`.
189///
190/// Note that:
191///
192/// * the size of the layout most recently used to allocate the block
193/// is guaranteed to be in the range `[use_min, use_max]`, and
194///
195/// * a lower-bound on `use_max` can be safely approximated by a call to
196/// `usable_size`.
197///
198/// * if a layout `k` fits a memory block (denoted by `ptr`)
199/// currently allocated via an allocator `a`, then it is legal to
200/// use that layout to deallocate it, i.e. `a.dealloc(ptr, k);`.
201///
202/// # Unsafety
203///
204/// The `Alloc` trait is an `unsafe` trait for a number of reasons, and
205/// implementors must ensure that they adhere to these contracts:
206///
207/// * Pointers returned from allocation functions must point to valid memory and
208/// retain their validity until at least the instance of `Alloc` is dropped
209/// itself.
210///
211/// * `Layout` queries and calculations in general must be correct. Callers of
212/// this trait are allowed to rely on the contracts defined on each method,
213/// and implementors must ensure such contracts remain true.
214///
215/// Note that this list may get tweaked over time as clarifications are made in
216/// the future.
217// #[unstable(feature = "allocator_api", issue = "32838")]
218pub unsafe trait Alloc {
219 // (Note: some existing allocators have unspecified but well-defined
220 // behavior in response to a zero size allocation request ;
221 // e.g. in C, `malloc` of 0 will either return a null pointer or a
222 // unique pointer, but will not have arbitrary undefined
223 // behavior.
224 // However in jemalloc for example,
225 // `mallocx(0)` is documented as undefined behavior.)
226
227 /// Returns a pointer meeting the size and alignment guarantees of
228 /// `layout`.
229 ///
230 /// If this method returns an `Ok(addr)`, then the `addr` returned
231 /// will be non-null address pointing to a block of storage
232 /// suitable for holding an instance of `layout`.
233 ///
234 /// The returned block of storage may or may not have its contents
235 /// initialized. (Extension subtraits might restrict this
236 /// behavior, e.g. to ensure initialization to particular sets of
237 /// bit patterns.)
238 ///
239 /// # Safety
240 ///
241 /// This function is unsafe because undefined behavior can result
242 /// if the caller does not ensure that `layout` has non-zero size.
243 ///
244 /// (Extension subtraits might provide more specific bounds on
245 /// behavior, e.g. guarantee a sentinel address or a null pointer
246 /// in response to a zero-size allocation request.)
247 ///
248 /// # Errors
249 ///
250 /// Returning `Err` indicates that either memory is exhausted or
251 /// `layout` does not meet allocator's size or alignment
252 /// constraints.
253 ///
254 /// Implementations are encouraged to return `Err` on memory
255 /// exhaustion rather than panicking or aborting, but this is not
256 /// a strict requirement. (Specifically: it is *legal* to
257 /// implement this trait atop an underlying native allocation
258 /// library that aborts on memory exhaustion.)
259 ///
260 /// Clients wishing to abort computation in response to an
261 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
262 /// rather than directly invoking `panic!` or similar.
263 ///
264 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
265 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr>;
266
267 /// Deallocate the memory referenced by `ptr`.
268 ///
269 /// # Safety
270 ///
271 /// This function is unsafe because undefined behavior can result
272 /// if the caller does not ensure all of the following:
273 ///
274 /// * `ptr` must denote a block of memory currently allocated via
275 /// this allocator,
276 ///
277 /// * `layout` must *fit* that block of memory,
278 ///
279 /// * In addition to fitting the block of memory `layout`, the
280 /// alignment of the `layout` must match the alignment used
281 /// to allocate that block of memory.
282 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout);
283
284 // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
285 // usable_size
286
287 /// Returns bounds on the guaranteed usable size of a successful
288 /// allocation created with the specified `layout`.
289 ///
290 /// In particular, if one has a memory block allocated via a given
291 /// allocator `a` and layout `k` where `a.usable_size(k)` returns
292 /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
293 /// layout in the size range [l, u].
294 ///
295 /// (All implementors of `usable_size` must ensure that
296 /// `l <= k.size() <= u`)
297 ///
298 /// Both the lower- and upper-bounds (`l` and `u` respectively)
299 /// are provided, because an allocator based on size classes could
300 /// misbehave if one attempts to deallocate a block without
301 /// providing a correct value for its size (i.e., one within the
302 /// range `[l, u]`).
303 ///
304 /// Clients who wish to make use of excess capacity are encouraged
305 /// to use the `alloc_excess` and `realloc_excess` instead, as
306 /// this method is constrained to report conservative values that
307 /// serve as valid bounds for *all possible* allocation method
308 /// calls.
309 ///
310 /// However, for clients that do not wish to track the capacity
311 /// returned by `alloc_excess` locally, this method is likely to
312 /// produce useful results.
313 #[inline]
314 fn usable_size(&self, layout: &Layout) -> (usize, usize) {
315 (layout.size(), layout.size())
316 }
317
318 // == METHODS FOR MEMORY REUSE ==
319 // realloc. alloc_excess, realloc_excess
320
321 /// Returns a pointer suitable for holding data described by
322 /// a new layout with `layout`’s alignment and a size given
323 /// by `new_size`. To
324 /// accomplish this, this may extend or shrink the allocation
325 /// referenced by `ptr` to fit the new layout.
326 ///
327 /// If this returns `Ok`, then ownership of the memory block
328 /// referenced by `ptr` has been transferred to this
329 /// allocator. The memory may or may not have been freed, and
330 /// should be considered unusable (unless of course it was
331 /// transferred back to the caller again via the return value of
332 /// this method).
333 ///
334 /// If this method returns `Err`, then ownership of the memory
335 /// block has not been transferred to this allocator, and the
336 /// contents of the memory block are unaltered.
337 ///
338 /// # Safety
339 ///
340 /// This function is unsafe because undefined behavior can result
341 /// if the caller does not ensure all of the following:
342 ///
343 /// * `ptr` must be currently allocated via this allocator,
344 ///
345 /// * `layout` must *fit* the `ptr` (see above). (The `new_size`
346 /// argument need not fit it.)
347 ///
348 /// * `new_size` must be greater than zero.
349 ///
350 /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
351 /// must not overflow (i.e. the rounded value must be less than `usize::MAX`).
352 ///
353 /// (Extension subtraits might provide more specific bounds on
354 /// behavior, e.g. guarantee a sentinel address or a null pointer
355 /// in response to a zero-size allocation request.)
356 ///
357 /// # Errors
358 ///
359 /// Returns `Err` only if the new layout
360 /// does not meet the allocator's size
361 /// and alignment constraints of the allocator, or if reallocation
362 /// otherwise fails.
363 ///
364 /// Implementations are encouraged to return `Err` on memory
365 /// exhaustion rather than panicking or aborting, but this is not
366 /// a strict requirement. (Specifically: it is *legal* to
367 /// implement this trait atop an underlying native allocation
368 /// library that aborts on memory exhaustion.)
369 ///
370 /// Clients wishing to abort computation in response to a
371 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
372 /// rather than directly invoking `panic!` or similar.
373 ///
374 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
375 unsafe fn realloc(
376 &mut self,
377 ptr: NonNull<u8>,
378 layout: Layout,
379 new_size: usize,
380 ) -> Result<NonNull<u8>, AllocErr> {
381 let old_size = layout.size();
382
383 if new_size >= old_size {
384 if let Ok(()) = self.grow_in_place(ptr, layout, new_size) {
385 return Ok(ptr);
386 }
387 } else if new_size < old_size {
388 if let Ok(()) = self.shrink_in_place(ptr, layout, new_size) {
389 return Ok(ptr);
390 }
391 }
392
393 // otherwise, fall back on alloc + copy + dealloc.
394 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
395 let result = self.alloc(new_layout);
396 if let Ok(new_ptr) = result {
397 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), cmp::min(old_size, new_size));
398 self.dealloc(ptr, layout);
399 }
400 result
401 }
402
403 /// Behaves like `alloc`, but also ensures that the contents
404 /// are set to zero before being returned.
405 ///
406 /// # Safety
407 ///
408 /// This function is unsafe for the same reasons that `alloc` is.
409 ///
410 /// # Errors
411 ///
412 /// Returning `Err` indicates that either memory is exhausted or
413 /// `layout` does not meet allocator's size or alignment
414 /// constraints, just as in `alloc`.
415 ///
416 /// Clients wishing to abort computation in response to an
417 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
418 /// rather than directly invoking `panic!` or similar.
419 ///
420 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
421 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
422 let size = layout.size();
423 let p = self.alloc(layout);
424 if let Ok(p) = p {
425 ptr::write_bytes(p.as_ptr(), 0, size);
426 }
427 p
428 }
429
430 /// Behaves like `alloc`, but also returns the whole size of
431 /// the returned block. For some `layout` inputs, like arrays, this
432 /// may include extra storage usable for additional data.
433 ///
434 /// # Safety
435 ///
436 /// This function is unsafe for the same reasons that `alloc` is.
437 ///
438 /// # Errors
439 ///
440 /// Returning `Err` indicates that either memory is exhausted or
441 /// `layout` does not meet allocator's size or alignment
442 /// constraints, just as in `alloc`.
443 ///
444 /// Clients wishing to abort computation in response to an
445 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
446 /// rather than directly invoking `panic!` or similar.
447 ///
448 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
449 unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
450 let usable_size = self.usable_size(&layout);
451 self.alloc(layout).map(|p| Excess(p, usable_size.1))
452 }
453
454 /// Behaves like `realloc`, but also returns the whole size of
455 /// the returned block. For some `layout` inputs, like arrays, this
456 /// may include extra storage usable for additional data.
457 ///
458 /// # Safety
459 ///
460 /// This function is unsafe for the same reasons that `realloc` is.
461 ///
462 /// # Errors
463 ///
464 /// Returning `Err` indicates that either memory is exhausted or
465 /// `layout` does not meet allocator's size or alignment
466 /// constraints, just as in `realloc`.
467 ///
468 /// Clients wishing to abort computation in response to a
469 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
470 /// rather than directly invoking `panic!` or similar.
471 ///
472 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
473 unsafe fn realloc_excess(
474 &mut self,
475 ptr: NonNull<u8>,
476 layout: Layout,
477 new_size: usize,
478 ) -> Result<Excess, AllocErr> {
479 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
480 let usable_size = self.usable_size(&new_layout);
481 self.realloc(ptr, layout, new_size)
482 .map(|p| Excess(p, usable_size.1))
483 }
484
485 /// Attempts to extend the allocation referenced by `ptr` to fit `new_size`.
486 ///
487 /// If this returns `Ok`, then the allocator has asserted that the
488 /// memory block referenced by `ptr` now fits `new_size`, and thus can
489 /// be used to carry data of a layout of that size and same alignment as
490 /// `layout`. (The allocator is allowed to
491 /// expend effort to accomplish this, such as extending the memory block to
492 /// include successor blocks, or virtual memory tricks.)
493 ///
494 /// Regardless of what this method returns, ownership of the
495 /// memory block referenced by `ptr` has not been transferred, and
496 /// the contents of the memory block are unaltered.
497 ///
498 /// # Safety
499 ///
500 /// This function is unsafe because undefined behavior can result
501 /// if the caller does not ensure all of the following:
502 ///
503 /// * `ptr` must be currently allocated via this allocator,
504 ///
505 /// * `layout` must *fit* the `ptr` (see above); note the
506 /// `new_size` argument need not fit it,
507 ///
508 /// * `new_size` must not be less than `layout.size()`,
509 ///
510 /// # Errors
511 ///
512 /// Returns `Err(CannotReallocInPlace)` when the allocator is
513 /// unable to assert that the memory block referenced by `ptr`
514 /// could fit `layout`.
515 ///
516 /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
517 /// function; clients are expected either to be able to recover from
518 /// `grow_in_place` failures without aborting, or to fall back on
519 /// another reallocation method before resorting to an abort.
520 unsafe fn grow_in_place(
521 &mut self,
522 ptr: NonNull<u8>,
523 layout: Layout,
524 new_size: usize,
525 ) -> Result<(), CannotReallocInPlace> {
526 let _ = ptr; // this default implementation doesn't care about the actual address.
527 debug_assert!(new_size >= layout.size());
528 let (_l, u) = self.usable_size(&layout);
529 // _l <= layout.size() [guaranteed by usable_size()]
530 // layout.size() <= new_layout.size() [required by this method]
531 if new_size <= u {
532 Ok(())
533 } else {
534 Err(CannotReallocInPlace)
535 }
536 }
537
538 /// Attempts to shrink the allocation referenced by `ptr` to fit `new_size`.
539 ///
540 /// If this returns `Ok`, then the allocator has asserted that the
541 /// memory block referenced by `ptr` now fits `new_size`, and
542 /// thus can only be used to carry data of that smaller
543 /// layout. (The allocator is allowed to take advantage of this,
544 /// carving off portions of the block for reuse elsewhere.) The
545 /// truncated contents of the block within the smaller layout are
546 /// unaltered, and ownership of block has not been transferred.
547 ///
548 /// If this returns `Err`, then the memory block is considered to
549 /// still represent the original (larger) `layout`. None of the
550 /// block has been carved off for reuse elsewhere, ownership of
551 /// the memory block has not been transferred, and the contents of
552 /// the memory block are unaltered.
553 ///
554 /// # Safety
555 ///
556 /// This function is unsafe because undefined behavior can result
557 /// if the caller does not ensure all of the following:
558 ///
559 /// * `ptr` must be currently allocated via this allocator,
560 ///
561 /// * `layout` must *fit* the `ptr` (see above); note the
562 /// `new_size` argument need not fit it,
563 ///
564 /// * `new_size` must not be greater than `layout.size()`
565 /// (and must be greater than zero),
566 ///
567 /// # Errors
568 ///
569 /// Returns `Err(CannotReallocInPlace)` when the allocator is
570 /// unable to assert that the memory block referenced by `ptr`
571 /// could fit `layout`.
572 ///
573 /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
574 /// function; clients are expected either to be able to recover from
575 /// `shrink_in_place` failures without aborting, or to fall back
576 /// on another reallocation method before resorting to an abort.
577 unsafe fn shrink_in_place(
578 &mut self,
579 ptr: NonNull<u8>,
580 layout: Layout,
581 new_size: usize,
582 ) -> Result<(), CannotReallocInPlace> {
583 let _ = ptr; // this default implementation doesn't care about the actual address.
584 debug_assert!(new_size <= layout.size());
585 let (l, _u) = self.usable_size(&layout);
586 // layout.size() <= _u [guaranteed by usable_size()]
587 // new_layout.size() <= layout.size() [required by this method]
588 if l <= new_size {
589 Ok(())
590 } else {
591 Err(CannotReallocInPlace)
592 }
593 }
594
595 // == COMMON USAGE PATTERNS ==
596 // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array
597
598 /// Allocates a block suitable for holding an instance of `T`.
599 ///
600 /// Captures a common usage pattern for allocators.
601 ///
602 /// The returned block is suitable for passing to the
603 /// `alloc`/`realloc` methods of this allocator.
604 ///
605 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
606 /// must be considered "currently allocated" and must be
607 /// acceptable input to methods such as `realloc` or `dealloc`,
608 /// *even if* `T` is a zero-sized type. In other words, if your
609 /// `Alloc` implementation overrides this method in a manner
610 /// that can return a zero-sized `ptr`, then all reallocation and
611 /// deallocation methods need to be similarly overridden to accept
612 /// such values as input.
613 ///
614 /// # Errors
615 ///
616 /// Returning `Err` indicates that either memory is exhausted or
617 /// `T` does not meet allocator's size or alignment constraints.
618 ///
619 /// For zero-sized `T`, may return either of `Ok` or `Err`, but
620 /// will *not* yield undefined behavior.
621 ///
622 /// Clients wishing to abort computation in response to an
623 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
624 /// rather than directly invoking `panic!` or similar.
625 ///
626 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
627 fn alloc_one<T>(&mut self) -> Result<NonNull<T>, AllocErr>
628 where
629 Self: Sized,
630 {
631 let k = Layout::new::<T>();
632 if k.size() > 0 {
633 unsafe { self.alloc(k).map(|p| p.cast()) }
634 } else {
635 Err(AllocErr)
636 }
637 }
638
639 /// Deallocates a block suitable for holding an instance of `T`.
640 ///
641 /// The given block must have been produced by this allocator,
642 /// and must be suitable for storing a `T` (in terms of alignment
643 /// as well as minimum and maximum size); otherwise yields
644 /// undefined behavior.
645 ///
646 /// Captures a common usage pattern for allocators.
647 ///
648 /// # Safety
649 ///
650 /// This function is unsafe because undefined behavior can result
651 /// if the caller does not ensure both:
652 ///
653 /// * `ptr` must denote a block of memory currently allocated via this allocator
654 ///
655 /// * the layout of `T` must *fit* that block of memory.
656 unsafe fn dealloc_one<T>(&mut self, ptr: NonNull<T>)
657 where
658 Self: Sized,
659 {
660 let k = Layout::new::<T>();
661 if k.size() > 0 {
662 self.dealloc(ptr.cast(), k);
663 }
664 }
665
666 /// Allocates a block suitable for holding `n` instances of `T`.
667 ///
668 /// Captures a common usage pattern for allocators.
669 ///
670 /// The returned block is suitable for passing to the
671 /// `alloc`/`realloc` methods of this allocator.
672 ///
673 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
674 /// must be considered "currently allocated" and must be
675 /// acceptable input to methods such as `realloc` or `dealloc`,
676 /// *even if* `T` is a zero-sized type. In other words, if your
677 /// `Alloc` implementation overrides this method in a manner
678 /// that can return a zero-sized `ptr`, then all reallocation and
679 /// deallocation methods need to be similarly overridden to accept
680 /// such values as input.
681 ///
682 /// # Errors
683 ///
684 /// Returning `Err` indicates that either memory is exhausted or
685 /// `[T; n]` does not meet allocator's size or alignment
686 /// constraints.
687 ///
688 /// For zero-sized `T` or `n == 0`, may return either of `Ok` or
689 /// `Err`, but will *not* yield undefined behavior.
690 ///
691 /// Always returns `Err` on arithmetic overflow.
692 ///
693 /// Clients wishing to abort computation in response to an
694 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
695 /// rather than directly invoking `panic!` or similar.
696 ///
697 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
698 fn alloc_array<T>(&mut self, n: usize) -> Result<NonNull<T>, AllocErr>
699 where
700 Self: Sized,
701 {
702 match Layout::array::<T>(n) {
703 Ok(layout) if layout.size() > 0 => unsafe { self.alloc(layout).map(|p| p.cast()) },
704 _ => Err(AllocErr),
705 }
706 }
707
708 /// Reallocates a block previously suitable for holding `n_old`
709 /// instances of `T`, returning a block suitable for holding
710 /// `n_new` instances of `T`.
711 ///
712 /// Captures a common usage pattern for allocators.
713 ///
714 /// The returned block is suitable for passing to the
715 /// `alloc`/`realloc` methods of this allocator.
716 ///
717 /// # Safety
718 ///
719 /// This function is unsafe because undefined behavior can result
720 /// if the caller does not ensure all of the following:
721 ///
722 /// * `ptr` must be currently allocated via this allocator,
723 ///
724 /// * the layout of `[T; n_old]` must *fit* that block of memory.
725 ///
726 /// # Errors
727 ///
728 /// Returning `Err` indicates that either memory is exhausted or
729 /// `[T; n_new]` does not meet allocator's size or alignment
730 /// constraints.
731 ///
732 /// For zero-sized `T` or `n_new == 0`, may return either of `Ok` or
733 /// `Err`, but will *not* yield undefined behavior.
734 ///
735 /// Always returns `Err` on arithmetic overflow.
736 ///
737 /// Clients wishing to abort computation in response to a
738 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
739 /// rather than directly invoking `panic!` or similar.
740 ///
741 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
742 unsafe fn realloc_array<T>(
743 &mut self,
744 ptr: NonNull<T>,
745 n_old: usize,
746 n_new: usize,
747 ) -> Result<NonNull<T>, AllocErr>
748 where
749 Self: Sized,
750 {
751 match (Layout::array::<T>(n_old), Layout::array::<T>(n_new)) {
752 (Ok(ref k_old), Ok(ref k_new)) if k_old.size() > 0 && k_new.size() > 0 => {
753 debug_assert!(k_old.align() == k_new.align());
754 self.realloc(ptr.cast(), k_old.clone(), k_new.size())
755 .map(NonNull::cast)
756 }
757 _ => Err(AllocErr),
758 }
759 }
760
761 /// Deallocates a block suitable for holding `n` instances of `T`.
762 ///
763 /// Captures a common usage pattern for allocators.
764 ///
765 /// # Safety
766 ///
767 /// This function is unsafe because undefined behavior can result
768 /// if the caller does not ensure both:
769 ///
770 /// * `ptr` must denote a block of memory currently allocated via this allocator
771 ///
772 /// * the layout of `[T; n]` must *fit* that block of memory.
773 ///
774 /// # Errors
775 ///
776 /// Returning `Err` indicates that either `[T; n]` or the given
777 /// memory block does not meet allocator's size or alignment
778 /// constraints.
779 ///
780 /// Always returns `Err` on arithmetic overflow.
781 unsafe fn dealloc_array<T>(&mut self, ptr: NonNull<T>, n: usize) -> Result<(), AllocErr>
782 where
783 Self: Sized,
784 {
785 match Layout::array::<T>(n) {
786 Ok(k) if k.size() > 0 => {
787 self.dealloc(ptr.cast(), k);
788 Ok(())
789 }
790 _ => Err(AllocErr),
791 }
792 }
793}