Crates.io | structified_enum |
lib.rs | structified_enum |
version | 0.1.0 |
source | src |
created_at | 2023-12-10 13:14:13.386939 |
updated_at | 2023-12-10 13:14:13.386939 |
description | Marcos to structify unit-like enum with discriminants |
homepage | |
repository | https://github.com/TOETOE55/structified_enum |
max_upload_size | |
id | 1064195 |
size | 21,928 |
structified_enum
This crate provides an attribute macro structify
transforming a unit-like enum to a struct with its discriminant.
The following code:
use structified_enum::structify;
#[structify]
#[repr(u8)]
#[derive(Copy, Clone)]
enum Foo {
A = 0,
B,
C,
}
is equivalent to
// #[repr(ty)] -> #[repr(transparent)]
#[repr(transparent)]
#[derive(Copy, Clone)]
struct Foo(u8);
impl Foo {
pub const A: Self = Self(0);
pub const B: Self = Self(1);
pub const C: Self = Self(2);
pub fn new(value: u8) -> Self {
Self(value)
}
// like `Foo::A as u8`
pub fn value(self) -> u8 {
self.0
}
}
There are two main reasons:
unsafe
or crates like num-derive to generate conversion methods.
Because structures like struct Foo(repr_ty)
can naturally express this conversion.