#generate #programming #枚举 #类型级别 # #伪枚举

enum-to-types

用于生成类型级别编程的伪枚举的宏

1 个不稳定版本

0.1.0 2020 年 7 月 21 日

#1950Rust 模式

自定义许可

7KB

Enum-to-types

用于生成类型级别编程的伪枚举的宏。这与 https://github.com/fmease/tylift 类似,但使用 macro_rules! 语法实现。

安装

[dependencies]
enum_to_types = "0.1.0"
use enum_to_types::enum_to_types;
use std::marker::PhantomData;

enum_to_types!(AccessLevel; User, Admin);

struct DataStorage<T: AccessLevel::AccessLevel>(i32, PhantomData<T>);

impl<T: AccessLevel::AccessLevel> DataStorage<T> {
     fn new(i: i32) -> Self {
         Self(i, PhantomData)
     }
}

trait ReadStorage<T: AccessLevel::AccessLevel> {
    fn read(&self) -> i32;
}

impl ReadStorage<AccessLevel::Admin> for DataStorage<AccessLevel::User> {
     fn read(&self) -> i32 {
         self.0
     }
}

impl ReadStorage<AccessLevel::User> for DataStorage<AccessLevel::User> {
     fn read(&self) -> i32 {
         self.0
     }
}

impl ReadStorage<AccessLevel::Admin> for DataStorage<AccessLevel::Admin> {
     fn read(&self) -> i32 {
         self.0
     }
}

impl ReadStorage<AccessLevel::User> for DataStorage<AccessLevel::Admin> {
     fn read(&self) -> i32 {
         panic!("You have no rights to read this");
     }
}

fn main() {
     let storage = DataStorage::<AccessLevel::Admin>::new(1);
     assert_eq!(<DataStorage::<AccessLevel::Admin> as ReadStorage<AccessLevel::Admin>>::read(&storage), 1);
     let storage = DataStorage::<AccessLevel::User>::new(5);
     assert_eq!(<DataStorage::<AccessLevel::User> as ReadStorage<AccessLevel::User>>::read(&storage), 5);
     // reading storage with `AccessLevel::Admin` by user will cause panic
}

这可能看起来非常冗长,但它提供了很多灵活性。此外,其他示例可能看起来不那么冗长。

无运行时依赖