#enums #hash-map #iterator #derive #fields #length #convert

macro small_iter_fields

get an iterator, or get the length, or convert to a hashmap from an enum

5 releases

0.1.5 Sep 25, 2024
0.1.4 Aug 23, 2024

#556 in Procedural macros

MIT/Apache

7KB
61 lines

small_iter_fields

This crate adds #[derive(IterFields)], #[derive(LenFields)] and #[derive(HashFields)].

It works for:

  • Enums

Known Limitations

  • Enum variants must have no data

Example

use std::collections::HashMap;
use small_iter_fields::{IterFields, LenFields, HashFields};
 
#[derive(IterFields, LenFields, HashFields, Hash, PartialEq, Eq)]
enum Stage {
  Start,
  Middle,
  End,
}

let mut vec: Vec<Stage> = Vec::with_capacity(Stage::len());
assert!(vec.capacity() >= 3);

for stage in Stage::iter_fields() {
    vec.push(stage);
};

assert!(vec.contains(&Stage::Start));
assert!(vec.contains(&Stage::Middle));
assert!(vec.contains(&Stage::End));

let map: HashMap<Stage, Vec<i32>> = Stage::to_hashmap(Vec::new());
assert!(map.capacity() >= 3);

assert_eq!(map.get(&Stage::Start), Some(&Vec::new()));

License

MIT or Apache-2.0


lib.rs:

Example

use std::collections::HashMap;
use small_iter_fields::{IterFields, LenFields, HashFields};

#[derive(IterFields, LenFields, HashFields, Hash, PartialEq, Eq)]
enum Stage {
    Start,
    Middle,
    End,
}

let mut vec: Vec<Stage> = Vec::with_capacity(Stage::len());
assert!(vec.capacity() >= 3);

for stage in Stage::iter_fields() {
    vec.push(stage);
};

assert!(vec.contains(&Stage::Start));
assert!(vec.contains(&Stage::Middle));
assert!(vec.contains(&Stage::End));

let map: HashMap<Stage, Vec<i32>> = Stage::to_hashmap(Vec::new());
assert!(map.capacity() >= 3);

assert_eq!(map.get(&Stage::Start), Some(&Vec::new()));

Enums must have no data associated with it

use small_iter_fields::IterFields;

#[derive(IterFields)]
enum DataEnum {
    Data(bool),
}

Dependencies

~220–660KB
~16K SLoC