#enums #set #variant #generate #proc-macro #procedural #insert

macro insert-only-set

A procedural macro to generate insert-only sets from enums

4 releases (2 breaking)

0.3.1 May 10, 2024
0.3.0 May 10, 2024
0.2.0 May 10, 2024
0.1.0 May 10, 2024

#407 in Procedural macros

Download history 199/week @ 2024-05-05 10/week @ 2024-05-12 22/week @ 2024-05-19

231 downloads per month

MIT/Apache

8KB
105 lines

Insert Only Set

insert_only_set is a procedural macro to generates thread-safe insert-only sets from enums in Rust. Under the hood this set is a struct with a OnceLock field for each enum variant.

Features

  • Automatically generates an insert-only set for any enum
  • Thread-safe insertions with OnceLock
  • Iterates over set variants that have been inserted

Example

use insert_only_set::InsertOnlySet;

#[derive(InsertOnlySet, Debug, PartialEq)]
pub enum Type {
    Customer,
    Employee,
}

fn main() {
    let set = Type::InsertOnlySet();

    assert!(!set.contains(Type::Customer));
    assert!(!set.contains(Type::Employee));

    assert!(set.insert(Type::Customer));
    assert!(set.contains(Type::Customer));
    assert!(!set.contains(Type::Employee));

    assert!(set.insert(Type::Employee));
    assert!(set.contains(Type::Customer));
    assert!(set.contains(Type::Employee));

    // Try to insert again, should return false
    assert!(!set.insert(Type::Customer));

    for variant in set.iter() {
        println!("{:?}", variant);
    }
}

Dependencies

~1.5MB
~34K SLoC