Skip to content

Commit

Permalink
feat: Iterators
Browse files Browse the repository at this point in the history
Iterate over values and key-value zipped iterators.
  • Loading branch information
Pscheidl committed May 24, 2024
1 parent 6953bdd commit fff471a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ Debug and Eq are optional features. They are enabled by default.

## Usage

Please refer to the [documentation(https://docs.rs/enum-collections/latest/enum_collections/)] for a complete list of features and more in-depth documentation.

```rust
use enum_collections::{EnumMap, Enumerated};

Expand Down
46 changes: 44 additions & 2 deletions enum-collections/src/enummap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{
ops::{Index, IndexMut},
};

///
/// Creates an EnumMap with user-provided values.
/// ```
/// use enum_collections::{em, Enumerated, EnumMap};
/// #[derive(Enumerated)]
Expand All @@ -33,7 +33,7 @@ macro_rules! em {

}

///
/// Initializes an EnumMap with default values for all variants not explicitly specified.
/// ```
/// use enum_collections::{em_default, Enumerated, EnumMap};
/// #[derive(Enumerated)]
Expand Down Expand Up @@ -231,6 +231,48 @@ impl<K: Enumerated, V, const N: usize> EnumMap<K, V, N> {
}
}

/// Iterates over the EnumMap's key-value pairs.
///
/// ```
/// use enum_collections::{EnumMap, Enumerated};
/// #[derive(Enumerated, Debug)]
/// pub enum Letter {
/// A,
/// B,
/// }
///
/// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new(|| 42);
/// for (_letter, value) in enum_map.iter_kv() {
/// assert_eq!(42, *value);
/// }
///
/// ```
#[cfg(feature = "variants")]
pub fn iter_kv(&self) -> std::iter::Zip<std::slice::Iter<'_, K>, std::slice::Iter<'_, V>> {
K::VARIANTS.iter().zip(self.data.iter())
}

/// Iterates over the EnumMap's values.
///
/// ```
/// use enum_collections::{EnumMap, Enumerated};
/// #[derive(Enumerated, Debug)]
/// pub enum Letter {
/// A,
/// B,
/// }
///
/// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new(|| 42);
/// for value in enum_map.iter() {
/// assert_eq!(42, *value);
/// }
///
/// ```
#[cfg(feature = "variants")]
pub fn iter(&self) -> std::slice::Iter<'_, V> {
self.data.iter()
}

/// Creates a new EnumMap where value of each variant is produced by the provided function.
/// The function receives the enum variant being initialized for inspection.
///
Expand Down

0 comments on commit fff471a

Please sign in to comment.