Union of two non-overlapping enums

⚓ Rust    📅 2025-07-10    👤 surdeus    👁️ 4      

surdeus

I have two non-overlapping enums that are passed to me from C.
Is there a way to write a enum, encompassing both, which is of the same size as the original enum (so that I could use all of them in C interface)?

Here is the example:

#[repr(u8)]
#[rustfmt::skip]
pub enum low_level_message_type_enum {                                       
    initiate_disconnection = 0x0,
    confirm_disconnection  = 0x1,
    continuous_flow        = 0x2,
}

#[repr(u8)]
#[rustfmt::skip]
pub enum match_client_message_types_enum {
    connection_request                 = 0x40,
    get_startup_info                   = 0x41,
    join_match                         = 0x42,
    client_player_update               = 0x43,
    client_player_commit_suicide       = 0x44,
    time_synchronization_request       = 0x45,
    time_synchronization_confirmation  = 0x46,
    bullets_info_request               = 0x47,
    team_bases_initialize_info         = 0x48,
    force_finish_match                 = 0x49,
    world_synchronization_confirmation = 0x4A,
    match_client_invalid_message_type  = 0x7F,
}
    
#[repr(u8)]
pub enum both {
    Low(low_level_message_type_enum),
    High(match_client_message_types_enum),
}

fn main() {
    assert_eq!(std::mem::size_of::<low_level_message_type_enum>(), 1);
    assert_eq!(std::mem::size_of::<match_client_message_types_enum>(), 1);
    assert_eq!(std::mem::size_of::<both>(), 1); // <- fails
}

3 posts - 2 participants

Read full topic

🏷️ rust_feed