illicitonion / num_enum

Apache License 2.0
264 stars 34 forks source link

Could IntoPrimitive::into() be a const function? #148

Open DavidAntliff opened 5 months ago

DavidAntliff commented 5 months ago

Would it be possible for MyEnum.into() to be a const function?

Then I could use it like this, for example with something like the bitfield-struct crate:

#[derive(Debug, IntoPrimitive)]
#[repr(u16)]
enum Opcode {
    Jump = 1,
    Halt = 2,
    // ... etc
}

#[bitfield(u32)]
pub(crate) struct JumpInstruction {
    #[bits(16)]
    address: Address,
    #[bits(16, default=Opcode::Jump.into())]
    opcode: u16,
}

Unfortunately, as things stand:

error[E0015]: cannot call non-const fn `<Opcode as Into<u8>>::into` in constant functions
  --> src/ops.rs:75:36
   |
75 |     #[bits(16, default=Opcode::Jump.into())]
   |                                     ^^^^^^
   |

Is this technically possible? The discriminants of the enum variants are static const, I assume? However, I think I read that trait function implementations cannot be const fn in stable Rust.

illicitonion commented 5 months ago

See https://github.com/illicitonion/num_enum/pull/147 which has some discussion about this and an in-progress implementation :)