1use std::any::{Any, TypeId};
22use std::fmt::{Debug, Display, Formatter};
23use std::hash::{Hash, Hasher};
24use std::marker::PhantomData;
25
26use serde::{Deserialize, Serialize};
27
28use super::entity_store::get_entity_metadata_static;
29
30#[derive(Serialize, Deserialize)]
33#[serde(transparent)]
34pub struct EntityId<E: Entity>(pub(crate) usize, PhantomData<E>);
35impl<E: Entity> PartialEq for EntityId<E> {
40 fn eq(&self, other: &Self) -> bool {
41 self.0 == other.0
42 }
43}
44impl<E: Entity> Eq for EntityId<E> {}
45
46impl<E: Entity> Clone for EntityId<E> {
48 #[inline]
49 fn clone(&self) -> Self {
50 *self
51 }
52}
53
54impl<E: Entity> Copy for EntityId<E> {}
56
57impl<E: Entity> Debug for EntityId<E> {
59 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
60 let name = format!("{}Id", E::name());
61 f.debug_tuple(name.as_str()).field(&self.0).finish()
62 }
63}
64impl<E: Entity> Display for EntityId<E> {
66 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
67 write!(f, "{}", self.0)
68 }
69}
70
71impl<E: Entity> Hash for EntityId<E> {
73 fn hash<H: Hasher>(&self, state: &mut H) {
74 self.0.hash(state);
75 }
76}
77
78impl<E: Entity> EntityId<E> {
79 pub(crate) fn new(index: usize) -> Self {
81 Self(index, PhantomData)
82 }
83}
84
85pub trait Entity: Any + Default {
87 #[must_use]
88 fn name() -> &'static str {
89 let full = std::any::type_name::<Self>();
90 full.rsplit("::").next().unwrap()
91 }
92
93 #[must_use]
94 fn type_id() -> TypeId {
95 TypeId::of::<Self>()
96 }
97
98 #[must_use]
100 fn property_ids() -> &'static [TypeId] {
101 let (property_ids, _) = get_entity_metadata_static(<Self as Entity>::type_id());
102 property_ids
103 }
104
105 #[must_use]
107 fn required_property_ids() -> &'static [TypeId] {
108 let (_, required_property_ids) = get_entity_metadata_static(<Self as Entity>::type_id());
109 required_property_ids
110 }
111
112 #[must_use]
116 fn id() -> usize;
117
118 #[must_use]
120 fn new_boxed() -> Box<Self> {
121 Box::default()
122 }
123
124 fn as_any(&self) -> &dyn Any;
126 fn as_any_mut(&mut self) -> &mut dyn Any;
127}
128
129pub type BxEntity = Box<dyn Entity>;
130
131#[derive(Copy, Clone)]
136pub struct PopulationIterator<E: Entity> {
137 population: usize,
139 entity_id: usize,
141
142 _phantom: PhantomData<E>,
143}
144
145impl<E: Entity> PopulationIterator<E> {
146 pub(crate) fn new(population: usize) -> Self {
149 PopulationIterator::<E> {
150 population,
151 entity_id: 0,
152 _phantom: PhantomData,
153 }
154 }
155
156 #[must_use]
157 pub(crate) fn population(&self) -> usize {
158 self.population
159 }
160}
161
162impl<E: Entity> Iterator for PopulationIterator<E> {
163 type Item = EntityId<E>;
164
165 fn next(&mut self) -> Option<Self::Item> {
166 if self.entity_id < self.population {
167 let current_id = self.entity_id;
168 self.entity_id += 1;
170 Some(EntityId::new(current_id))
171 } else {
172 None
173 }
174 }
175
176 fn size_hint(&self) -> (usize, Option<usize>) {
178 let remaining = self.len();
179 (remaining, Some(remaining))
180 }
181
182 fn count(self) -> usize {
184 self.len()
185 }
186
187 fn nth(&mut self, n: usize) -> Option<Self::Item> {
189 self.entity_id = (self.entity_id + n).min(self.population);
191 self.next()
192 }
193}
194
195impl<E: Entity> ExactSizeIterator for PopulationIterator<E> {
196 fn len(&self) -> usize {
197 self.population - self.entity_id
199 }
200}
201impl<E: Entity> std::iter::FusedIterator for PopulationIterator<E> {}
203
204#[cfg(test)]
205mod tests {
206 use super::*;
207 use crate::define_entity;
208
209 define_entity!(DummyEntity);
210
211 #[test]
212 fn entity_id_debug_display() {
213 let entity_id = DummyEntityId::new(137);
214 assert_eq!(format!("{:?}", entity_id), "DummyEntityId(137)");
215 assert_eq!(format!("{}", entity_id), "137");
216 }
217
218 #[test]
219 fn define_entity_helpers_create_and_downcast() {
220 assert_eq!(DummyEntity::new(), DummyEntity);
221
222 let mut entity = DummyEntity::new();
223 assert!(entity.as_any().downcast_ref::<DummyEntity>().is_some());
224 assert!(entity.as_any_mut().downcast_mut::<DummyEntity>().is_some());
225 }
226
227 #[test]
228 fn test_entity_iterator_basic() {
229 let mut iter = PopulationIterator::<DummyEntity>::new(3);
230
231 assert_eq!(iter.len(), 3);
232 assert_eq!(iter.next(), Some(EntityId::new(0)));
233 assert_eq!(iter.len(), 2);
234 assert_eq!(iter.next(), Some(EntityId::new(1)));
235 assert_eq!(iter.len(), 1);
236 assert_eq!(iter.next(), Some(EntityId::new(2)));
237 assert_eq!(iter.len(), 0);
238 assert_eq!(iter.next(), None);
239 assert_eq!(iter.len(), 0);
240 assert_eq!(iter.next(), None); }
242
243 #[test]
244 fn test_entity_iterator_nth() {
245 let mut iter = PopulationIterator::<DummyEntity>::new(10);
246
247 assert_eq!(iter.nth(2), Some(EntityId::new(2)));
249 assert_eq!(iter.len(), 7);
250
251 assert_eq!(iter.nth(1), Some(EntityId::new(4)));
253
254 assert_eq!(iter.nth(10), None);
256 assert_eq!(iter.len(), 0);
257 assert_eq!(iter.next(), None);
258 }
259
260 #[test]
261 fn test_entity_iterator_size_hint() {
262 let mut iter = PopulationIterator::<DummyEntity>::new(5);
263 assert_eq!(iter.size_hint(), (5, Some(5)));
264
265 iter.next();
266 assert_eq!(iter.size_hint(), (4, Some(4)));
267
268 assert_eq!(iter.nth(10), None);
270 assert_eq!(iter.size_hint(), (0, Some(0)));
271 }
272
273 #[test]
274 fn test_entity_iterator_clonable() {
275 let mut iter = PopulationIterator::<DummyEntity>::new(5);
276 iter.next();
277
278 let mut cloned = iter;
279 assert_eq!(iter.next(), cloned.next());
280 assert_eq!(iter.size_hint(), cloned.size_hint());
281 }
282}