mesa/src/compiler/rust/enum_as_u8.rs
Faith Ekstrand 3f18c81d4f compiler/rust: Add an EnumAsU8 trait
Reviewed-by: Mel Henning <mhenning@darkrefraction.com>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/41915>
2026-06-01 19:51:17 +00:00

23 lines
773 B
Rust

// Copyright © 2023 Collabora, Ltd.
// SPDX-License-Identifier: MIT
use crate::bitset::ConstBitSet;
/// A trait for enums which are `#[repr(u8)]` which provides some extra sugar
/// on top. By deriving this trait with `#[derive(EnumAsU8)]`, you get
/// `From<MyEnum> for u8` and `TryFrom<u8> for MyEnum` for free as well as
/// an iterator over all valid variants in the enum. This trait works
/// regardless of whether or not discriminant are explicitly specified.
pub trait EnumAsU8: Sized {
const VARIANTS: ConstBitSet<8, u8>;
fn as_u8(self) -> u8;
unsafe fn from_u8_unchecked(u: u8) -> Self;
fn iter() -> impl Iterator<Item = Self> {
Self::VARIANTS
.iter()
.map(|u| unsafe { Self::from_u8_unchecked(u) })
}
}