Custom discriminant for enum types?

I'm building a high performance merkle tree for a research paper. I'm using the arena approach, i.e.: I allocate a very big array and then each node use a type ArenaID = (u8, u16) as pointer. To simplify I have 3 main types of nodes:

  • Real node
  • Sentinel node: contains metadata for up to 16 sibling nodes (hash, guardian offset, ...)
  • Guardian node: contains metadata for up to 16 sibling sentinel nodes (parent, height, sentinels offsets, ... to treat it as a skip list)

Now all 3 type of nodes are represented as type NodeUnion = [u8, 16] (more or less), with the actual type encoded in the first u8.

I would like now to write a generic function which takes a generic NodeUnion and changes its behaviour according to the actual node type.

My questions are:

  • Could I use an enum but with a custom discriminant, to guarantee packed representation (no more than 128 bits) while reusing Rust idioms?
  • Should I use the union type instead maybe? Never used those, didn't know Rust had them, I always used enums before
  • Should I do a manual casts with as or into? But then I would not use the Rust compiler guarantees in terms of exhaustive matching
  • Is there another smarter/more idiomatic approach?

you can control the discriminant type with the #[repr(...) attribute, for example, if you want use 8 bits for the discriminant, you can use u8.

however, there's no guarantee how the payload will be packed under the default Rust representation. see Enumerations - The Rust Reference for more information. in many cases, you can use #[repr(C)] to manually control the memory layout of the fields.

example:

#[repr(u8, C)]
enum MyEnum {
    Foo(u8),
    Bar(u16),
    Baz(u32),
}
2 Likes

Thanks! I forgot to mention that I'm packing other data in the u8 (so it's actually just 2 bits, and use the remaining 6 bits for something else), so I think this approach won't work.

Another quesetion: is repr(c) compatible with WASM? Will it hold the same guarantees?

When posting the same question in several places you should crosslink them to avoid causing duplicate work. Reddit - The heart of the internet

1 Like

My apologies, I will try to be more mindful about this