< 返回版块

YiiSh 发表于 2021-07-30 05:08

Tags:enum,flags,bitflags

其他的库

新的实现

现有的类似库,都不太好用。所以就参考 csharp 实现了一版 enum-flags

地址是:https://github.com/mokeyish/enum-flags

在 bitor、 bitand 等运算之后的类型是与原枚举是类型是一样的。

示例代码

use enum_flags::EnumFlags;

#[repr(u8)]
#[derive(EnumFlags, Copy, Clone, PartialEq)]
enum Flags{
    None = 0,
    A = 1,
    B = 2,
    C = 4
}
fn main() {
    let e1: Flags = Flags::A | Flags::C;
    let e2 = Flags::B | Flags::C;
    
    assert_eq!(e1 | e2, Flags::A | Flags::B | Flags::C); // union
    assert_eq!(e1 & e2, Flags::C); // intersection
    assert_eq!(e1 ^ e2, Flags::A | Flags::B); // xor
    assert_eq!(e1 & (!Flags::C), Flags::B); // deletion
    assert_eq!(e1 - Flags::C, Flags::A); // deletion

    assert_eq!("(Flags::A | Flags::C)", format!("{:?}", e1).as_str());
    assert!(e1.has_a());
    assert!(!e1.has_b());
    assert!(e1.has_flag(Flags::C));
    
}

评论区

写评论
7sDream 2021-07-30 16:17

想法是好的,但其实这样是 UB:

Producing an invalid value, even in private fields and locals. "Producing" a value happens any time a value is assigned to or read from a place, passed to a function/primitive operation or returned from a function/primitive operation. The following values are invalid (at their respective type):

  • A discriminant in an enum not included in the type definition.

https://doc.rust-lang.org/reference/behavior-considered-undefined.html

作者 YiiSh 2021-07-30 11:31

什么bug

--
👇
sanri: 示例代码有bug. 但是这个库看起来还不错.

sanri 2021-07-30 11:12

示例代码有bug. 但是这个库看起来还不错.

坚果修补匠 2021-07-30 10:31

看起来挺不错的

1 共 4 条评论, 1 页