consume_iterator/
lib.rs

1#![no_std]
2//! Iterator utility for consuming an iterator fully.
3//!
4//! To use, either `use consume_iterator::consume` to get the function,
5//! or `use consume_iterator::ConsumeIterator` to get the convenience trait.
6
7/// Consume an iterator.
8///
9/// This function takes any implementation of [`IntoIterator`],
10/// which includes iterators themselves.
11///
12/// # Example
13///
14/// The iterator is always fully consumed.
15///
16/// ```
17/// # use consume_iterator::consume;
18/// let mut range = 0..=10;
19/// consume(&mut range);
20/// assert!(range.is_empty());
21/// ```
22#[inline]
23pub fn consume(iter: impl IntoIterator) {
24    for _ in iter {}
25}
26
27/// Convenience trait to allow using [`consume`] as a method.
28/// This trait is implemented for every [`Iterator`].
29pub trait ConsumeIterator: Iterator {
30    /// Consume an iterator.
31    ///
32    /// # Example
33    ///
34    /// The iterator is always fully consumed.
35    ///
36    /// ```
37    /// # use consume_iterator::ConsumeIterator;
38    /// let mut range = 0..=10;
39    /// range.by_ref().consume();
40    /// assert!(range.is_empty());
41    /// ```
42    #[inline]
43    fn consume(self)
44    where
45        Self: Sized,
46    {
47        consume(self);
48    }
49}
50
51impl<T: Iterator> ConsumeIterator for T {}