Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rust guarantee that elements of a Vec smaller than a word size will be tightly packed?

Tags:

rust

How much space the contents of a Vec<u16> takes? With, say, 1000 elements. Is there a way to verify this with a test program?

Is this guaranteed to be the same as &[u16]? (I think it would make no sense to not be, since the conversion is cheap)

Also Vec[u8], &[u8], etc.

(std::mem::size_of returns the static size of the type, not of its contents)

like image 352
darque Avatar asked Nov 17 '25 08:11

darque


1 Answers

Yes.

The representation of the contents of a vector is the same as that of a slice, which is the same as that of a fixed-size array. Thus you may compare std::mem::size_of::<[u16, 1]>() and std::mem::size_of::<[u16, 10]>() and see that they always differ by a factor of ten. (Citation: this code.)

Rust uses byte indexing, so u8 takes one byte, u16 takes two bytes, u32 takes four bytes and u64 takes eight bytes. bool also takes one byte; there are seven wasted bits per byte (hence types like the currently unstable BitVec).

like image 70
Chris Morgan Avatar answered Nov 20 '25 00:11

Chris Morgan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!