alloc_traits/
util.rs

1//! Various utilities such as default implementations.
2
3/// Implementations of default items of traits.
4///
5/// It is expected that these might be used as a fallback 'super' call of sorts on trait
6/// implementors to opportunistically do some form of optimization.
7pub mod defaults {
8    /// Default implementations for the `LocalAlloc` trait.
9    ///
10    /// See [`LocalAlloc`] for more information. The methods called by the functions in this module
11    /// are documented and will not change between non-breaking releases, if at all. Rather new
12    /// variants may be added that call additional methods that might be more efficient. This
13    /// avoids accidentally creating a dependency loop in implementors.
14    ///
15    /// [`LocalAlloc`]: ../../../trait.LocalAlloc.html
16    pub mod local {
17        use core::ptr::{copy_nonoverlapping, write_bytes};
18        use crate::NonZeroLayout;
19        use crate::local::{LocalAlloc, Allocation};
20
21        /// Allocate a block of memory initialized with zeros.
22        ///
23        /// See [`LocalAlloc::alloc_zeroed`] for more information. This is a default implementation
24        /// that might be less efficient than a dedicated one. It only uses the `alloc` method.
25        ///
26        /// [`LocalAlloc::alloc_zeroed`]: ../../../trait.LocalAlloc.html
27        pub fn alloc_zeroed<'alloc, Alloc>(
28            this: &'alloc Alloc,
29            layout: NonZeroLayout
30        ) -> Option<Allocation<'alloc>>
31        where
32            Alloc: LocalAlloc<'alloc> + ?Sized,
33        {
34            let allocation = this.alloc(layout)?;
35            unsafe {
36                write_bytes(allocation.ptr.as_ptr(), 0u8, allocation.layout.size().into());
37            }
38            Some(allocation)
39        }
40
41        /// Change the layout of a block previously allocated.
42        ///
43        /// See [`LocalAlloc::realloc`] for more information. This is a default implementation that
44        /// might be less efficient than a dedicated one. It only uses the `alloc` and `dealloc`
45        /// methods.
46        ///
47        /// # Safety
48        /// See the trait.
49        ///
50        /// [`LocalAlloc::realloc`]: ../../../trait.LocalAlloc.html
51        pub unsafe fn realloc<'alloc, Alloc>(
52            this: &'alloc Alloc,
53            alloc: Allocation<'alloc>,
54            layout: NonZeroLayout
55        ) -> Option<Allocation<'alloc>>
56        where
57            Alloc: LocalAlloc<'alloc> + ?Sized,
58        {
59            let new_alloc = this.alloc(layout)?;
60            copy_nonoverlapping(
61                alloc.ptr.as_ptr(),
62                new_alloc.ptr.as_ptr(),
63                core::cmp::min(layout.size(), alloc.layout.size()).get());
64            this.dealloc(alloc);
65            Some(new_alloc)
66        }
67    }
68}