Skip to content

Cannot use constants in derive(PrimitiveEnum) #87

Open
@berkowski

Description

@berkowski

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,
   |     ^^^^^^^^^^

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions