enum_iterator/
lib.rs

1// Copyright (C) 2018-2021 Stephane Raux. Distributed under the 0BSD license.
2
3//! # Overview
4//! - [📦 crates.io](https://crates.io/crates/enum-iterator)
5//! - [📖 Documentation](https://docs.rs/enum-iterator)
6//! - [âš– 0BSD license](https://spdx.org/licenses/0BSD.html)
7//!
8//! Tools to iterate over the variants of a field-less enum.
9//!
10//! See the [`IntoEnumIterator`] trait.
11//!
12//! # Example
13//! ```
14//! use enum_iterator::IntoEnumIterator;
15//!
16//! #[derive(Debug, IntoEnumIterator, PartialEq)]
17//! enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
18//!
19//! fn main() {
20//!     assert_eq!(Day::into_enum_iter().next(), Some(Day::Monday));
21//!     assert_eq!(Day::into_enum_iter().last(), Some(Day::Sunday));
22//! }
23//! ```
24//!
25//! # Contribute
26//! All contributions shall be licensed under the [0BSD license](https://spdx.org/licenses/0BSD.html).
27
28#![deny(missing_docs)]
29#![deny(warnings)]
30#![no_std]
31
32pub use enum_iterator_derive::IntoEnumIterator;
33
34use core::iter;
35
36/// Trait to iterate over the variants of a field-less enum.
37///
38/// Field-less (a.k.a. C-like) enums are enums whose variants don't have additional data.
39///
40/// This trait is meant to be derived.
41///
42/// # Example
43///
44/// ```
45/// use enum_iterator::IntoEnumIterator;
46///
47/// #[derive(Clone, IntoEnumIterator, PartialEq)]
48/// enum Direction { North, South, West, East }
49///
50/// fn main() {
51///     assert_eq!(Direction::VARIANT_COUNT, 4);
52///     assert!(Direction::into_enum_iter().eq([Direction::North,
53///         Direction::South, Direction::West, Direction::East].iter()
54///         .cloned()));
55/// }
56/// ```
57pub trait IntoEnumIterator: Sized {
58    /// Type of the iterator over the variants.
59    type Iterator: Iterator<Item = Self> + iter::ExactSizeIterator + iter::FusedIterator + Copy;
60
61    /// Number of variants.
62    const VARIANT_COUNT: usize;
63
64    /// Returns an iterator over the variants.
65    ///
66    /// Variants are yielded in the order they are defined in the enum.
67    fn into_enum_iter() -> Self::Iterator;
68}