Maximum size of an array in 32 bits?

后端 未结 2 893
旧时难觅i
旧时难觅i 2020-12-20 13:54

According to the Rust Reference:

The isize type is a signed integer type with the same number of bits as the platform\'s pointer type. Th

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-20 14:30

    The internals of Vec do cap the value to 4GB, both in with_capacity and grow_capacity, using

    let size = capacity.checked_mul(mem::size_of::())
                       .expect("capacity overflow");
    

    which will panic if the pointer overflows.

    As such, Vec-allocated slices are also capped in this way in Rust. Given that this is because of an underlying restriction in the allocation API, I would be surprised if any typical type could circumvent this. And if they did, Index on slices would be unsafe due to pointer overflow. So I hope not.

    It might still not be possible to allocate all 4GB for other reasons, though. In particular, allocate won't let you allocate more than 2GB (isize::MAX bytes), so Vec is restricted to that.

提交回复
热议问题