Compact nested enum

Maybe this has been asked before, but I didn't find an exact same one. I want to achieve the size of the following enum (32 bytes on 64-bit system)

enum Data {
    SmallA(usize),
    LargeA(Vec<usize>),
    SmallB(usize),
    LargeB(Vec<usize>),
}

// std::mem::size_of::<Data>() = 32

with the following structure (40 bytes on 64 bit system)

enum DataPrimitive {
    Small(usize),
    Large(Vec<usize>)
}
enum Data {
    A(DataPrimitive),
    B(DataPrimitive)
}

// std::mem::size_of::<Data>() = 40

Is there any workaround to keep the structure without increasing the memory size?

There's no guaranteed way without changing the types. The guaranteed representations with those types result in size 40, so you would need to rely on layout optimization with the default representation (explicitly unspecified), and layout optimization for those is only guaranteed in very specific cases (not this one). More on enum layouts can be found here.

If you could get your DataPrimitive down to 24 bytes you could have it. That might happen automatically with your current types in an un-guaranteed way some day [1], but it's not happening currently.

If your Large never need to change once created, you could switch the types to

enum DataPrimitive {
    Small(usize),
    Large(Box<[usize]>),
}

enum Data {
    A(DataPrimitive),
    B(DataPrimitive),
}

And save a usize.


  1. see issue 46213 ↩ī¸Ž

1 Like

Thanks for the references! Then it depends on rustc's optimization.

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.