Why the mixture of <u8> and <[u8]> in std::alloc::Allocator

This isn't a problem or anything, just curiosity. The functions in the trait

take NonNull<u8> as parameters but return NonNull<[u8]> results.

For example:

    unsafe fn grow(
        &self,
        ptr: NonNull<u8>,
        old_layout: Layout,
        new_layout: Layout
    ) -> Result<NonNull<[u8]>, AllocError> { ... }

I was wondering why. It seems inconsistent for no reason obvious to me, not sure what I am missing!

1 Like

I think this is just because the returned slice doesn't necessarily have the same size as new_layout specified, so the function needs to return a length, and putting it in a fat pointer is an easy, unambiguous way to do it.

3 Likes

As per the docs:

Returns a new NonNull<[u8]> containing a pointer and the actual size of the allocated memory.

  • ptr must denote a block of memory currently allocated via this allocator.
  • old_layout must fit that block of memory (The new_layout argument need not fit it.).

And in particular behind the "fit" link:

  • The block must be allocated with the same alignment as layout.align(), and
  • The provided layout.size() must fall in the range min ..= max, where:
    • min is the size of the layout most recently used to allocate the block, and
    • max is the latest actual size returned from allocate, grow, or shrink.

Forcing the callers to construct a slice pointer in order to specify a specific length would be redundant (and add a need for additional checks -- what if the slice length and old_layout were incompatible?).

Also, returning the length allows, for example, a Vec implementation to take advantage of the excess memory returned by calculating a larger capacity than requested.

And then the leniency of "fitting" allows, for example, the Vec to just use that larger capacity to create old_layout when growing in the future, instead of having to remember either the requested layout or the returned length from last time.

3 Likes

Ah! That text isn't included for the first function ( allocate ), which is maybe why I missed it.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.