hashmismatch / packed_struct.rs

Bit-level packing and unpacking for Rust
MIT License
163 stars 30 forks source link

Cannot use constants in derive(PrimitiveEnum) #87

Open berkowski opened 2 years ago

berkowski commented 2 years ago

I'd like to use packed_struct in a use case where the rust struct contains an enum, and the enum values are defined by constants generated by bindgen. Modifying the example in the docs shows the behavior I'm seeing:

#![no_std]
use packed_struct::prelude::*;

// These consts would be imported from the bindgen sources, but just defining consts here works well enough
// as an example
pub const NORMAL: u8 = 0;
pub const POSITIVE: u8 = 1;
pub const NEGATIVE: u8 = 2;
pub const DEBUG: u8 = 3;

#[derive(PrimitiveEnum_u8, Clone, Copy, Debug, PartialEq)]
pub enum SelfTestMode {
    NormalMode = NORMAL,
    PositiveSignSelfTest = POSITIVE,
    NegativeSignSelfTest = NEGATIVE,
    DebugMode = DEBUG,
}
$cargo build
error: Unsupported enum const expr
  --> src/lib.rs:12:5
   |
12 |     NormalMode = NORMAL,
   |     ^^^^^^^^^^

error[E0308]: mismatched types
  --> src/lib.rs:12:18
   |
12 |     NormalMode = NORMAL,
   |                  ^^^^^^ expected `isize`, found `u8`

error[E0308]: mismatched types
  --> src/lib.rs:13:28
   |
13 |     PositiveSignSelfTest = POSITIVE,
   |                            ^^^^^^^^ expected `isize`, found `u8`

error[E0308]: mismatched types
  --> src/lib.rs:14:28
   |
14 |     NegativeSignSelfTest = NEGATIVE,
   |                            ^^^^^^^^ expected `isize`, found `u8`

error[E0308]: mismatched types
  --> src/lib.rs:15:17
   |
15 |     DebugMode = DEBUG,
   |                 ^^^^^ expected `isize`, found `u8`

Ok, so let's add #[repr(u8)] to the enum definition:

#![no_std]

use packed_struct::prelude::*;

pub const NORMAL: u8 = 0;
pub const POSITIVE: u8 = 1;
pub const NEGATIVE: u8 = 2;
pub const DEBUG: u8 = 3;

#[derive(PrimitiveEnum_u8, Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum SelfTestMode {
    NormalMode = NORMAL,
    PositiveSignSelfTest = POSITIVE,
    NegativeSignSelfTest = NEGATIVE,
    DebugMode = DEBUG,
}
$cargo build

error: Unsupported enum const expr
  --> src/lib.rs:13:5
   |
13 |     NormalMode = NORMAL,
   |     ^^^^^^^^^^