Skip to main content

ixa/entity/
entity.rs

1/*!
2
3An implementor of [`Entity`] is a type that names a collection of related properties in
4analogy to a table in a database. The properties are analogous to the columns in the table,
5and the [`EntityId<E>`] type is analogous to the primary key of the table, the row number.
6
7[`Entity`]s are declared with the [`define_entity!`] macro:
8
9```rust
10use ixa::define_entity;
11define_entity!(Person);
12```
13
14Once an [`Entity`] is defined, [`Property`]s can be defined for the [`Entity`]. See the
15[`property`](crate::entity::property) module.
16
17Right now an `Entity` type is just a zero-sized marker type. The static data associated with the type isn't used yet.
18
19*/
20
21use 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/// A type that can be named and used (copied, cloned) but not created outside of this crate.
31/// In the `define_entity!` macro we define the alias `pub type MyEntityId = EntityId<MyEntity>`.
32#[derive(Serialize, Deserialize)]
33#[serde(transparent)]
34pub struct EntityId<E: Entity>(pub(crate) usize, PhantomData<E>);
35// Note: The generics on `EntityId<E>` prevent the compiler from "seeing" the derived traits in some client code,
36//       so we provide blanket implementations below.
37
38// Otherwise the compiler isn't smart enough to know `EntityId<E>` is always `PartialEq`/`Eq`
39impl<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
46// Otherwise the compiler isn't smart enough to know `EntityId<E>` is always `Clone`
47impl<E: Entity> Clone for EntityId<E> {
48    #[inline]
49    fn clone(&self) -> Self {
50        *self
51    }
52}
53
54// Otherwise the compiler isn't smart enough to know `EntityId<E>` is always `Copy`
55impl<E: Entity> Copy for EntityId<E> {}
56
57// The value `EntityId<Person>(7, PhantomData<Person>)` has `Debug` display "PersonId(7)".
58impl<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}
64// The value `EntityId<Person>(7, PhantomData<Person>)` will display as "7".
65impl<E: Entity> Display for EntityId<E> {
66    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
67        write!(f, "{}", self.0)
68    }
69}
70
71// Otherwise the compiler isn't smart enough to know `EntityId<E>` is always `Hash`
72impl<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    /// Only constructible from this crate.
80    pub(crate) fn new(index: usize) -> Self {
81        Self(index, PhantomData)
82    }
83}
84
85/// All entities must implement this trait using the `define_entity!` macro.
86pub 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    /// Get a list of all properties this `Entity` has. This list is static, computed in with `ctor` magic.
99    #[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    /// Get a list of all properties of this `Entity` that _must_ be supplied when a new entity is created.
106    #[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    /// The index of this item in the owner, which is initialized globally per type
113    /// upon first access. We explicitly initialize this in a `ctor` in order to know
114    /// how many [`Entity`] types exist globally when we construct any `EntityStore`.
115    #[must_use]
116    fn id() -> usize;
117
118    /// Creates a new boxed instance of the item.
119    #[must_use]
120    fn new_boxed() -> Box<Self> {
121        Box::default()
122    }
123
124    /// Standard pattern for downcasting to concrete types.
125    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/// An iterator over the total population of `EntityId<E>`s at the time of iterator creation.
132///
133/// If entities are added _after_ this iterator has been created, this iterator will _not_ produce the `EntityId<E>`s
134/// of the newly added entities.
135#[derive(Copy, Clone)]
136pub struct PopulationIterator<E: Entity> {
137    /// The total count of all entities of this type at the time this iterator was created
138    population: usize,
139    /// The next `EntityId<E>` this iterator will produce (assuming `entity_id < population`)
140    entity_id: usize,
141
142    _phantom: PhantomData<E>,
143}
144
145impl<E: Entity> PopulationIterator<E> {
146    // Only internal Ixa code can create a new `PopulationIterator<E>` in order to guarantee only valid
147    // `EntityId<E>` values are ever created.
148    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` saturates to `self.population`.
169            self.entity_id += 1;
170            Some(EntityId::new(current_id))
171        } else {
172            None
173        }
174    }
175
176    // This iterator knows how many elements it will iterate over.
177    fn size_hint(&self) -> (usize, Option<usize>) {
178        let remaining = self.len();
179        (remaining, Some(remaining))
180    }
181
182    // Fast consuming count
183    fn count(self) -> usize {
184        self.len()
185    }
186
187    // Fast "seeking" operation.
188    fn nth(&mut self, n: usize) -> Option<Self::Item> {
189        // `self.entity_id` saturates to `self.population`.
190        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        // Safety: Since `self.entity_id` saturates to `self.population`, we do not need `saturating_sub` here.
198        self.population - self.entity_id
199    }
200}
201// Once `PopulationIterator<E>` returns `None`, it will always return `None`.
202impl<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); // FusedIterator behavior
241    }
242
243    #[test]
244    fn test_entity_iterator_nth() {
245        let mut iter = PopulationIterator::<DummyEntity>::new(10);
246
247        // Seek to 3rd element (index 2)
248        assert_eq!(iter.nth(2), Some(EntityId::new(2)));
249        assert_eq!(iter.len(), 7);
250
251        // Seek relative to current position (+1 means skip index 3, return 4)
252        assert_eq!(iter.nth(1), Some(EntityId::new(4)));
253
254        // Seek past end
255        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        // Seek past end
269        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}