const_primes/cache/
primes_iter.rs

1// Copyright 2025 Johanna Sörngård
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use super::Underlying;
5use core::iter::FusedIterator;
6
7/// A borrowing iterator over prime numbers.
8///
9/// Created by the [`iter`](super::Primes::iter) function on [`Primes`](super::Primes),
10/// see it for more information.
11#[derive(Debug, Clone)]
12#[cfg_attr(
13    feature = "rkyv",
14    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
15)]
16#[cfg_attr(
17    feature = "zerocopy",
18    derive(zerocopy::IntoBytes, zerocopy::Immutable, zerocopy::KnownLayout)
19)]
20#[must_use = "iterators are lazy and do nothing unless consumed"]
21#[cfg_attr(feature = "zerocopy", repr(transparent))]
22pub struct PrimesIter<'a>(core::slice::Iter<'a, Underlying>);
23
24impl<'a> PrimesIter<'a> {
25    pub(crate) const fn new(iter: core::slice::Iter<'a, Underlying>) -> Self {
26        Self(iter)
27    }
28
29    /// Returns an immutable slice of all the primes that have not been yielded yet.
30    pub fn as_slice(&self) -> &[Underlying] {
31        self.0.as_slice()
32    }
33}
34
35impl<'a> Iterator for PrimesIter<'a> {
36    type Item = &'a Underlying;
37
38    #[inline]
39    fn next(&mut self) -> Option<Self::Item> {
40        self.0.next()
41    }
42
43    #[inline]
44    fn size_hint(&self) -> (usize, Option<usize>) {
45        self.0.size_hint()
46    }
47
48    #[inline]
49    fn nth(&mut self, n: usize) -> Option<Self::Item> {
50        self.0.nth(n)
51    }
52
53    #[inline]
54    fn count(self) -> usize {
55        self.0.count()
56    }
57
58    #[inline]
59    fn last(self) -> Option<Self::Item> {
60        self.0.last()
61    }
62}
63
64impl ExactSizeIterator for PrimesIter<'_> {
65    #[inline]
66    fn len(&self) -> usize {
67        self.0.len()
68    }
69}
70
71impl FusedIterator for PrimesIter<'_> {}
72
73impl DoubleEndedIterator for PrimesIter<'_> {
74    #[inline]
75    fn next_back(&mut self) -> Option<Self::Item> {
76        self.0.next_back()
77    }
78
79    #[inline]
80    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
81        self.0.nth_back(n)
82    }
83}