Custom discriminant for enum types?
⚓ Rust 📅 2026-02-15 👤 surdeus 👁️ 6I'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
enumbut with a custom discriminant, to guarantee packed representation (no more than 128 bits) while reusing Rust idioms? - Should I use the
uniontype instead maybe? Never used those, didn't know Rust had them, I always used enums before - Should I do a manual casts with
asorinto? But then I would not use the Rust compiler guarantees in terms of exhaustive matching - Is there another smarter/more idiomatic approach?
1 post - 1 participant
🏷️ Rust_feed