1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
use core::{ops::Range, slice};

use crate::{
    archetype::{chunk_idx, first_of_chunk, Archetype, CHUNK_LEN_USIZE},
    epoch::EpochId,
};

use super::{fetch::Fetch, Query, QueryItem};

/// Iterator over entities with a query `Q`.
/// Yields query items for every matching entity.
pub struct QueryIter<'a, Q: Query> {
    query: Q,
    epoch: EpochId,
    archetypes_iter: slice::Iter<'a, Archetype>,
    fetch: Q::Fetch<'a>,
    indices: Range<usize>,
    visit_chunk: bool,
}

impl<'a, Q> QueryIter<'a, Q>
where
    Q: Query,
{
    pub(crate) fn new(query: Q, epoch: EpochId, archetypes: &'a [Archetype]) -> Self {
        QueryIter {
            query,
            epoch,
            archetypes_iter: archetypes.iter(),
            fetch: <Q::Fetch<'a>>::dangling(),
            indices: 0..0,
            visit_chunk: false,
        }
    }
}

impl<'a, Q> Iterator for QueryIter<'a, Q>
where
    Q: Query,
{
    type Item = QueryItem<'a, Q>;

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let upper = self
            .archetypes_iter
            .clone()
            .fold(self.indices.len(), |acc, archetype| {
                if !self.query.visit_archetype(archetype) {
                    return acc;
                }
                acc + archetype.len()
            });

        (0, Some(upper))
    }

    #[inline]
    fn next(&mut self) -> Option<QueryItem<'a, Q>> {
        loop {
            match self.indices.next() {
                None => {
                    // move to the next archetype.
                    loop {
                        let archetype = self.archetypes_iter.next()?;

                        if archetype.is_empty() {
                            continue;
                        }

                        if !self.query.visit_archetype(archetype) {
                            continue;
                        }

                        self.fetch = unsafe { self.query.fetch(archetype, self.epoch) };
                        self.indices = 0..archetype.len();
                        break;
                    }
                }
                Some(idx) => {
                    if let Some(chunk_idx) = first_of_chunk(idx) {
                        if !unsafe { self.fetch.visit_chunk(chunk_idx) } {
                            self.indices.nth(CHUNK_LEN_USIZE - 1);
                            continue;
                        }
                        self.visit_chunk = true;
                    }

                    if unsafe { self.fetch.visit_item(idx) } {
                        if self.visit_chunk {
                            unsafe { self.fetch.touch_chunk(chunk_idx(idx)) }
                            self.visit_chunk = false;
                        }

                        let item = unsafe { self.fetch.get_item(idx) };

                        return Some(item);
                    }
                }
            }
        }
    }

    fn fold<B, Fun>(mut self, init: B, mut f: Fun) -> B
    where
        Self: Sized,
        Fun: FnMut(B, QueryItem<'a, Q>) -> B,
    {
        let mut acc = init;
        while let Some(idx) = self.indices.next() {
            if let Some(chunk_idx) = first_of_chunk(idx) {
                if !unsafe { self.fetch.visit_chunk(chunk_idx) } {
                    self.indices.nth(CHUNK_LEN_USIZE - 1);
                    continue;
                }
                self.visit_chunk = true;
            }

            if unsafe { self.fetch.visit_item(idx) } {
                if self.visit_chunk {
                    unsafe { self.fetch.touch_chunk(chunk_idx(idx)) }
                    self.visit_chunk = false;
                }
                let item = unsafe { self.fetch.get_item(idx) };

                acc = f(acc, item);
            }
        }

        for archetype in self.archetypes_iter.by_ref() {
            if archetype.is_empty() {
                continue;
            }
            if !self.query.visit_archetype(archetype) {
                continue;
            }
            let mut fetch = unsafe { self.query.fetch(archetype, self.epoch) };

            let mut indices = 0..archetype.len();

            while let Some(idx) = indices.next() {
                if let Some(chunk_idx) = first_of_chunk(idx) {
                    if !unsafe { fetch.visit_chunk(chunk_idx) } {
                        self.indices.nth(CHUNK_LEN_USIZE - 1);
                        continue;
                    }
                    self.visit_chunk = true;
                }

                if unsafe { fetch.visit_item(idx) } {
                    if self.visit_chunk {
                        unsafe { fetch.touch_chunk(chunk_idx(idx)) }
                        self.visit_chunk = false;
                    }
                    let item = unsafe { fetch.get_item(idx) };

                    acc = f(acc, item);
                }
            }
        }
        acc
    }
}