Question on RawVec::alloc_guard

Hello folks,

I hope this is the right forum for this question. I’ve been poking around the internals of RawVec and am confused about alloc_guard. The code in question is:

// We need to guarantee the following:
// * We don't ever allocate `> isize::MAX` byte-size objects
// * We don't overflow `usize::MAX` and actually allocate too little
// On 64-bit we just need to check for overflow since trying to allocate
// `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add
// an extra guard for this in case we're running on a platform which can use
// all 4GB in user-space. e.g. PAE or x32

fn alloc_guard(alloc_size: usize) {
    if mem::size_of::<usize>() < 8 {
            alloc_size <= ::core::isize::MAX as usize,
            "capacity overflow"


Concerning the second guarantee “We don’t overflow usize::MAX and actually allocate too little”, is that checked here? If so, how? Seems like with that first branch the function bails out immediately when the system is 64 bit or greater.

Concerning the first guarantee, what’s special about > isize::MAX byte-sized objects?

As far as I can tell, the 2nd guarantee is not enforced in this function, but elsewhere. Search for "capacity overflow" in and observe the use of checked_* arithmetic.

Regarding the first guarantee, I think that’s so that it’s always valid to use an isize offset from any point in the vec to any other point; see the Rust Reference.

1 Like

Ah, perfect. Cleared up both questions. Thank you!

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