1 // SPDX-License-Identifier: GPL-2.0
5 //! Custom layout types extending or improving [`Layout`].
7 use core::{alloc::Layout, marker::PhantomData};
9 /// Error when constructing an [`ArrayLayout`].
10 pub struct LayoutError;
12 /// A layout for an array `[T; n]`.
16 /// - `len * size_of::<T>() <= isize::MAX`.
17 pub struct ArrayLayout<T> {
19 _phantom: PhantomData<fn() -> T>,
22 impl<T> Clone for ArrayLayout<T> {
23 fn clone(&self) -> Self {
27 impl<T> Copy for ArrayLayout<T> {}
29 const ISIZE_MAX: usize = isize::MAX as usize;
31 impl<T> ArrayLayout<T> {
32 /// Creates a new layout for `[T; 0]`.
33 pub const fn empty() -> Self {
34 // INVARIANT: `0 * size_of::<T>() <= isize::MAX`.
37 _phantom: PhantomData,
41 /// Creates a new layout for `[T; len]`.
45 /// When `len * size_of::<T>()` overflows or when `len * size_of::<T>() > isize::MAX`.
46 pub const fn new(len: usize) -> Result<Self, LayoutError> {
47 match len.checked_mul(core::mem::size_of::<T>()) {
48 Some(size) if size <= ISIZE_MAX => {
49 // INVARIANT: We checked above that `len * size_of::<T>() <= isize::MAX`.
52 _phantom: PhantomData,
55 _ => Err(LayoutError),
59 /// Creates a new layout for `[T; len]`.
63 /// `len` must be a value, for which `len * size_of::<T>() <= isize::MAX` is true.
64 pub unsafe fn new_unchecked(len: usize) -> Self {
65 // INVARIANT: By the safety requirements of this function
66 // `len * size_of::<T>() <= isize::MAX`.
69 _phantom: PhantomData,
73 /// Returns the number of array elements represented by this layout.
74 pub const fn len(&self) -> usize {
78 /// Returns `true` when no array elements are represented by this layout.
79 pub const fn is_empty(&self) -> bool {
84 impl<T> From<ArrayLayout<T>> for Layout {
85 fn from(value: ArrayLayout<T>) -> Self {
86 let res = Layout::array::<T>(value.len);
87 // SAFETY: By the type invariant of `ArrayLayout` we have
88 // `len * size_of::<T>() <= isize::MAX` and thus the result must be `Ok`.
89 unsafe { res.unwrap_unchecked() }