Blog

Part 27 · Memory Layout in Rust: size_of, Alignment and Free Option<&T>

Two structs with the same three fields can have different sizes. This part covers size_of, alignment, padding, how Rust lays out enums, and why an Option of a reference costs no extra bytes.

Every value in Rust has a size in bytes and an address it’s allowed to start at. Most of the time you never think about either. But they decide how much memory a Vec of a million items takes, why one enum is 16 bytes and a similar one is 1,004, and why Option<&T> costs nothing at all.

This part covers size_of and align_of, the padding the compiler adds between fields, how you can see it with offset_of!, how enums are laid out, the “niche” trick behind free Options, zero-sized types, and why any of this matters for speed. It builds on struct padding from Part 10, Box from Part 20 and fat pointers from Part 21. Every program here was run on Rust 1.95, on a 64-bit machine, and its output is pasted from the run.

Try this first

These two structs have the same three fields in the same order. The only difference is the #[repr(C)] line on the second one. A u8 is 1 byte and a u32 is 4. Guess what each line prints:

use std::mem::size_of;

#[allow(dead_code)]
struct Plain {
    a: u8,
    b: u32,
    c: u8,
}

#[allow(dead_code)]
#[repr(C)]
struct LikeC {
    a: u8,
    b: u32,
    c: u8,
}

fn main() {
    println!("fields add up to {} bytes", 1 + 4 + 1);
    println!("Plain: {} bytes", size_of::<Plain>());
    println!("LikeC: {} bytes", size_of::<LikeC>());
}

It prints:

fields add up to 6 bytes
Plain: 8 bytes
LikeC: 12 bytes

Neither struct is 6 bytes, and the two aren’t even the same size. (The #[allow(dead_code)] line tells the compiler we never read the fields on purpose. Without it, clippy would stop the build with a warning.)

By the end of this part you’ll be able to work out both numbers by hand. Two ideas explain them: alignment, and the freedom Rust has to reorder fields.

size_of and align_of

std::mem::size_of::<T>() returns how many bytes a value of type T takes. std::mem::align_of::<T>() returns its alignment: the number that its address must be a multiple of.

use std::mem::{align_of, size_of};

fn row<T>(name: &str) {
    println!("{name:<6} {:>4}  {:>5}", size_of::<T>(), align_of::<T>());
}

fn main() {
    println!("type   size  align");
    row::<u8>("u8");
    row::<u16>("u16");
    row::<u32>("u32");
    row::<u64>("u64");
    row::<usize>("usize");
    row::<f64>("f64");
    row::<bool>("bool");
    row::<char>("char");
    row::<&u8>("&u8");
}

It prints:

type   size  align
u8        1      1
u16       2      2
u32       4      4
u64       8      8
usize     8      8
f64       8      8
bool      1      1
char      4      4
&u8       8      8

usize and references are 8 bytes because this is a 64-bit machine. On a 32-bit machine they’d be 4. For the plain number types, size and alignment are the same number. That isn’t true of structs, as we’ll see.

Why a u32 wants an address that’s a multiple of 4

The processor doesn’t read memory one byte at a time. It reads in small aligned chunks. A u32 that starts at address 8 sits inside one chunk, and one read fetches it. A u32 that starts at address 6 would straddle two chunks, so the processor would need two reads and some shifting to put the value together. Some processors do that slowly. Some refuse and stop the program.

Rust avoids the question. In safe code, every value sits at an address that’s a multiple of its alignment. A u32 lives at 0, 4, 8, 12 and so on. A u64 lives at a multiple of 8. A u8 can go anywhere.

There’s a second rule that follows from the first. A type’s size is always a multiple of its alignment. That way, in an array, where items sit side by side with no gaps, every item starts at a properly aligned address.

Padding: where the missing bytes went

Now we can work out LikeC. #[repr(C)] tells Rust to lay the struct out the way C does: fields in the order you wrote them, each one at the next address that suits its alignment.

  1. a is a u8. It goes at offset 0. (An offset is how many bytes from the start of the struct.)
  2. b is a u32. The next free byte is 1, but b needs a multiple of 4. So bytes 1, 2 and 3 are skipped, and b takes bytes 4 to 7.
  3. c is a u8. It takes byte 8.
  4. The struct’s alignment is the largest of its fields’ alignments, 4. Its size must be a multiple of 4, so bytes 9, 10 and 11 are added at the end. The size is 12.

The skipped bytes are padding. Nothing is stored in them. They exist only to keep b aligned, in this struct and in the next one along in an array.

The default layout, the one you get without #[repr(...)], is allowed to reorder the fields. Rust 1.95 puts b first. Then a and c fit in bytes 4 and 5, and 2 bytes of padding round the size up to 8. The animation shows both.

#[repr(C)] struct S { a: u8, b: u32, c: u8 } struct S { a: u8, b: u32, c: u8 } (default layout) bytes 0 1 2 3 4 5 6 7 8 9 10 11 a padding b: u32 c padding b: u32 a c padding offset of a: 0 offset of b: 4, and bytes 1 to 3 are padding size 12, of which 6 bytes are padding size 8, of which 2 bytes are padding repr(C) keeps the order: a, a u8, goes in byte 0 b is a u32: it must start at a multiple of 4 c takes byte 8; tail padding makes the size a multiple of 4 the default layout may reorder: b first, then a and c

With #[repr(C)], the fields keep their order and the struct needs 6 bytes of padding. With the default layout, Rust moves the u32 to the front and needs only 2.

Here are those steps in words, in case the animation doesn’t play for you:

  1. With #[repr(C)], the fields go in the order written. a is a u8, so it takes byte 0.
  2. b is a u32 and must start at a multiple of 4. Bytes 1, 2 and 3 become padding, and b takes bytes 4 to 7.
  3. c takes byte 8. The size must be a multiple of 4, the struct’s alignment, so bytes 9, 10 and 11 become tail padding. The size is 12.
  4. With the default layout, Rust is free to reorder the fields. It puts b in bytes 0 to 3, a in byte 4 and c in byte 5. Bytes 6 and 7 are padding, and the size is 8.

A warning about step 4. The default layout is unspecified. The Rust reference promises only that each field is aligned and that fields don’t overlap. It doesn’t promise an order, and the compiler may change its choice in a future version. So 8 bytes is what Rust 1.95 does, not a rule you can build on. When the order matters, because the bytes go to C code, to a file or across a network, write #[repr(C)].

Seeing the offsets with offset_of!

You don’t have to take the animation on trust. std::mem::offset_of! takes a type and a field name and gives the field’s offset. It has been stable since Rust 1.77.

use std::mem::{offset_of, size_of};

#[allow(dead_code)]
struct Plain {
    a: u8,
    b: u32,
    c: u8,
}

#[allow(dead_code)]
#[repr(C)]
struct LikeC {
    a: u8,
    b: u32,
    c: u8,
}

fn main() {
    println!(
        "LikeC: a at {}, b at {}, c at {}, size {}",
        offset_of!(LikeC, a),
        offset_of!(LikeC, b),
        offset_of!(LikeC, c),
        size_of::<LikeC>()
    );
    println!(
        "Plain: a at {}, b at {}, c at {}, size {}",
        offset_of!(Plain, a),
        offset_of!(Plain, b),
        offset_of!(Plain, c),
        size_of::<Plain>()
    );
}

It prints:

LikeC: a at 0, b at 4, c at 8, size 12
Plain: a at 4, b at 0, c at 5, size 8

The LikeC line will be the same on every compiler, because #[repr(C)] fixes it. The Plain line is what Rust 1.95 chose. The struct you wrote in Part 10, a String, a u32 and a bool in 32 bytes, follows the same rules: 29 bytes of fields, rounded up to a multiple of 8.

Enums: a tag plus the largest variant

An enum value must have room for any of its variants, and it must remember which one it holds. So the usual layout is a tag, a small number that says which variant this is, followed by enough space for the largest variant.

use std::mem::size_of;

#[allow(dead_code)]
enum Shape {
    Dot,
    Circle(f64),
    Rect(f64, f64),
}

#[allow(dead_code)]
enum Direction {
    North,
    East,
    South,
    West,
}

fn main() {
    println!("f64:       {} bytes", size_of::<f64>());
    println!("Shape:     {} bytes", size_of::<Shape>());
    println!("Direction: {} bytes", size_of::<Direction>());
}

It prints:

f64:       8 bytes
Shape:     24 bytes
Direction: 1 bytes

The largest variant of Shape is Rect, at 16 bytes. The tag needs only one byte, but the f64s after it must be aligned to 8, so the tag effectively takes 8. That’s 24. A Dot takes 24 bytes too. Every value of an enum is the same size, whichever variant it holds.

Direction has no data at all, so it’s only a tag, and four variants fit in one byte. (Yes, “1 bytes”. We kept every line in the same format.)

The niche: why Option<&T> costs nothing

Option<T> is an enum with two variants, None and Some(T). By the rule above, Option<u32> should be a tag plus 4 bytes, rounded up to 8. It is. But look at the other lines:

use std::mem::size_of;
use std::num::NonZeroU32;

fn show<T>(name: &str) {
    println!("{name:<20}{} bytes", size_of::<T>());
}

fn main() {
    show::<u32>("u32:");
    show::<Option<u32>>("Option<u32>:");
    show::<&u32>("&u32:");
    show::<Option<&u32>>("Option<&u32>:");
    show::<Box<u32>>("Box<u32>:");
    show::<Option<Box<u32>>>("Option<Box<u32>>:");
    show::<NonZeroU32>("NonZeroU32:");
    show::<Option<NonZeroU32>>("Option<NonZeroU32>:");
    show::<char>("char:");
    show::<Option<char>>("Option<char>:");
    show::<String>("String:");
    show::<Option<String>>("Option<String>:");
}

It prints:

u32:                4 bytes
Option<u32>:        8 bytes
&u32:               8 bytes
Option<&u32>:       8 bytes
Box<u32>:           8 bytes
Option<Box<u32>>:   8 bytes
NonZeroU32:         4 bytes
Option<NonZeroU32>: 4 bytes
char:               4 bytes
Option<char>:       4 bytes
String:             24 bytes
Option<String>:     24 bytes

Only Option<u32> grew. Every other Option is the same size as what it wraps.

The reason is a niche: a bit pattern that a type can never hold. A reference can never be null, so the all-zero address is a niche. Rust uses it to mean None. An Option<&u32> is a plain pointer. Zero means None, and anything else means Some with that address. No tag is needed.

The others have niches too:

  • Box<T> is never null, the same as a reference. So is the pointer inside a String or a Vec, which is why Option<String> is still 24 bytes.
  • NonZeroU32 is a u32 that can’t be 0, so 0 is free to mean None. You make one with NonZeroU32::new(n), which itself returns an Option: None if n is 0.
  • A char holds a Unicode scalar value, which never goes above 0x10FFFF. That leaves billions of unused patterns in its 4 bytes, and None takes one of them.
  • A u32 has no niche. All 4,294,967,296 patterns are valid numbers. So Option<u32> needs a separate tag, and alignment pads it to 8.

For references, Box, NonZero types and a few others, the standard library guarantees this: the docs for Option list them, and they say Option<&T> has the same size as &T. That’s why Rust code uses Option<&T> freely where C code would use a pointer that might be null. You get the null check from the type system and pay nothing for it.

A fun one: Option<Option<bool>>

A bool is one byte, but only two patterns are valid: 0 for false and 1 for true. That leaves 254 niches. Each layer of Option can take one.

use std::mem::size_of;

fn main() {
    println!("bool:                 {}", size_of::<bool>());
    println!("Option<bool>:         {}", size_of::<Option<bool>>());
    let nested = size_of::<Option<Option<bool>>>();
    println!("Option<Option<bool>>: {nested}");
    let values = [Some(Some(true)), Some(Some(false)), Some(None), None];
    for v in values {
        println!("{v:?}");
    }
}

It prints:

bool:                 1
Option<bool>:         1
Option<Option<bool>>: 1
Some(Some(true))
Some(Some(false))
Some(None)
None

Four different values, all in one byte. The compiler picks which unused patterns mean the two Nones. The exact numbers aren’t promised, so don’t depend on them.

Zero-sized types

Some types take no bytes at all. They’re called zero-sized types, or ZSTs:

use std::marker::PhantomData;
use std::mem::size_of;

struct Marker;

fn main() {
    println!("():                  {}", size_of::<()>());
    println!("Marker:              {}", size_of::<Marker>());
    println!("PhantomData<String>: {}", size_of::<PhantomData<String>>());
    println!("[u64; 0]:            {}", size_of::<[u64; 0]>());

    let units: Vec<()> = vec![(); 1_000_000];
    println!("len {}", units.len());
    println!("capacity is usize::MAX: {}", units.capacity() == usize::MAX);
    let _ = Marker;
}

It prints:

():                  0
Marker:              0
PhantomData<String>: 0
[u64; 0]:            0
len 1000000
capacity is usize::MAX: true

() is the unit type from Part 3, what a function returns when it returns nothing. Marker is a unit struct from Part 10. PhantomData<T> is a marker that tells the compiler “act as if this type holds a T” without storing one. You’ll see it in library code that holds raw pointers, which Part 28 introduces.

A Vec<()> with a million items never allocates. Each item is 0 bytes, so a million of them are 0 bytes too. The vector only counts them, and it reports an endless capacity because it can never run out of room.

This isn’t just a curiosity. The standard library’s docs describe HashSet<T> as a HashMap<T, ()>: a map whose values take no space. Zero-sized types let a generic type drop the parts a particular use doesn’t need, at no cost.

Pointers, slices and the 24-byte collections

Part 21 showed that a pointer to a dyn Trait is a fat pointer: two words instead of one. Slices are fat pointers too, an address plus a length. Here are the common pointer-shaped types side by side:

use std::fmt::Debug;
use std::mem::size_of;

fn main() {
    println!("&u8:         {} bytes", size_of::<&u8>());
    println!("Box<u8>:     {} bytes", size_of::<Box<u8>>());
    println!("&[u8]:       {} bytes", size_of::<&[u8]>());
    println!("&str:        {} bytes", size_of::<&str>());
    println!("&dyn Debug:  {} bytes", size_of::<&dyn Debug>());
    println!("Box<[u8]>:   {} bytes", size_of::<Box<[u8]>>());
    println!("Box<str>:    {} bytes", size_of::<Box<str>>());
    println!("Vec<u8>:     {} bytes", size_of::<Vec<u8>>());
    println!("String:      {} bytes", size_of::<String>());
    println!("Vec<String>: {} bytes", size_of::<Vec<String>>());
}

It prints:

&u8:         8 bytes
Box<u8>:     8 bytes
&[u8]:       16 bytes
&str:        16 bytes
&dyn Debug:  16 bytes
Box<[u8]>:   16 bytes
Box<str>:    16 bytes
Vec<u8>:     24 bytes
String:      24 bytes
Vec<String>: 24 bytes
  • A thin pointer (&u8, Box<u8>) is one address: 8 bytes.
  • A pointer to a slice or a str is an address and a length: 16 bytes.
  • A pointer to a dyn value is an address and a vtable pointer: 16 bytes.
  • A Vec or a String is a pointer, a capacity and a length: 24 bytes. That’s true whatever it holds. A Vec<String> is 24 bytes, and each String inside it is 24 more, on the heap.

As Part 6 said, Rust doesn’t promise the order of the three fields inside a Vec or String. Only the size is something you can observe, and only size_of tells you that.

Box<[T]> or Vec<T>?

A Box<[T]> is a slice that owns its heap memory. It’s like a Vec that can’t grow, so it doesn’t need a capacity. That saves 8 bytes per value and, more usefully, any spare capacity:

fn main() {
    let mut v: Vec<u32> = Vec::with_capacity(100);
    v.extend([1, 2, 3]);
    println!("vec:   len {}, capacity {}", v.len(), v.capacity());

    let boxed: Box<[u32]> = v.into_boxed_slice();
    println!("boxed: len {}", boxed.len());
    println!("boxed: {boxed:?}");

    let back: Vec<u32> = boxed.into_vec();
    println!("back:  len {}, capacity {}", back.len(), back.capacity());
}

It prints:

vec:   len 3, capacity 100
boxed: len 3
boxed: [1, 2, 3]
back:  len 3, capacity 3

into_boxed_slice shrinks the buffer to fit before it hands it over. That’s why the vector we get back has a capacity of 3, not 100. Use Box<[T]> (or Box<str>, its string twin) for data that’s built once and then only read, especially when you keep a lot of them. Use Vec<T> while the data is still growing.

#[repr(u8)] on enums

Without a repr, Rust picks the tag’s size and values itself. #[repr(u8)] on an enum with no data fixes the tag as a u8. With it, you can give each variant its own number and convert with as:

use std::mem::size_of;

#[derive(Debug, Clone, Copy)]
#[repr(u8)]
enum Level {
    Debug = 10,
    Info = 20,
    Warn = 30,
    Error = 40,
}

fn main() {
    println!("Level: {} byte", size_of::<Level>());
    for level in [Level::Debug, Level::Info, Level::Warn, Level::Error] {
        println!("{level:?} is stored as {}", level as u8);
    }
}

It prints:

Level: 1 byte
Debug is stored as 10
Info is stored as 20
Warn is stored as 30
Error is stored as 40

Reach for it when the number itself matters: a byte in a file format, a code in a network protocol, a value passed to C. Going the other way, from a u8 to a Level, isn’t automatic, because 15 isn’t a valid Level. You write a match that returns an Option, or implement TryFrom<u8>. Exercise 3 does this.

You can also put #[repr(u8)] (or u16, i32 and so on) on an enum that carries data. Then the tag’s size is fixed, and the reference documents the layout exactly. That’s mostly for code that shares data with C.

Why layout matters

A program that’s correct is correct whatever the layout. Layout matters for speed and memory.

The processor doesn’t fetch single values from main memory. It fetches a cache line, a block that’s often 64 bytes, and keeps it in a small, fast memory called the cache. Reading main memory is far slower than reading the cache. So the more of your data fits in each line, the fewer slow trips the processor makes.

That makes size count when you have many values:

  • A Vec of a million 8-byte structs is 8 MB. The same fields with #[repr(C)] in a bad order, at 12 bytes each, is 12 MB, and a loop over it reads 50% more memory.
  • An enum is as big as its biggest variant. If one rare variant holds a large array, every value pays for it, including the small common ones.

The second problem is common enough that clippy has a lint for it. The next worked example shows it.

Worked example: boxing a large enum variant

Here’s a message type for a small network app. Most messages are Quit or Move. Now and then one carries a 1,000-byte frame:

use std::mem::size_of;

#[allow(clippy::large_enum_variant)]
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Frame([u8; 1000]),
}

fn describe(m: &Message) -> String {
    match m {
        Message::Quit => "quit".to_string(),
        Message::Move { x, y } => format!("move to {x},{y}"),
        Message::Frame(bytes) => format!("frame of {} bytes", bytes.len()),
    }
}

fn main() {
    let inbox = vec![
        Message::Move { x: 1, y: 2 },
        Message::Frame([0; 1000]),
        Message::Quit,
    ];
    for m in &inbox {
        println!("{}", describe(m));
    }
    println!("one Message: {} bytes", size_of::<Message>());
    let total = inbox.len() * size_of::<Message>();
    println!("the inbox's buffer: {total} bytes");
}

It prints:

move to 1,2
frame of 1000 bytes
quit
one Message: 1004 bytes
the inbox's buffer: 3012 bytes

Every message is 1,004 bytes: a 1,000-byte array plus a tag, rounded up to the 4-byte alignment that Move‘s i32s need. A Quit that holds nothing costs the same as a frame.

We had to add #[allow(clippy::large_enum_variant)] to get this past clippy. Without that line, cargo clippy -- -D warnings stops with this:

error: large size difference between variants
 --> src/main.rs:1:1
  |
1 | / enum Message {
2 | |     Quit,
3 | |     Move { x: i32, y: i32 },
  | |     ----------------------- the second-largest variant contains at least 8 bytes
4 | |     Frame([u8; 1000]),
  | |     ----------------- the largest variant contains at least 1000 bytes
5 | | }
  | |_^ the entire enum is at least 1004 bytes
...
help: consider boxing the large fields or introducing indirection in some other way to reduce the total size of the enum
  |
4 -     Frame([u8; 1000]),
4 +     Frame(Box<[u8; 1000]>),

Read it from the top. The first line names the problem. The arrows point at the two biggest variants and their sizes, and the last arrow gives the size of the whole enum. The help: line gives the fix: put the large data in a Box, so the variant holds an 8-byte pointer and the array lives on the heap.

use std::mem::size_of;

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Frame(Box<[u8; 1000]>),
}

fn describe(m: &Message) -> String {
    match m {
        Message::Quit => "quit".to_string(),
        Message::Move { x, y } => format!("move to {x},{y}"),
        Message::Frame(bytes) => format!("frame of {} bytes", bytes.len()),
    }
}

fn main() {
    let inbox = vec![
        Message::Move { x: 1, y: 2 },
        Message::Frame(Box::new([0; 1000])),
        Message::Quit,
    ];
    for m in &inbox {
        println!("{}", describe(m));
    }
    println!("one Message: {} bytes", size_of::<Message>());
    let total = inbox.len() * size_of::<Message>();
    println!("the inbox's buffer: {total} bytes");
}

It prints:

move to 1,2
frame of 1000 bytes
quit
one Message: 16 bytes
the inbox's buffer: 48 bytes

The frame’s 1,000 bytes now live in their own heap allocation, and only the messages that carry a frame pay for one. Everything else costs 16 bytes: 8 for the Box or the two i32s, and 8 for the tag and alignment. The price is one allocation per frame, and one pointer to follow when you read it. For a variant that’s both large and rare, that’s a good trade. If most of your messages were frames, it wouldn’t be.

Worked example: size_of::<str>() doesn’t compile

Not every type has a size you can ask for. Try it with str:

use std::mem::size_of;

fn main() {
    println!("{}", size_of::<str>());
}

It prints:

error[E0277]: the size for values of type `str` cannot be known at compilation time
...
  = help: the trait `Sized` is not implemented for `str`

The first line says it plainly: a str has no size known at compile time. One str might be “hi”, 2 bytes, and another a whole book. The help line names the trait involved. Sized is the trait for types whose size the compiler knows, and size_of::<T>() requires T: Sized. Slices [T] and dyn Trait are unsized too, which is the same reason Part 21 needed a pointer to hold a dyn Shape.

There are two things you can ask instead. You can ask for the size of the pointer, which is always known. Or you can ask for the size of one particular value with size_of_val, which reads it from the fat pointer at run time:

use std::mem::{size_of, size_of_val};

fn main() {
    let short: &str = "hi";
    let long: &str = "a much longer piece of text";
    println!("&str:  {} bytes", size_of::<&str>());
    println!("short: {} bytes", size_of_val(short));
    println!("long:  {} bytes", size_of_val(long));

    let numbers: &[u32] = &[1, 2, 3];
    println!("slice: {} bytes", size_of_val(numbers));
}

It prints:

&str:  16 bytes
short: 2 bytes
long:  27 bytes
slice: 12 bytes

The two &str values are both 16 bytes, but the text they point at is 2 bytes and 27 bytes. size_of_val multiplies the length stored in the fat pointer by the size of one item: three u32s make 12 bytes. For a &dyn Trait, it reads the size from the vtable instead, as Part 21 showed.

Worked example: putting fields in a good order

Here’s a message header that we send to a C program, so it must be #[repr(C)]. Its fields were written in the order someone thought of them:

use std::mem::{offset_of, size_of};

#[allow(dead_code)]
#[repr(C)]
struct Header {
    kind: u8,
    id: u64,
    flags: u8,
    len: u32,
    port: u16,
}

fn main() {
    println!("kind  at {:>2}", offset_of!(Header, kind));
    println!("id    at {:>2}", offset_of!(Header, id));
    println!("flags at {:>2}", offset_of!(Header, flags));
    println!("len   at {:>2}", offset_of!(Header, len));
    println!("port  at {:>2}", offset_of!(Header, port));
    println!("size {}", size_of::<Header>());
}

It prints:

kind  at  0
id    at  8
flags at 16
len   at 20
port  at 24
size 32

The fields add up to 1 + 8 + 1 + 4 + 2 = 16 bytes, but the struct is twice that. kind takes byte 0, and id must start at 8, so 7 bytes are wasted. flags at 16 leaves 3 more before len at 20. port ends at 26, and tail padding rounds 26 up to 32, a multiple of 8.

The fix is the rule of thumb for any #[repr(C)] struct: largest alignment first. Each field then starts where the previous one ended, already aligned:

use std::mem::{offset_of, size_of};

#[allow(dead_code)]
#[repr(C)]
struct Header {
    id: u64,
    len: u32,
    port: u16,
    kind: u8,
    flags: u8,
}

fn main() {
    println!("id    at {:>2}", offset_of!(Header, id));
    println!("len   at {:>2}", offset_of!(Header, len));
    println!("port  at {:>2}", offset_of!(Header, port));
    println!("kind  at {:>2}", offset_of!(Header, kind));
    println!("flags at {:>2}", offset_of!(Header, flags));
    println!("size {}", size_of::<Header>());
}

It prints:

id    at  0
len   at  8
port  at 12
kind  at 14
flags at 15
size 16

No padding at all. A list of a million headers just went from 32 MB to 16 MB.

Without #[repr(C)], you don’t need to do this by hand: the default layout reorders fields for you, and the badly ordered version is 16 bytes too on Rust 1.95. That’s one reason the default layout is unspecified: it leaves the compiler free to pick a good order. Change the order by hand only when you’ve had to write #[repr(C)].

Tips and traps

  • Relying on the default field order. Code that reads a struct’s bytes, sends them over a network or passes them to C, and assumes the order you wrote, can break with a new compiler. Use #[repr(C)] whenever the layout leaves your program.
  • Hard-coding sizes. usize, references and Box are 8 bytes on a 64-bit machine and 4 on a 32-bit one. Write size_of::<T>() instead of a number, and the code stays correct on both.
  • Option<u32> where 0 never happens. If a count or an ID can never be 0, Option<NonZeroU32> is half the size. In a large Vec that adds up. Don’t do it if 0 is a valid value; NonZeroU32::new(0) returns None.
  • One huge variant. Clippy’s large_enum_variant warning means every value pays for the biggest variant. Box the big data, as in the worked example, unless the big variant is the common one.
  • Counting Vec bytes with size_of. size_of::<Vec<T>>() is always 24 on a 64-bit machine. The items are on the heap. For the bytes the items take, multiply len() (or capacity()) by size_of::<T>().
  • Expecting repr(C) to shrink anything. It does the opposite when fields are in a bad order. It gives you a fixed, documented layout, not a small one.

A value’s size is its fields plus the padding that keeps each one aligned, and an Option is free whenever the type inside has a pattern it can never hold.

Exercises

Exercise 1. Without running it, work out what this prints on a 64-bit machine. Use the four steps from the padding section.

use std::mem::size_of;

#[allow(dead_code)]
#[repr(C)]
struct A {
    x: u16,
    y: u64,
    z: u16,
}

fn main() {
    println!("{}", size_of::<A>());
}

Exercise 2. Predict the size of each type, then write a program that prints them: Option<u8>, Option<NonZeroU8>, Option<&String>, Option<Vec<u8>> and Result<Box<u8>, ()>. Which ones use a niche?

Exercise 3. Write a Level enum with #[repr(u8)] and the values 10, 20, 30, 40 from the section above, and a function fn from_u8(n: u8) -> Option<Level> that turns a byte back into a Level. Print what it gives for 20, 40 and 15.

Answers

1. It prints 24. x takes bytes 0 and 1. y must start at a multiple of 8, so bytes 2 to 7 are padding and y takes 8 to 15. z takes 16 and 17. The struct’s alignment is 8, so tail padding takes it to 24. With the default layout, Rust 1.95 puts y first and the size is 16:

use std::mem::size_of;

#[allow(dead_code)]
#[repr(C)]
struct A {
    x: u16,
    y: u64,
    z: u16,
}

#[allow(dead_code)]
struct B {
    x: u16,
    y: u64,
    z: u16,
}

fn main() {
    println!("repr(C): {}", size_of::<A>());
    println!("default: {}", size_of::<B>());
}

It prints:

repr(C): 24
default: 16

2. Option<u8> needs a tag, because every byte value is a valid u8. The others all have a niche: a NonZeroU8 is never 0, and a reference, a Vec‘s pointer and a Box are never null. Result<Box<u8>, ()> works like an Option, because Err(()) carries no data, so it can use the null pointer.

use std::mem::size_of;
use std::num::NonZeroU8;

fn main() {
    println!("Option<u8>:          {}", size_of::<Option<u8>>());
    println!("Option<NonZeroU8>:   {}", size_of::<Option<NonZeroU8>>());
    println!("Option<&String>:     {}", size_of::<Option<&String>>());
    println!("Option<Vec<u8>>:     {}", size_of::<Option<Vec<u8>>>());
    println!("Result<Box<u8>, ()>: {}", size_of::<Result<Box<u8>, ()>>());
}

It prints:

Option<u8>:          2
Option<NonZeroU8>:   1
Option<&String>:     8
Option<Vec<u8>>:     24
Result<Box<u8>, ()>: 8

3. A match on the byte, with a catch-all arm for every number that isn’t a level. In a larger program you’d implement TryFrom<u8> instead, which does the same job under a standard name.

#[derive(Debug, Clone, Copy)]
#[repr(u8)]
enum Level {
    Debug = 10,
    Info = 20,
    Warn = 30,
    Error = 40,
}

fn from_u8(n: u8) -> Option<Level> {
    match n {
        10 => Some(Level::Debug),
        20 => Some(Level::Info),
        30 => Some(Level::Warn),
        40 => Some(Level::Error),
        _ => None,
    }
}

fn main() {
    for n in [20, 40, 15] {
        println!("{n} -> {:?}", from_u8(n));
    }
    println!("and back: {}", Level::Warn as u8);
}

It prints:

20 -> Some(Info)
40 -> Some(Error)
15 -> None
and back: 30

What’s next

Everything in this part was safe Rust asking the compiler about layout. In Part 28, we’ll step past the compiler’s checks with unsafe: raw pointers, what unsafe does and doesn’t allow, and how to wrap unsafe code in an API that’s safe to use.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.