Can we add `Layout` to `core::alloc::AllocError`?

I think an alloc error with Layout is more useful. We can see that TryReserveErrorKind::AllocError{..} also contains Layout.

For example, Box::try_new() returns AllocError without layout. If we want to return an alloc error with layout, we need to do like this:

enum CustomError {
    AllocError(layout),
}

fn example() -> Result<Box<i32>, CustomError> {
    Box::try_new(10_i32).map_err(|_| CustomError::AllocError(Layout::new::<i32>()))
}

Note that we have to use map_err everywhere.

If AllocError defined as AllocError(Layout), we can directly use ?:

impl From<AllocError> for CustomError {
    fn from(e: AllocError) -> Self {
        CustomError::AllocError(e.layout())
    }
}

fn example() -> Result<Box<i32>, CustomError> {
    Ok(Box::try_new(10_i32)?)
}

So I suggest AllocError defined as belows:

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(transparent)]
pub struct AllocError(Layout);

impl AllocError {
    #[must_use]
    #[inline]
    pub const fn new(layout: Layout) -> Self {
        AllocError(layout)
    }

    #[must_use]
    #[inline]
    pub const fn layout(self) -> Layout {
        self.0
    }
}

It's important for AllocError to be a ZST, so Result<NonNull<u8>, AllocError> is just a nullable *mut u8. Whenever you use the GlobalAlloc/Allocator APIs, which are those that return AllocError, you necessarily have the layout already in order to provide it.

Rather, this is an argument that try_new should also return TryReserveError (or a similar error) which wraps AllocError with a Layout. Modulo naming being hard, of course.

Personally, with the (pending) decision to move the isize::MAX limit into Layout, I think the richer error type should be (modulo naming being hard)

enum CollectionAllocError {
    /// The requested size is to big for a Rust object.
    LayoutError,
    /// The requested allocation failed.
    AllocError(Layout),
}

There's (in face of custom allocators) not really a difference between "capacity overflow" and an allocation error.

(Disclaimer: this is my own opinion, not that of wg-allocators)

5 Likes

It makes sense, thank you!

BTW, what do you want to use the Layout for when you handle the alloc error?

I'm collecting use-cases for the error API.

1 Like

Just report an error or write a log with layout. I want to tell the user or client not only there is an alloc error, but also the required layout when the error occurred.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.