ferravex_ecs/
lib.rs

1//! Original, dependency-free entity/component storage for small Ferravex games.
2//!
3//! Components live in one sparse, contiguous slot array per Rust type. Entity
4//! generations prevent stale handles from reaching reused slots. Iteration visits
5//! live entity slots in stable order. Runtime component borrowing uses standard
6//! library [`Ref`] / [`RefMut`] guards, so overlapping queries cannot create
7//! aliased mutable references, even if an iterator is retained or abandoned.
8//!
9//! ```
10//! use ferravex_ecs::{Entity, World};
11//! let mut world = World::new();
12//! let player = world.spawn((10_i32, 2.0_f32));
13//! for (entity, mut health, speed) in &mut world.query::<(Entity, &mut i32, &f32)>() {
14//!     assert_eq!(entity, player);
15//!     *health += *speed as i32;
16//! }
17//! assert_eq!(*world.get::<&i32>(player).unwrap(), 12);
18//! world.despawn(player).unwrap();
19//! assert!(!world.contains(player));
20//! ```
21//!
22//! Query results are borrow guards rather than naked references. Bind mutable
23//! results with `mut`, as above. `try_query` and `try_iter` report conflicts as
24//! errors; `query` and `iter` panic on invalid/overlapping borrows. Structural
25//! operations require `&mut World`, so Rust prevents them while guards exist.
26//!
27//! ```compile_fail
28//! use ferravex_ecs::World;
29//! let mut world = World::new();
30//! let entity = world.spawn((42_i32,));
31//! let component = world.get::<&i32>(entity).unwrap();
32//! world.despawn(entity).unwrap(); // A live guard borrows the world.
33//! println!("{}", *component);
34//! ```
35#![forbid(unsafe_code)]
36
37use std::any::{Any as StdAny, TypeId, type_name};
38use std::cell::RefCell;
39pub use std::cell::{Ref, RefMut};
40use std::collections::HashMap;
41use std::fmt;
42use std::hash::{BuildHasherDefault, Hasher};
43use std::marker::PhantomData;
44
45/// Component storages keyed by `TypeId`. Every fetch and presence check looks
46/// a storage up; `TypeId` is already a well-distributed hash, so it is used
47/// directly instead of being rehashed with SipHash on each lookup.
48type StorageMap = HashMap<TypeId, Box<dyn ErasedStorage>, BuildHasherDefault<TypeIdHasher>>;
49#[derive(Default)]
50struct TypeIdHasher(u64);
51impl Hasher for TypeIdHasher {
52    fn write(&mut self, bytes: &[u8]) {
53        // Fallback for a `TypeId` representation that hashes as bytes.
54        for &byte in bytes {
55            self.0 = (self.0 ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3);
56        }
57    }
58    fn write_u64(&mut self, value: u64) {
59        self.0 ^= value;
60    }
61    fn write_u128(&mut self, value: u128) {
62        self.0 ^= value as u64 ^ (value >> 64) as u64;
63    }
64    fn finish(&self) -> u64 {
65        self.0
66    }
67}
68
69/// Opaque slot identity. A despawned entity never becomes valid again in its world.
70/// Handles are world-local; two separate worlds may issue the same identity.
71#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
72pub struct Entity {
73    index: u32,
74    generation: u32,
75}
76
77impl Entity {
78    /// Sparse slot index, useful for diagnostics. It is not a unique identity alone.
79    pub fn id(self) -> u32 {
80        self.index
81    }
82    pub fn generation(self) -> u32 {
83        self.generation
84    }
85    /// A compact representation for local persistence. Validate with World::contains.
86    pub fn to_bits(self) -> u64 {
87        (u64::from(self.generation) << 32) | u64::from(self.index)
88    }
89    /// Reconstructs a handle; this does not prove that its entity exists.
90    pub fn from_bits(bits: u64) -> Self {
91        Self {
92            index: bits as u32,
93            generation: (bits >> 32) as u32,
94        }
95    }
96}
97
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub enum Error {
100    NoSuchEntity(Entity),
101    MissingComponent(&'static str),
102    BorrowConflict(&'static str),
103    DuplicateComponent(&'static str),
104    ConflictingQuery(&'static str),
105}
106
107impl fmt::Display for Error {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        match self {
110            Self::NoSuchEntity(entity) => write!(f, "entity {entity:?} is not alive"),
111            Self::MissingComponent(name) => write!(f, "entity has no {name} component"),
112            Self::BorrowConflict(name) => {
113                write!(f, "{name} component is already incompatibly borrowed")
114            }
115            Self::DuplicateComponent(name) => write!(f, "bundle contains {name} more than once"),
116            Self::ConflictingQuery(name) => {
117                write!(f, "query requests overlapping mutable access to {name}")
118            }
119        }
120    }
121}
122impl std::error::Error for Error {}
123
124/// Failure to prepare storage or preflight a bounded spawn batch.
125///
126/// Separate from [`Error`] to preserve that enum's exhaustive matches. A batch
127/// returns this error together with all of its original owned bundles; see
128/// [`World::try_spawn_batch`] for precedence and ownership rules.
129#[derive(Clone, Debug, PartialEq, Eq)]
130#[non_exhaustive]
131pub enum SpawnError {
132    DuplicateComponent(&'static str),
133    OutputTooSmall {
134        required: usize,
135        available: usize,
136    },
137    /// Highest selected sparse slot plus one exceeds the prepared entity budget.
138    EntityCapacity {
139        required: usize,
140        prepared: usize,
141    },
142    /// A selected index exceeds this type's explicitly prepared sparse budget.
143    ComponentCapacity {
144        component: &'static str,
145        required: usize,
146        prepared: usize,
147    },
148    /// The request exceeds representable entity indices or usize arithmetic.
149    IdentityCapacity,
150    /// A standard-library try_reserve operation failed during preparation.
151    AllocationFailed,
152}
153
154impl fmt::Display for SpawnError {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        match self {
157            Self::DuplicateComponent(name) => write!(f, "bundle contains {name} more than once"),
158            Self::OutputTooSmall {
159                required,
160                available,
161            } => {
162                write!(
163                    f,
164                    "batch needs {required} output handles, received {available}"
165                )
166            }
167            Self::EntityCapacity { required, prepared } => {
168                write!(
169                    f,
170                    "batch needs {required} entity slots, prepared {prepared}"
171                )
172            }
173            Self::ComponentCapacity {
174                component,
175                required,
176                prepared,
177            } => {
178                write!(
179                    f,
180                    "batch needs {required} {component} slots, prepared {prepared}"
181                )
182            }
183            Self::IdentityCapacity => write!(f, "entity slot identity capacity exceeded"),
184            Self::AllocationFailed => write!(f, "could not reserve spawn storage"),
185        }
186    }
187}
188impl std::error::Error for SpawnError {}
189
190/// Failure to read an explicit selected-component duplication plan.
191///
192/// See [`World::plan_duplication`] for validation order and a runnable recipe.
193/// Spawn admission uses the existing separate [`SpawnError`].
194#[derive(Clone, Debug, PartialEq, Eq)]
195#[non_exhaustive]
196pub enum DuplicationError {
197    /// Invalid selection, stale source, missing component or conflicting borrow.
198    Access(Error),
199    /// Each source must occur once so the returned map has unique old identities.
200    DuplicateSource(Entity),
201}
202
203impl fmt::Display for DuplicationError {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        match self {
206            Self::Access(error) => error.fmt(f),
207            Self::DuplicateSource(entity) => write!(f, "duplication repeats source {entity:?}"),
208        }
209    }
210}
211impl std::error::Error for DuplicationError {
212    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
213        match self {
214            Self::Access(error) => Some(error),
215            Self::DuplicateSource(_) => None,
216        }
217    }
218}
219
220/// Owned snapshot of explicitly selected components for `N` distinct sources.
221///
222/// Created by [`World::plan_duplication`]. This holds no world borrow and never
223/// rereads sources, even after edits/despawns. Each component's `Clone` defines
224/// whether its internal data stays shared (for example, an `Rc<RefCell<_>>`).
225/// Dropping the plan discards the clones. Stack storage/work scales with `N` and
226/// the selected bundle size; use small arrays for authoring. `Clone` may allocate.
227/// The plan is not a whole-world, identity, hierarchy or reference-remapping clone.
228#[derive(Debug)]
229#[must_use]
230pub struct DuplicationPlan<B: CloneBundle, const N: usize> {
231    sources: [Entity; N],
232    bundles: [B; N],
233}
234
235impl<B: CloneBundle, const N: usize> DuplicationPlan<B, N> {
236    /// Spawns the captured bundles within the target's prepared sparse budgets.
237    ///
238    /// Returns exactly `N` `(old, new)` pairs in source order. Old identities are
239    /// informational: sources need not still exist. A different target world is
240    /// allowed; old/new handles then belong to their respective worlds and may
241    /// have equal bits. In the same world each new handle differs from every
242    /// source identity. Hosts explicitly remap any entity references afterward.
243    ///
244    /// Uses [`World::try_spawn_batch`] without weakening its admission guarantees:
245    /// any reported error returns the entire plan for retry, without spawning,
246    /// dropping or recloning components. No ECS buffers/metadata grow on success;
247    /// preparation is the caller's responsibility. A valid empty plan needs none.
248    /// User `Clone`/`Drop` and allocator panics/aborts are not caught or rolled back.
249    /// See [`World::plan_duplication`] for a complete actor-template recipe.
250    pub fn try_spawn(self, world: &mut World) -> Result<[(Entity, Entity); N], (SpawnError, Self)> {
251        let Self { sources, bundles } = self;
252        let mut entities = [Entity::from_bits(0); N];
253        match world.try_spawn_batch(bundles, &mut entities) {
254            Ok(_) => Ok(std::array::from_fn(|i| (sources[i], entities[i]))),
255            Err((error, bundles)) => Err((error, Self { sources, bundles })),
256        }
257    }
258}
259
260#[derive(Default)]
261struct Slot {
262    generation: u32,
263    alive: bool,
264}
265
266trait ErasedStorage {
267    fn as_any(&self) -> &dyn StdAny;
268    fn as_any_mut(&mut self) -> &mut dyn StdAny;
269    fn erase(&mut self, index: usize);
270    fn prepared_capacity(&self) -> usize;
271    fn presence(&self) -> &[u64];
272}
273
274struct Storage<T> {
275    slots: Vec<Option<RefCell<T>>>,
276    present: Vec<u64>,
277    prepared: usize,
278}
279
280impl<T> Default for Storage<T> {
281    fn default() -> Self {
282        Self {
283            slots: Vec::new(),
284            present: Vec::new(),
285            prepared: 0,
286        }
287    }
288}
289
290impl<T: 'static> ErasedStorage for Storage<T> {
291    fn as_any(&self) -> &dyn StdAny {
292        self
293    }
294    fn as_any_mut(&mut self) -> &mut dyn StdAny {
295        self
296    }
297    fn erase(&mut self, index: usize) {
298        if let Some(slot) = self.slots.get_mut(index) {
299            *slot = None;
300        }
301        if let Some(word) = self.present.get_mut(index >> 6) {
302            *word &= !(1_u64 << (index & 63));
303        }
304    }
305    fn prepared_capacity(&self) -> usize {
306        self.prepared
307    }
308    fn presence(&self) -> &[u64] {
309        &self.present
310    }
311}
312
313/// Sparse typed storage with generational entities and checked component borrows.
314///
315/// RefCell deliberately makes World !Sync. Parallel mutation should use separate
316/// worlds or explicit synchronization around the whole world.
317#[derive(Default)]
318pub struct World {
319    slots: Vec<Slot>,
320    alive: Vec<u64>,
321    free: Vec<u32>,
322    storages: StorageMap,
323    len: usize,
324    prepared_entities: usize,
325}
326
327impl World {
328    pub fn new() -> Self {
329        Self::default()
330    }
331    pub fn len(&self) -> usize {
332        self.len
333    }
334    pub fn is_empty(&self) -> bool {
335        self.len == 0
336    }
337
338    /// Prepares at least `capacity` total sparse entity slots and free-list entries.
339    ///
340    /// This is a monotonic index budget, not an additional/live entity count.
341    /// Retired slots still occupy indices. It never creates entities, consumes
342    /// free slots or shrinks buffers. Ordinary spawn ignores this budget and
343    /// retains its existing growth behavior. Allocator rounding does not enlarge
344    /// the logical budget returned by [`Self::prepared_entity_capacity`].
345    ///
346    /// Returns [`SpawnError::IdentityCapacity`] for unrepresentable slot counts,
347    /// or [`SpawnError::AllocationFailed`] if a reservation fails. On error the
348    /// logical budget, identities and contents are unchanged, but an earlier
349    /// successful reservation may have enlarged a buffer. Allocator panics/aborts
350    /// are not caught. See [`Self::try_spawn_batch`] for a complete wave recipe.
351    ///
352    /// ```
353    /// use ferravex_ecs::{SpawnError, World};
354    /// let mut world = World::new();
355    /// world.prepare_entities(16)?;
356    /// world.prepare_entities(4)?; // Never shrinks the explicit budget.
357    /// assert_eq!(world.prepared_entity_capacity(), 16);
358    /// assert!(world.is_empty());
359    /// # Ok::<(), SpawnError>(())
360    /// ```
361    pub fn prepare_entities(&mut self, capacity: usize) -> Result<(), SpawnError> {
362        check_identity_capacity(capacity)?;
363        self.slots
364            .try_reserve_exact(capacity.saturating_sub(self.slots.len()))
365            .map_err(|_| SpawnError::AllocationFailed)?;
366        self.free
367            .try_reserve_exact(capacity.saturating_sub(self.free.len()))
368            .map_err(|_| SpawnError::AllocationFailed)?;
369        let words = capacity.div_ceil(64);
370        self.alive
371            .try_reserve_exact(words.saturating_sub(self.alive.len()))
372            .map_err(|_| SpawnError::AllocationFailed)?;
373        if words > self.alive.len() {
374            self.alive.resize(words, 0);
375        }
376        self.prepared_entities = self.prepared_entities.max(capacity);
377        Ok(())
378    }
379
380    /// Explicit sparse entity-slot budget; initially zero, unaffected by ordinary spawn.
381    /// See [`Self::prepare_entities`] for an executable example.
382    pub fn prepared_entity_capacity(&self) -> usize {
383        self.prepared_entities
384    }
385
386    /// Registers `T` and prepares at least `capacity` sparse component slots.
387    ///
388    /// Every selected entity index must fit, even when few entities contain `T`.
389    /// No component values are constructed, replaced or dropped. Preparation is
390    /// monotonic and independent of entity preparation. Ordinary insert/spawn may
391    /// grow storage but do not increase its explicit prepared budget.
392    ///
393    /// Identity/reservation errors have the same meaning as [`Self::prepare_entities`].
394    /// On a reported error, component values and the logical budget are unchanged;
395    /// map capacity may grow. New storage is inserted only after its vector is
396    /// reserved. Its Box allocation uses the ordinary allocator and may panic or
397    /// abort rather than returning an error. No arbitrary allocation guarantee is made.
398    ///
399    /// ```
400    /// use ferravex_ecs::{SpawnError, World};
401    /// let mut world = World::new();
402    /// world.prepare_component::<String>(16)?; // No String values are created.
403    /// world.prepare_component::<String>(4)?;
404    /// assert_eq!(world.prepared_component_capacity::<String>(), 16);
405    /// assert_eq!(world.prepared_component_capacity::<u8>(), 0);
406    /// assert!(world.is_empty());
407    /// # Ok::<(), SpawnError>(())
408    /// ```
409    pub fn prepare_component<T: 'static>(&mut self, capacity: usize) -> Result<(), SpawnError> {
410        check_identity_capacity(capacity)?;
411        let id = TypeId::of::<T>();
412        if let Some(storage) = self.storages.get_mut(&id) {
413            return prepare_storage(
414                storage
415                    .as_any_mut()
416                    .downcast_mut::<Storage<T>>()
417                    .expect("component storage type matches its TypeId"),
418                capacity,
419            );
420        }
421        self.storages
422            .try_reserve(1)
423            .map_err(|_| SpawnError::AllocationFailed)?;
424        let mut storage = Storage::<T>::default();
425        prepare_storage(&mut storage, capacity)?;
426        self.storages.insert(id, Box::new(storage));
427        Ok(())
428    }
429
430    /// Explicit sparse budget for `T`; zero for unprepared/absent types.
431    /// See [`Self::prepare_component`] for an executable example.
432    pub fn prepared_component_capacity<T: 'static>(&self) -> usize {
433        self.storages
434            .get(&TypeId::of::<T>())
435            .map_or(0, |storage| storage.prepared_capacity())
436    }
437
438    /// Spawns an owned fixed array in caller order, within explicitly prepared storage.
439    ///
440    /// Writes exactly `N` handles into the output prefix and returns `Ok(N)`.
441    /// Free slots are popped in the same LIFO order as ordinary spawn, followed
442    /// by new indices. Preflight inspects only those selected free slots, so an
443    /// unselected high index does not require component preparation for that index.
444    /// Explicit entity and component budgets must cover the highest selected
445    /// index plus one. Allocation rounding and ordinary storage growth do not
446    /// increase these budgets. See [`Self::prepare_entities`] and
447    /// [`Self::prepare_component`].
448    ///
449    /// # Errors and ownership
450    ///
451    /// Checks, in order: duplicate component types (also for `N == 0`), output
452    /// length, identity arithmetic, entity budget, then component budgets in
453    /// bundle order. An empty valid batch needs no preparation and returns zero.
454    /// Every reported error returns `(error, original_bundles)` without moving
455    /// values out of that array, dropping components, registering storage,
456    /// changing entities/free-list order, or writing any output. The caller owns
457    /// the returned values and decides whether to retry or drop them. Unused
458    /// output is unchanged on both success and error; its initial handles need
459    /// not be valid entities.
460    ///
461    /// # Allocation and panic limits
462    ///
463    /// After successful preflight, the ECS does not grow entity, free-list, map
464    /// or component buffers, allocate storage boxes or allocate metadata. Input
465    /// construction happens before this call and can allocate/panic. This is an
466    /// all-or-none guarantee for *reported errors*, not a panic transaction:
467    /// panics/aborts are not caught or rolled back, and unconsumed owned values
468    /// are dropped during unwinding. User construction/Drop is not infallible.
469    /// Stack space is proportional to the caller-selected array size.
470    ///
471    /// A first-party wave/projectile recipe: invoke the spawn step only on an
472    /// executed simulation tick, and emit feedback only after `Ok` admission.
473    /// Restart despawns existing entities while retaining prepared buffers.
474    ///
475    /// ```
476    /// use ferravex_ecs::{Entity, SpawnError, World};
477    /// struct Position(f32);
478    /// struct Bullet { velocity: f32, remaining: f32 }
479    ///
480    /// let mut world = World::new();
481    /// world.prepare_entities(32)?;
482    /// world.prepare_component::<Position>(32)?;
483    /// world.prepare_component::<Bullet>(32)?;
484    /// let mut handles = [Entity::from_bits(0); 4];
485    /// let projectiles = std::array::from_fn::<_, 3, _>(|i| (
486    ///     Position(i as f32), Bullet { velocity: 8.0, remaining: 1.0 },
487    /// ));
488    /// let accepted = world.try_spawn_batch(projectiles, &mut handles)
489    ///     .map_err(|(error, _owned_projectiles)| error)?;
490    /// assert_eq!(accepted, 3); // Now emit three accepted-shot feedback events.
491    /// let fixed_dt = 0.25;
492    /// for (mut position, mut bullet) in world.query::<(&mut Position, &mut Bullet)>() {
493    ///     position.0 += bullet.velocity * fixed_dt;
494    ///     bullet.remaining -= fixed_dt;
495    /// }
496    /// assert_eq!(world.get::<&Position>(handles[0]).unwrap().0, 2.0);
497    /// assert_eq!(world.get::<&Bullet>(handles[0]).unwrap().remaining, 0.75);
498    /// let old = handles[0];
499    /// world.despawn_many(&handles[..accepted]).unwrap();
500    /// world.try_spawn_batch([(Position(10.0), Bullet { velocity: 4.0, remaining: 2.0 })],
501    ///     &mut handles).map_err(|(error, _)| error)?;
502    /// assert!(!world.contains(old));
503    /// assert_eq!(world.len(), 1);
504    /// # Ok::<(), SpawnError>(())
505    /// ```
506    pub fn try_spawn_batch<B: Bundle, const N: usize>(
507        &mut self,
508        bundles: [B; N],
509        output: &mut [Entity],
510    ) -> Result<usize, (SpawnError, [B; N])> {
511        if let Err(error) = self.preflight_batch::<B>(N, output.len()) {
512            return Err((error, bundles));
513        }
514        for (bundle, handle) in bundles.into_iter().zip(output.iter_mut()) {
515            *handle = self.spawn_validated(bundle);
516        }
517        Ok(N)
518    }
519
520    /// Captures selected `Clone` component types for a small set of source entities.
521    ///
522    /// `B` is an owned tuple of zero to eight explicitly chosen component types.
523    /// Nothing else is copied, including transient handles, unless selected.
524    /// Entity identity is never copied automatically; an explicitly stored Entity
525    /// component is just a value. Embedded entity references retain their old
526    /// values until the host explicitly remaps them using the returned spawn map.
527    /// No reflection, serialization or hierarchy traversal is performed.
528    ///
529    /// Checks duplicate component types (even for `N == 0`), all source identities
530    /// in order, then repeated sources, then reads in source/tuple order. Every
531    /// selected component is shared-borrowed before the first `Clone` call. Missing
532    /// components and outstanding mutable borrows are errors, never omissions.
533    /// Any reported error releases partial guards, calls no component `Clone`,
534    /// changes no ECS storage/identities and spawns nothing. Shared guards and
535    /// mutable guards of unselected components do not prevent capture.
536    ///
537    /// The returned plan owns a snapshot and releases all read guards. It can
538    /// outlive source edits/despawns. No ECS metadata heap allocation is needed;
539    /// fixed-array stack space scales with `N` and `B`. User `Clone` can allocate,
540    /// mutate shared interior state or panic; no rollback of user effects or
541    /// promise about panicking `Clone`/`Drop` is made. Successful earlier clones
542    /// are dropped on unwind. Spawn capacity is checked later by the plan.
543    /// Handles remain world-local; a foreign matching identity cannot be detected.
544    ///
545    /// This actor-template recipe omits a transient audio handle, explicitly
546    /// remaps a partner reference, and despawns the duplicates for reset. Run
547    /// authoring at a structural-edit boundary after query guards are released;
548    /// derive gameplay feedback only from accepted spawns.
549    ///
550    /// ```
551    /// use ferravex_ecs::World;
552    /// #[derive(Clone)] struct Position(f32);
553    /// #[derive(Clone)] struct Health(u32);
554    /// #[derive(Clone)] struct Partner(ferravex_ecs::Entity);
555    /// struct AudioVoice; // Transient, deliberately not Clone or selected.
556    /// let mut world = World::new();
557    /// let first = world.spawn((Position(1.0), Health(10), AudioVoice));
558    /// let second = world.spawn((Position(3.0), Health(20), AudioVoice));
559    /// world.insert(first, (Partner(second),))?;
560    /// world.insert(second, (Partner(first),))?;
561    /// world.prepare_entities(4)?;
562    /// world.prepare_component::<Position>(4)?;
563    /// world.prepare_component::<Health>(4)?;
564    /// world.prepare_component::<Partner>(4)?;
565    /// let plan = world.plan_duplication::<(Position, Health, Partner), 2>([first, second])?;
566    /// let map = plan.try_spawn(&mut world).map_err(|(error, _plan)| error)?;
567    /// assert_eq!(map.map(|(old, _)| old), [first, second]);
568    /// let copies = map.map(|(_, new)| new);
569    /// for (old, new) in map {
570    ///     assert_ne!(old, new);
571    ///     assert!(!world.has::<AudioVoice>(new));
572    ///     let mut partner = world.get::<&mut Partner>(new)?;
573    ///     let replacement = map.iter().find(|(source, _)| *source == partner.0).unwrap().1;
574    ///     partner.0 = replacement; // Explicit host remap, after all copies exist.
575    /// }
576    /// world.get::<&mut Position>(copies[0])?.0 += 5.0;
577    /// assert_eq!(world.get::<&Position>(first)?.0, 1.0);
578    /// assert_eq!(world.get::<&Position>(copies[0])?.0, 6.0);
579    /// assert_eq!(world.get::<&Health>(copies[1])?.0, 20);
580    /// assert_eq!(world.get::<&Partner>(copies[0])?.0, copies[1]);
581    /// assert_eq!(world.get::<&Partner>(first)?.0, second);
582    /// world.despawn_many(&copies)?; // Prepared buffers survive reset.
583    /// let again = world.plan_duplication::<(Position, Health), 1>([first])?
584    ///     .try_spawn(&mut world).map_err(|(error, _)| error)?;
585    /// assert!(copies.iter().all(|old| !world.contains(*old)));
586    /// assert_eq!(world.get::<&Health>(again[0].1)?.0, 10);
587    /// # Ok::<(), Box<dyn std::error::Error>>(())
588    /// ```
589    pub fn plan_duplication<B: CloneBundle, const N: usize>(
590        &self,
591        sources: [Entity; N],
592    ) -> Result<DuplicationPlan<B, N>, DuplicationError> {
593        validate_bundle::<B>().map_err(DuplicationError::Access)?;
594        for entity in sources {
595            self.validate(entity).map_err(DuplicationError::Access)?;
596        }
597        for (i, &entity) in sources.iter().enumerate() {
598            if sources[..i].contains(&entity) {
599                return Err(DuplicationError::DuplicateSource(entity));
600            }
601        }
602        let mut borrowed = std::array::from_fn::<_, N, _>(|_| None);
603        for (item, entity) in borrowed.iter_mut().zip(sources) {
604            *item = Some(B::borrow(self, entity).map_err(DuplicationError::Access)?);
605        }
606        let bundles = borrowed.each_ref().map(|item| {
607            B::clone_components(item.as_ref().expect("every source was fully borrowed"))
608        });
609        Ok(DuplicationPlan { sources, bundles })
610    }
611
612    pub fn contains(&self, entity: Entity) -> bool {
613        self.slots
614            .get(entity.index as usize)
615            .is_some_and(|slot| slot.alive && slot.generation == entity.generation)
616    }
617
618    /// Spawns one entity containing zero to eight components. See [`Bundle`]
619    /// for a complete five-component actor recipe.
620    /// Panics if a bundle repeats a component type; no entity is allocated in that case.
621    pub fn spawn<B: Bundle>(&mut self, bundle: B) -> Entity {
622        self.try_spawn(bundle)
623            .unwrap_or_else(|error| panic!("{error}"))
624    }
625
626    pub fn try_spawn<B: Bundle>(&mut self, bundle: B) -> Result<Entity, Error> {
627        validate_bundle::<B>()?;
628        Ok(self.spawn_validated(bundle))
629    }
630
631    fn spawn_validated<B: Bundle>(&mut self, bundle: B) -> Entity {
632        let index = if let Some(index) = self.free.pop() {
633            index
634        } else {
635            let index = u32::try_from(self.slots.len()).expect("entity slot capacity exceeded");
636            self.slots.push(Slot::default());
637            index
638        };
639        let slot = &mut self.slots[index as usize];
640        slot.alive = true;
641        let idx = index as usize;
642        let word = idx >> 6;
643        if self.alive.len() <= word {
644            self.alive.resize(word + 1, 0);
645        }
646        self.alive[word] |= 1_u64 << (idx & 63);
647        let entity = Entity {
648            index,
649            generation: slot.generation,
650        };
651        self.len += 1;
652        bundle.write(self, idx);
653        entity
654    }
655
656    /// Drops every component and invalidates the handle before reusing its slot.
657    pub fn despawn(&mut self, entity: Entity) -> Result<(), Error> {
658        self.validate(entity)?;
659        let idx = entity.index as usize;
660        let slot = &mut self.slots[idx];
661        slot.alive = false;
662        if let Some(word) = self.alive.get_mut(idx >> 6) {
663            *word &= !(1_u64 << (idx & 63));
664        }
665        self.len -= 1;
666        // Never wrap a generation: a fully exhausted slot is permanently retired.
667        let next_generation = slot.generation.checked_add(1);
668        if let Some(next) = next_generation {
669            slot.generation = next;
670        }
671        for storage in self.storages.values_mut() {
672            storage.erase(idx);
673        }
674        // A panicking component destructor leaves the slot retired, never recycled
675        // with leftover components from the despawned entity.
676        if next_generation.is_some() {
677            self.free.push(entity.index);
678        }
679        Ok(())
680    }
681
682    /// Despawns a batch after validating every handle, returning the number removed.
683    ///
684    /// Repeated live handles are accepted and removed exactly once, in order of
685    /// first occurrence. An empty slice returns `Ok(0)`. Successful removal has
686    /// the same component cleanup and slot-reuse behavior as [`World::despawn`].
687    /// The order in which different component types are dropped is unspecified.
688    ///
689    /// Validation and duplicate handling use constant extra space, perform no
690    /// allocation and do not scan unrelated entities. Removal may grow the
691    /// world's existing free-slot list, just like individual despawns.
692    ///
693    /// # Errors
694    ///
695    /// The first stale or invalid handle in input order returns
696    /// [`Error::NoSuchEntity`] before any mutation or component drops. Every
697    /// handle must be live at entry, including repeats. On `Err`, all entities,
698    /// components, generations and slot-reuse order remain unchanged. Handles
699    /// are world-local; matching identities from another world cannot be detected.
700    ///
701    /// # Panics
702    ///
703    /// Component destructors may panic. Such a panic is not rolled back: earlier
704    /// removals remain applied, the current entity is invalidated and its slot
705    /// retired, and unprocessed entities remain live, as with sequential despawns.
706    ///
707    /// ```
708    /// use ferravex_ecs::{Error, World};
709    ///
710    /// let mut world = World::new();
711    /// let first = world.spawn((10_i32,));
712    /// let second = world.spawn((20_i32,));
713    /// let stale = world.spawn(());
714    /// world.despawn(stale)?;
715    /// assert_eq!(world.despawn_many(&[first, stale]), Err(Error::NoSuchEntity(stale)));
716    /// assert_eq!(*world.get::<&i32>(first)?, 10);
717    /// assert_eq!(world.despawn_many(&[second, first, second])?, 2);
718    /// assert!(world.is_empty());
719    /// # Ok::<(), Error>(())
720    /// ```
721    ///
722    /// Structural removal requires exclusive access, including when guards came
723    /// from [`World::get_many`]:
724    ///
725    /// ```compile_fail
726    /// use ferravex_ecs::World;
727    /// let mut world = World::new();
728    /// let entity = world.spawn((42_i32,));
729    /// let guards = world.get_many::<&mut i32, 1>([entity]).unwrap();
730    /// world.despawn_many(&[entity]).unwrap();
731    /// drop(guards);
732    /// ```
733    pub fn despawn_many(&mut self, entities: &[Entity]) -> Result<usize, Error> {
734        for &entity in entities {
735            self.validate(entity)?;
736        }
737        let mut removed = 0;
738        for &entity in entities {
739            // Exclusive access keeps validation valid. A dead handle here can
740            // only be a duplicate already removed earlier in this batch.
741            if self.contains(entity) {
742                self.despawn(entity)?;
743                removed += 1;
744            }
745        }
746        Ok(removed)
747    }
748
749    /// Inserts or replaces a bundle's components. Other components remain unchanged.
750    /// Invalid identities and duplicate bundle types are rejected before any writes.
751    pub fn insert<B: Bundle>(&mut self, entity: Entity, bundle: B) -> Result<(), Error> {
752        self.validate(entity)?;
753        validate_bundle::<B>()?;
754        bundle.write(self, entity.index as usize);
755        Ok(())
756    }
757
758    pub fn remove<T: 'static>(&mut self, entity: Entity) -> Result<T, Error> {
759        self.validate(entity)?;
760        let idx = entity.index as usize;
761        let storage = self
762            .storages
763            .get_mut(&TypeId::of::<T>())
764            .and_then(|s| s.as_any_mut().downcast_mut::<Storage<T>>())
765            .ok_or(Error::MissingComponent(type_name::<T>()))?;
766        let value = storage
767            .slots
768            .get_mut(idx)
769            .and_then(Option::take)
770            .map(RefCell::into_inner)
771            .ok_or(Error::MissingComponent(type_name::<T>()))?;
772        if let Some(word) = storage.present.get_mut(idx >> 6) {
773            *word &= !(1_u64 << (idx & 63));
774        }
775        Ok(value)
776    }
777
778    pub fn has<T: 'static>(&self, entity: Entity) -> bool {
779        self.contains(entity) && self.cell::<T>(entity.index as usize).is_some()
780    }
781
782    /// Reads or mutates a typed component through an explicit access type.
783    /// Use `get::<&T>` or `get::<&mut T>`; returned guards enforce runtime aliasing.
784    /// `Option<&T>` and `Option<&mut T>` return `None` for an absent component.
785    /// Invalid entities and conflicting borrows still return errors.
786    ///
787    /// ```
788    /// use ferravex_ecs::{Error, World};
789    /// let mut world = World::new();
790    /// let entity = world.spawn(());
791    /// assert!(world.get::<Option<&i32>>(entity)?.is_none());
792    /// world.insert(entity, (10_i32,))?;
793    /// let mut health = world.get::<Option<&mut i32>>(entity)?.unwrap();
794    /// *health += 1;
795    /// assert!(matches!(world.get::<Option<&i32>>(entity), Err(Error::BorrowConflict(_))));
796    /// drop(health);
797    /// assert_eq!(*world.get::<Option<&i32>>(entity)?.unwrap(), 11);
798    /// # Ok::<(), Error>(())
799    /// ```
800    pub fn get<A: Access>(&self, entity: Entity) -> Result<A::Item<'_>, Error> {
801        self.validate(entity)?;
802        A::fetch(self, entity)
803    }
804
805    pub fn get_mut<T: 'static>(&self, entity: Entity) -> Result<RefMut<'_, T>, Error> {
806        self.get::<&mut T>(entity)
807    }
808
809    /// Borrows a fixed set of entities in the supplied order, without scanning the world.
810    ///
811    /// `Q` accepts the same single access or tuple of up to eight accesses as
812    /// [`World::query`]. Returned guards borrow the world, not the input array.
813    /// This performs no heap allocation and uses stack space proportional to `N`.
814    /// An empty array succeeds if the query signature is valid.
815    ///
816    /// # Errors
817    ///
818    /// An overlapping mutable access within `Q` returns [`Error::ConflictingQuery`].
819    /// Next, all handles are checked in input order: a despawned, reused or invalid
820    /// handle returns [`Error::NoSuchEntity`] before any components are borrowed.
821    /// Handles remain world-local; identities from another world cannot be detected.
822    ///
823    /// Components are then borrowed in entity and tuple order. A missing required
824    /// component returns [`Error::MissingComponent`]; a missing optional component
825    /// yields `None`. Incompatible outstanding guards or a repeated entity with
826    /// mutable access to a present component return [`Error::BorrowConflict`].
827    /// Repeated entities with absent optional mutable components are allowed.
828    /// Repeated entities are allowed for shared access and identity-only queries.
829    /// Any error releases every guard acquired by this call, including partial
830    /// tuple borrows. No components are changed and no partial result is returned.
831    ///
832    /// ```
833    /// use ferravex_ecs::{Error, World};
834    ///
835    /// let mut world = World::new();
836    /// let donor = world.spawn((10_i32,));
837    /// let receiver = world.spawn((2_i32,));
838    /// {
839    ///     let [mut from, mut to] = world.get_many::<&mut i32, 2>([donor, receiver])?;
840    ///     *from -= 3;
841    ///     *to += 3;
842    /// }
843    /// assert_eq!(*world.get::<&i32>(receiver)?, 5);
844    /// assert!(matches!(
845    ///     world.get_many::<&mut i32, 2>([donor, donor]),
846    ///     Err(Error::BorrowConflict(_))
847    /// ));
848    ///
849    /// // A tuple query can also retrieve several components of one known entity.
850    /// let [(id, health)] = world.get_many::<(ferravex_ecs::Entity, &i32), 1>([donor])?;
851    /// assert_eq!(id, donor);
852    /// assert_eq!(*health, 7);
853    /// # Ok::<(), Error>(())
854    /// ```
855    ///
856    /// Optional accesses preserve the requested order and borrow only components
857    /// that are present:
858    ///
859    /// ```
860    /// use ferravex_ecs::{Entity, Error, World};
861    /// let mut world = World::new();
862    /// let actor = world.spawn((10_i32,));
863    /// let scenery = world.spawn(());
864    /// let [(scenery_id, absent), (actor_id, health)] =
865    ///     world.get_many::<(Entity, Option<&mut i32>), 2>([scenery, actor])?;
866    /// assert_eq!((scenery_id, actor_id), (scenery, actor));
867    /// assert!(absent.is_none());
868    /// *health.unwrap() += 1;
869    /// assert_eq!(*world.get::<&i32>(actor)?, 11);
870    /// # Ok::<(), Error>(())
871    /// ```
872    pub fn get_many<Q: Query, const N: usize>(
873        &self,
874        entities: [Entity; N],
875    ) -> Result<[Q::Item<'_>; N], Error> {
876        Q::validate()?;
877        for entity in entities {
878            self.validate(entity)?;
879        }
880        // Options let partially initialized results drop normally on failure,
881        // without unsafe code or a temporary heap allocation.
882        let mut items = std::array::from_fn::<_, N, _>(|_| None);
883        for (item, entity) in items.iter_mut().zip(entities) {
884            *item = Some(Q::fetch(self, entity)?);
885        }
886        Ok(items.map(|item| item.expect("every requested entity was borrowed")))
887    }
888
889    /// Queries up to eight access types, counting each [`Entity`] entry.
890    /// Repeated shared access is valid; any repeated mutable access is rejected.
891    ///
892    /// `Option<&T>` yields `Option<Ref<'_, T>>`; `Option<&mut T>` yields
893    /// `Option<RefMut<'_, T>>`. Only required accesses filter entities: an
894    /// optional-only query visits every live entity, including componentless ones.
895    /// A missing optional component yields `None`, but an incompatible borrow of
896    /// a present component still fails. Use [`QueryBorrow::try_iter`] for fallible
897    /// iteration; ordinary iteration panics on borrow conflicts.
898    ///
899    /// Optional access participates in signature validation even if the component
900    /// is absent everywhere. For example, `(&T, Option<&mut T>)` is rejected by
901    /// [`World::try_query`] with [`Error::ConflictingQuery`].
902    ///
903    /// This fixed-step recipe updates moving actors while retaining stationary
904    /// scenery and optionally recording presentation changes:
905    ///
906    /// ```
907    /// use ferravex_ecs::{Entity, Error, World};
908    /// struct Position(f32);
909    /// struct Velocity(f32);
910    /// struct Presentation { updates: u32 }
911    ///
912    /// let mut world = World::new();
913    /// let actor = world.spawn((Position(1.0), Velocity(2.0), Presentation { updates: 0 }));
914    /// let scenery = world.spawn((Position(5.0),));
915    /// world.spawn((Velocity(99.0),)); // No Position: excluded by the required access.
916    /// let mut visited = 0;
917    /// let fixed_dt = 0.5;
918    /// for row in world.query::<(Entity, &mut Position, Option<&Velocity>, Option<&mut Presentation>)>().try_iter() {
919    ///     let (entity, mut position, velocity, presentation) = row?;
920    ///     if let Some(velocity) = velocity {
921    ///         position.0 += velocity.0 * fixed_dt;
922    ///         if let Some(mut presentation) = presentation {
923    ///             presentation.updates += 1;
924    ///         }
925    ///     }
926    ///     assert!(entity == actor || entity == scenery);
927    ///     visited += 1;
928    /// }
929    /// assert_eq!(visited, 2);
930    /// assert_eq!(world.get::<&Position>(actor)?.0, 2.0);
931    /// assert_eq!(world.get::<&Position>(scenery)?.0, 5.0);
932    /// assert_eq!(world.get::<&Presentation>(actor)?.updates, 1);
933    /// # Ok::<(), Error>(())
934    /// ```
935    pub fn query<Q: Query>(&self) -> QueryBorrow<'_, Q> {
936        self.try_query().unwrap_or_else(|error| panic!("{error}"))
937    }
938
939    pub fn try_query<Q: Query>(&self) -> Result<QueryBorrow<'_, Q>, Error> {
940        self.try_query_filtered::<Q, ()>()
941    }
942
943    /// Queries fetched accesses `Q` subject to structural component filter `F`.
944    ///
945    /// Filters inspect presence only: they never borrow component values or add
946    /// accesses to `Q`'s alias checks. Both the filter and all required accesses
947    /// must match before any value is borrowed. [`With`], [`Without`], [`All`],
948    /// [`Any`] and [`Not`] compose through tuples of up to four clauses per group.
949    /// `()` accepts every live entity; `Any<()>` accepts none. Nest groups for
950    /// larger expressions. There is no runtime filter storage or allocation;
951    /// expression size and nesting are fixed by the caller's concrete type.
952    ///
953    /// Live slots retain their normal order. Invalid fetched signatures panic;
954    /// use [`World::try_query_filtered`] to report them instead. As with
955    /// [`World::query`], [`QueryBorrow::try_iter`] reports fetched borrow conflicts
956    /// and continues, while ordinary iteration panics on them. Contradictory
957    /// filters simply match nothing and never excuse an invalid `Q` signature.
958    ///
959    /// This fixed-tick recipe moves active actors or projectiles, excludes frozen
960    /// entities, and optionally records presentation updates. Holding a mutable
961    /// marker guard does not interfere with filtering:
962    ///
963    /// ```
964    /// use ferravex_ecs::{All, Any, Entity, Error, Not, With, Without, World};
965    /// struct Position(f32);
966    /// struct Velocity(f32);
967    /// struct Presentation(u32);
968    /// struct Active;
969    /// struct Projectile;
970    /// struct Frozen;
971    ///
972    /// let mut world = World::new();
973    /// let actor = world.spawn((Position(1.0), Velocity(2.0), Active, Presentation(0)));
974    /// let projectile = world.spawn((Position(4.0), Projectile));
975    /// let frozen = world.spawn((Position(9.0), Active, Frozen));
976    /// world.spawn((Position(20.0),)); // Neither Active nor Projectile.
977    /// let marker = world.get::<&mut Active>(actor)?;
978    /// type Moving = All<(Any<(With<Active>, With<Projectile>)>, Without<Frozen>)>;
979    /// let fixed_dt = 0.5; // Call once per executed simulation tick.
980    /// let mut visited = 0;
981    /// for row in world.query_filtered::<
982    ///     (Entity, &mut Position, Option<&Velocity>, Option<&mut Presentation>), Moving
983    /// >().try_iter() {
984    ///     let (entity, mut position, velocity, presentation) = row?;
985    ///     if let Some(velocity) = velocity { position.0 += velocity.0 * fixed_dt; }
986    ///     if let Some(mut presentation) = presentation { presentation.0 += 1; }
987    ///     assert!(entity == actor || entity == projectile);
988    ///     visited += 1;
989    /// }
990    /// assert_eq!(visited, 2);
991    /// assert_eq!(world.get::<&Position>(actor)?.0, 2.0);
992    /// assert_eq!(world.get::<&Presentation>(actor)?.0, 1);
993    /// assert_eq!(world.get::<&Position>(frozen)?.0, 9.0);
994    /// assert_eq!(world.query_filtered::<Entity, Not<Moving>>().iter().count(), 2);
995    /// drop(marker);
996    /// # Ok::<(), Error>(())
997    /// ```
998    pub fn query_filtered<Q: Query, F: QueryFilter>(&self) -> QueryBorrow<'_, Q, F> {
999        self.try_query_filtered()
1000            .unwrap_or_else(|error| panic!("{error}"))
1001    }
1002
1003    /// Validates fetched access aliases before returning a filtered query.
1004    ///
1005    /// Presence filters introduce no borrow conflicts. Only `Q` is validated;
1006    /// dynamic borrow errors arise when iterating matching entities. Validation
1007    /// still runs on an empty world or a filter that excludes every entity.
1008    ///
1009    /// ```
1010    /// use ferravex_ecs::{Any, Error, With, World};
1011    /// let world = World::new();
1012    /// assert!(matches!(
1013    ///     world.try_query_filtered::<(&mut i32, Option<&i32>), Any<()>>(),
1014    ///     Err(Error::ConflictingQuery(_))
1015    /// ));
1016    /// assert_eq!(world.try_query_filtered::<&mut i32, With<i32>>()?.iter().count(), 0);
1017    /// # Ok::<(), Error>(())
1018    /// ```
1019    pub fn try_query_filtered<Q: Query, F: QueryFilter>(
1020        &self,
1021    ) -> Result<QueryBorrow<'_, Q, F>, Error> {
1022        Q::validate()?;
1023        Ok(QueryBorrow {
1024            world: self,
1025            marker: PhantomData,
1026        })
1027    }
1028
1029    /// Live identities in stable slot order, without borrowing any components.
1030    pub fn entities(&self) -> impl Iterator<Item = Entity> + '_ {
1031        self.slots.iter().enumerate().filter_map(|(index, slot)| {
1032            slot.alive.then_some(Entity {
1033                index: index as u32,
1034                generation: slot.generation,
1035            })
1036        })
1037    }
1038
1039    fn validate(&self, entity: Entity) -> Result<(), Error> {
1040        if self.contains(entity) {
1041            Ok(())
1042        } else {
1043            Err(Error::NoSuchEntity(entity))
1044        }
1045    }
1046
1047    fn preflight_batch<B: Bundle>(&self, count: usize, output: usize) -> Result<(), SpawnError> {
1048        validate_bundle::<B>().map_err(|error| match error {
1049            Error::DuplicateComponent(name) => SpawnError::DuplicateComponent(name),
1050            _ => unreachable!("bundle validation only checks duplicate types"),
1051        })?;
1052        if output < count {
1053            return Err(SpawnError::OutputTooSmall {
1054                required: count,
1055                available: output,
1056            });
1057        }
1058        let required = required_batch_slots(self.slots.len(), &self.free, count)?;
1059        if required > self.prepared_entities {
1060            return Err(SpawnError::EntityCapacity {
1061                required,
1062                prepared: self.prepared_entities,
1063            });
1064        }
1065        for (id, component) in B::component_types_inline().into_iter().flatten() {
1066            let prepared = self
1067                .storages
1068                .get(&id)
1069                .map_or(0, |storage| storage.prepared_capacity());
1070            if required > prepared {
1071                return Err(SpawnError::ComponentCapacity {
1072                    component,
1073                    required,
1074                    prepared,
1075                });
1076            }
1077        }
1078        Ok(())
1079    }
1080
1081    /// One shared, out-of-line lookup for every component type's fetches.
1082    #[inline(never)]
1083    fn erased_storage(&self, id: TypeId) -> Option<&dyn ErasedStorage> {
1084        self.storages.get(&id).map(|storage| &**storage)
1085    }
1086
1087    fn storage<T: 'static>(&self) -> Option<&Storage<T>> {
1088        self.erased_storage(TypeId::of::<T>())
1089            .and_then(|s| s.as_any().downcast_ref::<Storage<T>>())
1090    }
1091
1092    fn presence_bits<T: 'static>(&self) -> &[u64] {
1093        self.erased_storage(TypeId::of::<T>())
1094            .map_or(&[], ErasedStorage::presence)
1095    }
1096
1097    fn cell<T: 'static>(&self, index: usize) -> Option<&RefCell<T>> {
1098        self.storage::<T>()
1099            .and_then(|storage| storage.slots.get(index))
1100            .and_then(Option::as_ref)
1101    }
1102
1103    fn put<T: 'static>(&mut self, index: usize, value: T) {
1104        let storage = self
1105            .storages
1106            .entry(TypeId::of::<T>())
1107            .or_insert_with(|| Box::<Storage<T>>::default())
1108            .as_any_mut()
1109            .downcast_mut::<Storage<T>>()
1110            .expect("component storage type matches its TypeId");
1111        if storage.slots.len() <= index {
1112            storage.slots.resize_with(index + 1, || None);
1113        }
1114        storage.slots[index] = Some(RefCell::new(value));
1115        let word = index >> 6;
1116        if storage.present.len() <= word {
1117            storage.present.resize(word + 1, 0);
1118        }
1119        storage.present[word] |= 1_u64 << (index & 63);
1120    }
1121}
1122
1123fn check_identity_capacity(capacity: usize) -> Result<(), SpawnError> {
1124    if capacity > 0 && u32::try_from(capacity - 1).is_err() {
1125        Err(SpawnError::IdentityCapacity)
1126    } else {
1127        Ok(())
1128    }
1129}
1130
1131fn required_batch_slots(slots: usize, free: &[u32], count: usize) -> Result<usize, SpawnError> {
1132    if count == 0 {
1133        return Ok(0);
1134    }
1135    let new = count.saturating_sub(free.len());
1136    let required = if new > 0 {
1137        slots.checked_add(new).ok_or(SpawnError::IdentityCapacity)?
1138    } else {
1139        // Only selected free slots matter, not the whole sparse high-water mark.
1140        (free.iter().rev().take(count).copied().max().unwrap() as usize)
1141            .checked_add(1)
1142            .ok_or(SpawnError::IdentityCapacity)?
1143    };
1144    check_identity_capacity(required)?;
1145    Ok(required)
1146}
1147
1148fn prepare_storage<T>(storage: &mut Storage<T>, capacity: usize) -> Result<(), SpawnError> {
1149    storage
1150        .slots
1151        .try_reserve_exact(capacity.saturating_sub(storage.slots.len()))
1152        .map_err(|_| SpawnError::AllocationFailed)?;
1153    let words = capacity.div_ceil(64);
1154    storage
1155        .present
1156        .try_reserve_exact(words.saturating_sub(storage.present.len()))
1157        .map_err(|_| SpawnError::AllocationFailed)?;
1158    if capacity > storage.slots.len() {
1159        storage.slots.resize_with(capacity, || None);
1160    }
1161    if words > storage.present.len() {
1162        storage.present.resize(words, 0);
1163    }
1164    storage.prepared = storage.prepared.max(capacity);
1165    Ok(())
1166}
1167
1168mod sealed {
1169    use super::World;
1170
1171    pub trait Bundle {
1172        fn component_types_inline() -> [Option<(std::any::TypeId, &'static str)>; 8];
1173    }
1174    pub trait Access {
1175        type State<'world>;
1176        fn prepare(world: &World) -> Self::State<'_>;
1177        fn word_mask(state: &Self::State<'_>, word_idx: usize) -> u64;
1178    }
1179    pub trait CloneBundle {}
1180    pub trait Query {
1181        type State<'world>;
1182        fn prepare(world: &World) -> Self::State<'_>;
1183        fn word_mask(state: &Self::State<'_>, word_idx: usize) -> u64;
1184    }
1185    pub trait QueryFilter {
1186        fn word_mask(world: &World, word_idx: usize) -> u64;
1187    }
1188}
1189
1190/// Tuple of zero to eight owned component values accepted by spawn and insert.
1191/// Implementations are sealed so validation and insertion cannot disagree.
1192/// Duplicate types are rejected before any entity allocation or component write.
1193/// Validation uses bounded stack metadata; entity and component storage may allocate.
1194///
1195/// This actor recipe authors five components together and updates them once per
1196/// executed simulation tick, using six fetched entries including the identity:
1197///
1198/// ```
1199/// use ferravex_ecs::{Entity, Error, With, World};
1200/// struct Position(f32);
1201/// struct Velocity(f32);
1202/// struct Health(u32);
1203/// struct Faction(u8);
1204/// struct Presentation { last_position: f32 }
1205///
1206/// let mut world = World::new();
1207/// let actor = world.try_spawn((
1208///     Position(1.0), Velocity(2.0), Health(10), Faction(1),
1209///     Presentation { last_position: 1.0 },
1210/// ))?;
1211/// let fixed_dt = 0.5; // Caller invokes this system once per executed tick.
1212/// for row in world.query_filtered::<(
1213///     Entity, &mut Position, &Velocity, &Health, &Faction, Option<&mut Presentation>,
1214/// ), With<Faction>>().try_iter() {
1215///     let (id, mut position, velocity, health, faction, presentation) = row?;
1216///     assert_eq!(id, actor);
1217///     if health.0 > 0 && faction.0 == 1 {
1218///         position.0 += velocity.0 * fixed_dt;
1219///         if let Some(mut presentation) = presentation {
1220///             presentation.last_position = position.0;
1221///         }
1222///     }
1223/// }
1224/// assert_eq!(world.get::<&Position>(actor)?.0, 2.0);
1225/// assert_eq!(world.get::<&Presentation>(actor)?.last_position, 2.0);
1226/// world.despawn(actor)?;
1227/// assert!(world.is_empty());
1228/// # Ok::<(), Error>(())
1229/// ```
1230///
1231/// Nine component entries exceed the ceiling, even if their types are distinct:
1232///
1233/// ```compile_fail
1234/// use ferravex_ecs::World;
1235/// World::new().spawn((0_u8, 0_u16, 0_u32, 0_u64, 0_i8, 0_i16, 0_i32, 0_i64, false));
1236/// ```
1237pub trait Bundle: sealed::Bundle {
1238    #[doc(hidden)]
1239    fn component_types(types: &mut Vec<(TypeId, &'static str)>);
1240    #[doc(hidden)]
1241    fn write(self, world: &mut World, index: usize);
1242}
1243
1244/// Explicit tuple of zero to eight owned `Clone + 'static` component types.
1245///
1246/// Sealed to keep selected reads and spawned bundles consistent. See
1247/// [`World::plan_duplication`] for a complete actor-template recipe. Choose stored
1248/// component types rather than query access types, for example `(Position, Health)`.
1249/// An `Entity` entry selects an explicitly stored Entity component, not identity.
1250///
1251/// Non-Clone components remain supported by ordinary bundles, but cannot be
1252/// selected for duplication:
1253///
1254/// ```compile_fail
1255/// use ferravex_ecs::World;
1256/// struct AudioVoice;
1257/// let mut world = World::new();
1258/// let entity = world.spawn((AudioVoice,));
1259/// world.plan_duplication::<(AudioVoice,), 1>([entity]);
1260/// ```
1261pub trait CloneBundle: Bundle + sealed::CloneBundle {
1262    #[doc(hidden)]
1263    type Borrowed<'world>;
1264    #[doc(hidden)]
1265    fn borrow(world: &World, entity: Entity) -> Result<Self::Borrowed<'_>, Error>;
1266    #[doc(hidden)]
1267    fn clone_components(components: &Self::Borrowed<'_>) -> Self;
1268}
1269
1270impl sealed::Bundle for () {
1271    fn component_types_inline() -> [Option<(TypeId, &'static str)>; 8] {
1272        [None; 8]
1273    }
1274}
1275impl Bundle for () {
1276    fn component_types(_: &mut Vec<(TypeId, &'static str)>) {}
1277    fn write(self, _: &mut World, _: usize) {}
1278}
1279impl sealed::CloneBundle for () {}
1280impl CloneBundle for () {
1281    type Borrowed<'world> = ();
1282    fn borrow(_: &World, _: Entity) -> Result<(), Error> {
1283        Ok(())
1284    }
1285    fn clone_components(_: &()) -> Self {}
1286}
1287
1288macro_rules! bundle {
1289    ($($name:ident : $index:tt),+) => {
1290        impl<$($name: 'static),+> sealed::Bundle for ($($name,)+) {
1291            fn component_types_inline() -> [Option<(TypeId, &'static str)>; 8] {
1292                let mut types = [None; 8];
1293                $(types[$index] = Some((TypeId::of::<$name>(), type_name::<$name>()));)+
1294                types
1295            }
1296        }
1297        impl<$($name: 'static),+> Bundle for ($($name,)+) {
1298            fn component_types(types: &mut Vec<(TypeId, &'static str)>) {
1299                // Preserve the existing public metadata API for callers that use it.
1300                types.extend(<Self as sealed::Bundle>::component_types_inline().into_iter().flatten());
1301            }
1302            fn write(self, world: &mut World, index: usize) {
1303                $(world.put(index, self.$index);)+
1304            }
1305        }
1306        impl<$($name: Clone + 'static),+> sealed::CloneBundle for ($($name,)+) {}
1307        impl<$($name: Clone + 'static),+> CloneBundle for ($($name,)+) {
1308            type Borrowed<'world> = ($(Ref<'world, $name>,)+);
1309            fn borrow(world: &World, entity: Entity) -> Result<Self::Borrowed<'_>, Error> {
1310                Ok(($(world.get::<&$name>(entity)?,)+))
1311            }
1312            fn clone_components(components: &Self::Borrowed<'_>) -> Self {
1313                ($(<$name as Clone>::clone(&components.$index),)+)
1314            }
1315        }
1316    }
1317}
1318bundle!(A: 0);
1319bundle!(A: 0, B: 1);
1320bundle!(A: 0, B: 1, C: 2);
1321bundle!(A: 0, B: 1, C: 2, D: 3);
1322bundle!(A: 0, B: 1, C: 2, D: 3, E: 4);
1323bundle!(A: 0, B: 1, C: 2, D: 3, E: 4, F: 5);
1324bundle!(A: 0, B: 1, C: 2, D: 3, E: 4, F: 5, G: 6);
1325bundle!(A: 0, B: 1, C: 2, D: 3, E: 4, F: 5, G: 6, H: 7);
1326
1327fn validate_bundle<B: Bundle>() -> Result<(), Error> {
1328    let types = B::component_types_inline();
1329    for (index, item) in types.iter().enumerate() {
1330        if let Some((id, name)) = item
1331            && types[..index].iter().flatten().any(|other| other.0 == *id)
1332        {
1333            return Err(Error::DuplicateComponent(name));
1334        }
1335    }
1336    Ok(())
1337}
1338
1339#[doc(hidden)]
1340pub struct AccessInfo {
1341    id: TypeId,
1342    name: &'static str,
1343    mutable: bool,
1344}
1345
1346/// A required (`&T`, `&mut T`) or optional (`Option<&T>`, `Option<&mut T>`)
1347/// component access, or the entity identity itself.
1348///
1349/// Optional accesses return optional borrow guards, not naked references. They
1350/// match every live entity, returning `None` only for absent components. See
1351/// [`World::get`] and [`World::query`] for runnable examples.
1352pub trait Access: sealed::Access {
1353    type Item<'world>;
1354    #[doc(hidden)]
1355    fn info() -> Option<AccessInfo>;
1356    #[doc(hidden)]
1357    fn matches(world: &World, entity: Entity) -> bool;
1358    #[doc(hidden)]
1359    fn fetch(world: &World, entity: Entity) -> Result<Self::Item<'_>, Error>;
1360    #[doc(hidden)]
1361    fn fetch_prepared<'world>(
1362        state: &Self::State<'world>,
1363        world: &'world World,
1364        index: usize,
1365    ) -> Result<Self::Item<'world>, Error>;
1366}
1367
1368impl<T: 'static> sealed::Access for &T {
1369    type State<'world> = Option<(&'world [Option<RefCell<T>>], &'world [u64])>;
1370    #[inline]
1371    fn prepare(world: &World) -> Self::State<'_> {
1372        world
1373            .storage::<T>()
1374            .map(|s| (s.slots.as_slice(), s.present.as_slice()))
1375    }
1376    #[inline]
1377    fn word_mask(state: &Self::State<'_>, word_idx: usize) -> u64 {
1378        state.map_or(0, |(_, bits)| bits.get(word_idx).copied().unwrap_or(0))
1379    }
1380}
1381impl<T: 'static> Access for &T {
1382    type Item<'world> = Ref<'world, T>;
1383    fn info() -> Option<AccessInfo> {
1384        Some(AccessInfo {
1385            id: TypeId::of::<T>(),
1386            name: type_name::<T>(),
1387            mutable: false,
1388        })
1389    }
1390    fn matches(world: &World, entity: Entity) -> bool {
1391        world.has::<T>(entity)
1392    }
1393    fn fetch(world: &World, entity: Entity) -> Result<Self::Item<'_>, Error> {
1394        world.validate(entity)?;
1395        world
1396            .cell::<T>(entity.index as usize)
1397            .ok_or(Error::MissingComponent(type_name::<T>()))?
1398            .try_borrow()
1399            .map_err(|_| Error::BorrowConflict(type_name::<T>()))
1400    }
1401    #[inline]
1402    fn fetch_prepared<'world>(
1403        state: &Self::State<'world>,
1404        _: &'world World,
1405        index: usize,
1406    ) -> Result<Self::Item<'world>, Error> {
1407        state
1408            .and_then(|(slots, _)| slots.get(index))
1409            .and_then(Option::as_ref)
1410            .ok_or(Error::MissingComponent(type_name::<T>()))?
1411            .try_borrow()
1412            .map_err(|_| Error::BorrowConflict(type_name::<T>()))
1413    }
1414}
1415impl<T: 'static> sealed::Access for &mut T {
1416    type State<'world> = Option<(&'world [Option<RefCell<T>>], &'world [u64])>;
1417    #[inline]
1418    fn prepare(world: &World) -> Self::State<'_> {
1419        world
1420            .storage::<T>()
1421            .map(|s| (s.slots.as_slice(), s.present.as_slice()))
1422    }
1423    #[inline]
1424    fn word_mask(state: &Self::State<'_>, word_idx: usize) -> u64 {
1425        state.map_or(0, |(_, bits)| bits.get(word_idx).copied().unwrap_or(0))
1426    }
1427}
1428impl<T: 'static> Access for &mut T {
1429    type Item<'world> = RefMut<'world, T>;
1430    fn info() -> Option<AccessInfo> {
1431        Some(AccessInfo {
1432            id: TypeId::of::<T>(),
1433            name: type_name::<T>(),
1434            mutable: true,
1435        })
1436    }
1437    fn matches(world: &World, entity: Entity) -> bool {
1438        world.has::<T>(entity)
1439    }
1440    fn fetch(world: &World, entity: Entity) -> Result<Self::Item<'_>, Error> {
1441        world.validate(entity)?;
1442        world
1443            .cell::<T>(entity.index as usize)
1444            .ok_or(Error::MissingComponent(type_name::<T>()))?
1445            .try_borrow_mut()
1446            .map_err(|_| Error::BorrowConflict(type_name::<T>()))
1447    }
1448    #[inline]
1449    fn fetch_prepared<'world>(
1450        state: &Self::State<'world>,
1451        _: &'world World,
1452        index: usize,
1453    ) -> Result<Self::Item<'world>, Error> {
1454        state
1455            .and_then(|(slots, _)| slots.get(index))
1456            .and_then(Option::as_ref)
1457            .ok_or(Error::MissingComponent(type_name::<T>()))?
1458            .try_borrow_mut()
1459            .map_err(|_| Error::BorrowConflict(type_name::<T>()))
1460    }
1461}
1462impl<T: 'static> sealed::Access for Option<&T> {
1463    type State<'world> = Option<&'world [Option<RefCell<T>>]>;
1464    #[inline]
1465    fn prepare(world: &World) -> Self::State<'_> {
1466        world.storage::<T>().map(|s| s.slots.as_slice())
1467    }
1468    #[inline]
1469    fn word_mask(_: &Self::State<'_>, _: usize) -> u64 {
1470        u64::MAX
1471    }
1472}
1473impl<T: 'static> Access for Option<&T> {
1474    type Item<'world> = Option<Ref<'world, T>>;
1475    fn info() -> Option<AccessInfo> {
1476        // Optionality changes matching, never the aliasing rules for a type.
1477        <&T as Access>::info()
1478    }
1479    fn matches(world: &World, entity: Entity) -> bool {
1480        world.contains(entity)
1481    }
1482    fn fetch(world: &World, entity: Entity) -> Result<Self::Item<'_>, Error> {
1483        world.validate(entity)?;
1484        world
1485            .cell::<T>(entity.index as usize)
1486            .map(|cell| {
1487                cell.try_borrow()
1488                    .map_err(|_| Error::BorrowConflict(type_name::<T>()))
1489            })
1490            .transpose()
1491    }
1492    #[inline]
1493    fn fetch_prepared<'world>(
1494        state: &Self::State<'world>,
1495        _: &'world World,
1496        index: usize,
1497    ) -> Result<Self::Item<'world>, Error> {
1498        state
1499            .and_then(|slots| slots.get(index))
1500            .and_then(Option::as_ref)
1501            .map(|cell| {
1502                cell.try_borrow()
1503                    .map_err(|_| Error::BorrowConflict(type_name::<T>()))
1504            })
1505            .transpose()
1506    }
1507}
1508impl<T: 'static> sealed::Access for Option<&mut T> {
1509    type State<'world> = Option<&'world [Option<RefCell<T>>]>;
1510    #[inline]
1511    fn prepare(world: &World) -> Self::State<'_> {
1512        world.storage::<T>().map(|s| s.slots.as_slice())
1513    }
1514    #[inline]
1515    fn word_mask(_: &Self::State<'_>, _: usize) -> u64 {
1516        u64::MAX
1517    }
1518}
1519impl<T: 'static> Access for Option<&mut T> {
1520    type Item<'world> = Option<RefMut<'world, T>>;
1521    fn info() -> Option<AccessInfo> {
1522        <&mut T as Access>::info()
1523    }
1524    fn matches(world: &World, entity: Entity) -> bool {
1525        world.contains(entity)
1526    }
1527    fn fetch(world: &World, entity: Entity) -> Result<Self::Item<'_>, Error> {
1528        world.validate(entity)?;
1529        world
1530            .cell::<T>(entity.index as usize)
1531            .map(|cell| {
1532                cell.try_borrow_mut()
1533                    .map_err(|_| Error::BorrowConflict(type_name::<T>()))
1534            })
1535            .transpose()
1536    }
1537    #[inline]
1538    fn fetch_prepared<'world>(
1539        state: &Self::State<'world>,
1540        _: &'world World,
1541        index: usize,
1542    ) -> Result<Self::Item<'world>, Error> {
1543        state
1544            .and_then(|slots| slots.get(index))
1545            .and_then(Option::as_ref)
1546            .map(|cell| {
1547                cell.try_borrow_mut()
1548                    .map_err(|_| Error::BorrowConflict(type_name::<T>()))
1549            })
1550            .transpose()
1551    }
1552}
1553impl sealed::Access for Entity {
1554    type State<'world> = ();
1555    #[inline]
1556    fn prepare(_: &World) -> Self::State<'_> {}
1557    #[inline]
1558    fn word_mask(_: &Self::State<'_>, _: usize) -> u64 {
1559        u64::MAX
1560    }
1561}
1562impl Access for Entity {
1563    type Item<'world> = Entity;
1564    fn info() -> Option<AccessInfo> {
1565        None
1566    }
1567    fn matches(world: &World, entity: Entity) -> bool {
1568        world.contains(entity)
1569    }
1570    fn fetch(world: &World, entity: Entity) -> Result<Self::Item<'_>, Error> {
1571        world.validate(entity)?;
1572        Ok(entity)
1573    }
1574    #[inline]
1575    fn fetch_prepared<'world>(
1576        _: &Self::State<'world>,
1577        world: &'world World,
1578        index: usize,
1579    ) -> Result<Self::Item<'world>, Error> {
1580        Ok(Entity {
1581            index: index as u32,
1582            generation: world.slots[index].generation,
1583        })
1584    }
1585}
1586
1587/// Query signature: one access type or a tuple of one to eight access types.
1588/// Each [`Entity`] counts as an entry. Filter clauses have their own separate
1589/// four-clause group bound; see [`QueryFilter`]. See [`Bundle`] for an actor system.
1590///
1591/// Eight entries, including an entity identity and optional components:
1592///
1593/// ```
1594/// use ferravex_ecs::{Entity, Error, World};
1595/// let mut world = World::new();
1596/// let entity = world.spawn((1_u8, 2_u16, 3_u32, 4_u64, 5_i8, 6_i16, 7_i32, 8_i64));
1597/// let [(id, mut a, b, c, d, e, f, absent)] = world.get_many::<(
1598///     Entity, &mut u8, &u16, &u32, &u64, &i8, &i16, Option<&bool>,
1599/// ), 1>([entity])?;
1600/// *a += 1;
1601/// assert_eq!(id, entity);
1602/// assert_eq!((*a, *b, *c, *d, *e, *f), (2, 2, 3, 4, 5, 6));
1603/// assert!(absent.is_none());
1604/// # Ok::<(), Error>(())
1605/// ```
1606///
1607/// Entity plus eight component accesses exceeds the fetched tuple ceiling:
1608///
1609/// ```compile_fail
1610/// use ferravex_ecs::{Entity, World};
1611/// World::new().query::<(Entity, &u8, &u16, &u32, &u64, &i8, &i16, &i32, &i64)>();
1612/// ```
1613pub trait Query: sealed::Query {
1614    type Item<'world>;
1615    #[doc(hidden)]
1616    fn validate() -> Result<(), Error>;
1617    #[doc(hidden)]
1618    fn matches(world: &World, entity: Entity) -> bool;
1619    #[doc(hidden)]
1620    fn fetch(world: &World, entity: Entity) -> Result<Self::Item<'_>, Error>;
1621    #[doc(hidden)]
1622    fn fetch_prepared_item<'world>(
1623        state: &Self::State<'world>,
1624        world: &'world World,
1625        index: usize,
1626    ) -> Result<Self::Item<'world>, Error>;
1627}
1628
1629impl<A: Access> sealed::Query for A {
1630    type State<'world> = A::State<'world>;
1631    #[inline]
1632    fn prepare(world: &World) -> Self::State<'_> {
1633        A::prepare(world)
1634    }
1635    #[inline]
1636    fn word_mask(state: &Self::State<'_>, word_idx: usize) -> u64 {
1637        A::word_mask(state, word_idx)
1638    }
1639}
1640impl<A: Access> Query for A {
1641    type Item<'world> = A::Item<'world>;
1642    fn validate() -> Result<(), Error> {
1643        Ok(())
1644    }
1645    fn matches(world: &World, entity: Entity) -> bool {
1646        A::matches(world, entity)
1647    }
1648    fn fetch(world: &World, entity: Entity) -> Result<Self::Item<'_>, Error> {
1649        A::fetch(world, entity)
1650    }
1651    #[inline]
1652    fn fetch_prepared_item<'world>(
1653        state: &Self::State<'world>,
1654        world: &'world World,
1655        index: usize,
1656    ) -> Result<Self::Item<'world>, Error> {
1657        A::fetch_prepared(state, world, index)
1658    }
1659}
1660
1661macro_rules! query_tuple {
1662    ($($name:ident : $index:tt),+) => {
1663        impl<$($name: Access),+> sealed::Query for ($($name,)+) {
1664            type State<'world> = ($($name::State<'world>,)+);
1665            #[inline]
1666            fn prepare(world: &World) -> Self::State<'_> {
1667                ($($name::prepare(world),)+)
1668            }
1669            #[inline]
1670            fn word_mask(state: &Self::State<'_>, word_idx: usize) -> u64 {
1671                $($name::word_mask(&state.$index, word_idx))&+
1672            }
1673        }
1674        impl<$($name: Access),+> Query for ($($name,)+) {
1675            type Item<'world> = ($($name::Item<'world>,)+);
1676            fn validate() -> Result<(), Error> {
1677                let access = [$($name::info(),)+];
1678                for (index, item) in access.iter().enumerate() {
1679                    if let Some(item) = item {
1680                        if access[..index].iter().flatten().any(|other| {
1681                            other.id == item.id && (other.mutable || item.mutable)
1682                        }) { return Err(Error::ConflictingQuery(item.name)); }
1683                    }
1684                }
1685                Ok(())
1686            }
1687            fn matches(world: &World, entity: Entity) -> bool {
1688                $($name::matches(world, entity))&&+
1689            }
1690            fn fetch(world: &World, entity: Entity) -> Result<Self::Item<'_>, Error> {
1691                Ok(($($name::fetch(world, entity)?,)+))
1692            }
1693            #[inline]
1694            fn fetch_prepared_item<'world>(
1695                state: &Self::State<'world>,
1696                world: &'world World,
1697                index: usize,
1698            ) -> Result<Self::Item<'world>, Error> {
1699                Ok(($($name::fetch_prepared(&state.$index, world, index)?,)+))
1700            }
1701        }
1702    }
1703}
1704query_tuple!(A: 0);
1705query_tuple!(A: 0, B: 1);
1706query_tuple!(A: 0, B: 1, C: 2);
1707query_tuple!(A: 0, B: 1, C: 2, D: 3);
1708query_tuple!(A: 0, B: 1, C: 2, D: 3, E: 4);
1709query_tuple!(A: 0, B: 1, C: 2, D: 3, E: 4, F: 5);
1710query_tuple!(A: 0, B: 1, C: 2, D: 3, E: 4, F: 5, G: 6);
1711query_tuple!(A: 0, B: 1, C: 2, D: 3, E: 4, F: 5, G: 6, H: 7);
1712
1713/// A sealed structural component-presence predicate for [`World::query_filtered`].
1714///
1715/// Filters are types, not values or component accesses. `With<T>` and
1716/// `Without<T>` test whether a live entity has a component of exactly type `T`.
1717/// They do not inspect tag values (see the engine's separate `tags::TagPredicate`).
1718/// Tuples and [`All`] require every clause; [`Any`] requires at least one;
1719/// [`Not`] negates a predicate. Groups have zero to four clauses and may nest.
1720/// Empty conjunctions (`()`, `All<()>`) are true; `Any<()>` is false. Negation
1721/// applies within the live entity universe; dead slots are always excluded.
1722/// See [`World::query_filtered`] for a runnable tick-system recipe.
1723///
1724/// ```
1725/// use ferravex_ecs::{All, Any, Entity, Not, With, Without, World};
1726/// let mut world = World::new();
1727/// let tagged = world.spawn((1_u32,));
1728/// world.spawn(());
1729/// assert_eq!(world.query_filtered::<Entity, All<(With<u32>, Without<bool>)>>()
1730///     .iter().collect::<Vec<_>>(), [tagged]);
1731/// assert_eq!(world.query_filtered::<Entity, Any<()>>().iter().count(), 0);
1732/// assert_eq!(world.query_filtered::<Entity, Not<Any<()>>>().iter().count(), 2);
1733/// ```
1734///
1735/// Each tuple group is bounded to four clauses. Nest a group to combine more:
1736///
1737/// ```compile_fail
1738/// use ferravex_ecs::{Any, Entity, With, World};
1739/// let world = World::new();
1740/// world.query_filtered::<Entity, Any<(
1741///     With<u8>, With<u16>, With<u32>, With<u64>, With<bool>
1742/// )>>(); // Five clauses in one group are unsupported.
1743/// ```
1744pub trait QueryFilter: sealed::QueryFilter {
1745    #[doc(hidden)]
1746    fn matches(world: &World, entity: Entity) -> bool;
1747}
1748
1749/// Presence of component `T`, without borrowing its value.
1750/// Used as a type argument; see [`World::query_filtered`] for a runnable example.
1751pub struct With<T: 'static>(PhantomData<fn() -> T>);
1752
1753/// Absence of component `T`, without borrowing any value.
1754/// Used as a type argument; see [`QueryFilter`] for a runnable example.
1755pub struct Without<T: 'static>(PhantomData<fn() -> T>);
1756
1757/// Conjunction of a tuple of zero to four filters; groups may nest.
1758/// `All<()>` matches every live entity. See [`World::query_filtered`].
1759pub struct All<F>(PhantomData<fn() -> F>);
1760
1761/// Disjunction of a tuple of zero to four filters; groups may nest.
1762/// `Any<()>` matches no entities. See [`QueryFilter`] for a runnable example.
1763pub struct Any<F>(PhantomData<fn() -> F>);
1764
1765/// Negation of one filter within live entities. See [`QueryFilter`].
1766pub struct Not<F: QueryFilter>(PhantomData<fn() -> F>);
1767
1768impl<T: 'static> sealed::QueryFilter for With<T> {
1769    #[inline]
1770    fn word_mask(world: &World, word_idx: usize) -> u64 {
1771        world
1772            .presence_bits::<T>()
1773            .get(word_idx)
1774            .copied()
1775            .unwrap_or(0)
1776    }
1777}
1778impl<T: 'static> QueryFilter for With<T> {
1779    fn matches(world: &World, entity: Entity) -> bool {
1780        world.has::<T>(entity)
1781    }
1782}
1783impl<T: 'static> sealed::QueryFilter for Without<T> {
1784    #[inline]
1785    fn word_mask(world: &World, word_idx: usize) -> u64 {
1786        !world
1787            .presence_bits::<T>()
1788            .get(word_idx)
1789            .copied()
1790            .unwrap_or(0)
1791    }
1792}
1793impl<T: 'static> QueryFilter for Without<T> {
1794    fn matches(world: &World, entity: Entity) -> bool {
1795        world.contains(entity) && !world.has::<T>(entity)
1796    }
1797}
1798impl<F: QueryFilter> sealed::QueryFilter for Not<F> {
1799    #[inline]
1800    fn word_mask(world: &World, word_idx: usize) -> u64 {
1801        !F::word_mask(world, word_idx)
1802    }
1803}
1804impl<F: QueryFilter> QueryFilter for Not<F> {
1805    fn matches(world: &World, entity: Entity) -> bool {
1806        world.contains(entity) && !F::matches(world, entity)
1807    }
1808}
1809impl sealed::QueryFilter for () {
1810    #[inline]
1811    fn word_mask(_: &World, _: usize) -> u64 {
1812        u64::MAX
1813    }
1814}
1815impl QueryFilter for () {
1816    fn matches(world: &World, entity: Entity) -> bool {
1817        world.contains(entity)
1818    }
1819}
1820impl sealed::QueryFilter for All<()> {
1821    #[inline]
1822    fn word_mask(_: &World, _: usize) -> u64 {
1823        u64::MAX
1824    }
1825}
1826impl QueryFilter for All<()> {
1827    fn matches(world: &World, entity: Entity) -> bool {
1828        world.contains(entity)
1829    }
1830}
1831impl sealed::QueryFilter for Any<()> {
1832    #[inline]
1833    fn word_mask(_: &World, _: usize) -> u64 {
1834        0
1835    }
1836}
1837impl QueryFilter for Any<()> {
1838    fn matches(_: &World, _: Entity) -> bool {
1839        false
1840    }
1841}
1842
1843macro_rules! filter_tuple {
1844    ($($name:ident),+) => {
1845        impl<$($name: QueryFilter),+> sealed::QueryFilter for ($($name,)+) {
1846            #[inline]
1847            fn word_mask(world: &World, word_idx: usize) -> u64 {
1848                $($name::word_mask(world, word_idx))&+
1849            }
1850        }
1851        impl<$($name: QueryFilter),+> QueryFilter for ($($name,)+) {
1852            fn matches(world: &World, entity: Entity) -> bool {
1853                $($name::matches(world, entity))&&+
1854            }
1855        }
1856        impl<$($name: QueryFilter),+> sealed::QueryFilter for All<($($name,)+)> {
1857            #[inline]
1858            fn word_mask(world: &World, word_idx: usize) -> u64 {
1859                $($name::word_mask(world, word_idx))&+
1860            }
1861        }
1862        impl<$($name: QueryFilter),+> QueryFilter for All<($($name,)+)> {
1863            fn matches(world: &World, entity: Entity) -> bool {
1864                <($($name,)+) as QueryFilter>::matches(world, entity)
1865            }
1866        }
1867        impl<$($name: QueryFilter),+> sealed::QueryFilter for Any<($($name,)+)> {
1868            #[inline]
1869            fn word_mask(world: &World, word_idx: usize) -> u64 {
1870                $($name::word_mask(world, word_idx))|+
1871            }
1872        }
1873        impl<$($name: QueryFilter),+> QueryFilter for Any<($($name,)+)> {
1874            fn matches(world: &World, entity: Entity) -> bool {
1875                $($name::matches(world, entity))||+
1876            }
1877        }
1878    }
1879}
1880filter_tuple!(A);
1881filter_tuple!(A, B);
1882filter_tuple!(A, B, C);
1883filter_tuple!(A, B, C, D);
1884
1885pub struct QueryBorrow<'world, Q: Query, F: QueryFilter = ()> {
1886    world: &'world World,
1887    marker: PhantomData<fn() -> (Q, F)>,
1888}
1889
1890impl<'world, Q: Query, F: QueryFilter> QueryBorrow<'world, Q, F> {
1891    pub fn iter(&self) -> QueryIter<'world, Q, F> {
1892        QueryIter {
1893            inner: self.try_iter(),
1894        }
1895    }
1896    /// Visits all matching entities, reporting borrow conflicts without skipping silently.
1897    /// A conflict releases any partial tuple borrows and does not stop later entities.
1898    pub fn try_iter(&self) -> TryQueryIter<'world, Q, F> {
1899        TryQueryIter {
1900            world: self.world,
1901            q_state: Q::prepare(self.world),
1902            cursor: 0,
1903            word_idx: 0,
1904            current_word: 0,
1905            marker: PhantomData,
1906        }
1907    }
1908}
1909impl<'world, Q: Query, F: QueryFilter> IntoIterator for &mut QueryBorrow<'world, Q, F> {
1910    type Item = Q::Item<'world>;
1911    type IntoIter = QueryIter<'world, Q, F>;
1912    fn into_iter(self) -> Self::IntoIter {
1913        self.iter()
1914    }
1915}
1916impl<'world, Q: Query, F: QueryFilter> IntoIterator for &QueryBorrow<'world, Q, F> {
1917    type Item = Q::Item<'world>;
1918    type IntoIter = QueryIter<'world, Q, F>;
1919    fn into_iter(self) -> Self::IntoIter {
1920        self.iter()
1921    }
1922}
1923impl<'world, Q: Query, F: QueryFilter> IntoIterator for QueryBorrow<'world, Q, F> {
1924    type Item = Q::Item<'world>;
1925    type IntoIter = QueryIter<'world, Q, F>;
1926    fn into_iter(self) -> Self::IntoIter {
1927        self.iter()
1928    }
1929}
1930
1931pub struct TryQueryIter<'world, Q: Query, F: QueryFilter = ()> {
1932    world: &'world World,
1933    q_state: Q::State<'world>,
1934    cursor: usize,
1935    word_idx: usize,
1936    current_word: u64,
1937    marker: PhantomData<fn() -> F>,
1938}
1939impl<'world, Q: Query, F: QueryFilter> Iterator for TryQueryIter<'world, Q, F> {
1940    type Item = Result<Q::Item<'world>, Error>;
1941    #[inline]
1942    fn next(&mut self) -> Option<Self::Item> {
1943        let word_len = self.world.alive.len();
1944        while self.current_word == 0 {
1945            if self.word_idx >= word_len {
1946                self.cursor = self.world.slots.len();
1947                return None;
1948            }
1949            let w = self.word_idx;
1950            self.word_idx += 1;
1951            let alive = self.world.alive[w];
1952            if alive != 0 {
1953                let qmask = alive & Q::word_mask(&self.q_state, w);
1954                if qmask != 0 {
1955                    let mask = qmask & F::word_mask(self.world, w);
1956                    if mask != 0 {
1957                        self.current_word = mask;
1958                        break;
1959                    }
1960                }
1961            }
1962        }
1963        let bit = self.current_word.trailing_zeros() as usize;
1964        self.current_word &= self.current_word - 1;
1965        let index = ((self.word_idx - 1) << 6) | bit;
1966        self.cursor = index + 1;
1967        Some(Q::fetch_prepared_item(&self.q_state, self.world, index))
1968    }
1969    #[inline]
1970    fn fold<B, Fold>(self, mut accum: B, mut f: Fold) -> B
1971    where
1972        Fold: FnMut(B, Self::Item) -> B,
1973    {
1974        let world = self.world;
1975        let q_state = &self.q_state;
1976        if self.current_word != 0 {
1977            let base = (self.word_idx - 1) << 6;
1978            let mut mask = self.current_word;
1979            while mask != 0 {
1980                let bit = mask.trailing_zeros() as usize;
1981                mask &= mask - 1;
1982                accum = f(accum, Q::fetch_prepared_item(q_state, world, base | bit));
1983            }
1984        }
1985        let alive_words = &world.alive;
1986        for (w, &alive) in alive_words.iter().enumerate().skip(self.word_idx) {
1987            if alive == 0 {
1988                continue;
1989            }
1990            let qmask = alive & Q::word_mask(q_state, w);
1991            if qmask == 0 {
1992                continue;
1993            }
1994            let mut mask = qmask & F::word_mask(world, w);
1995            let base = w << 6;
1996            while mask != 0 {
1997                let bit = mask.trailing_zeros() as usize;
1998                mask &= mask - 1;
1999                accum = f(accum, Q::fetch_prepared_item(q_state, world, base | bit));
2000            }
2001        }
2002        accum
2003    }
2004    fn size_hint(&self) -> (usize, Option<usize>) {
2005        (0, Some(self.world.slots.len().saturating_sub(self.cursor)))
2006    }
2007}
2008impl<Q: Query, F: QueryFilter> std::iter::FusedIterator for TryQueryIter<'_, Q, F> {}
2009
2010pub struct QueryIter<'world, Q: Query, F: QueryFilter = ()> {
2011    inner: TryQueryIter<'world, Q, F>,
2012}
2013impl<'world, Q: Query, F: QueryFilter> Iterator for QueryIter<'world, Q, F> {
2014    type Item = Q::Item<'world>;
2015    #[inline]
2016    fn next(&mut self) -> Option<Self::Item> {
2017        self.inner
2018            .next()
2019            .map(|item| item.unwrap_or_else(|error| panic!("{error}")))
2020    }
2021    #[inline]
2022    fn fold<B, Fold>(self, accum: B, mut f: Fold) -> B
2023    where
2024        Fold: FnMut(B, Self::Item) -> B,
2025    {
2026        self.inner.fold(accum, |acc, item| {
2027            f(acc, item.unwrap_or_else(|error| panic!("{error}")))
2028        })
2029    }
2030    fn size_hint(&self) -> (usize, Option<usize>) {
2031        self.inner.size_hint()
2032    }
2033}
2034impl<Q: Query, F: QueryFilter> std::iter::FusedIterator for QueryIter<'_, Q, F> {}
2035
2036#[cfg(test)]
2037mod journey400_212 {
2038    use super::*;
2039
2040    #[derive(Debug, PartialEq)]
2041    struct Part<const N: usize>(i32);
2042
2043    type Eight = (
2044        Part<0>,
2045        Part<1>,
2046        Part<2>,
2047        Part<3>,
2048        Part<4>,
2049        Part<5>,
2050        Part<6>,
2051        Part<7>,
2052    );
2053    type MutableEight = (
2054        &'static mut Part<0>,
2055        &'static mut Part<1>,
2056        &'static mut Part<2>,
2057        &'static mut Part<3>,
2058        &'static mut Part<4>,
2059        &'static mut Part<5>,
2060        &'static mut Part<6>,
2061        &'static mut Part<7>,
2062    );
2063
2064    fn eight(value: i32) -> Eight {
2065        (
2066            Part(value),
2067            Part(value),
2068            Part(value),
2069            Part(value),
2070            Part(value),
2071            Part(value),
2072            Part(value),
2073            Part(value),
2074        )
2075    }
2076
2077    #[test]
2078    fn stack_metadata_and_existing_vec_api_agree_for_every_bundle_width() {
2079        fn check<B: Bundle>(expected: &[(TypeId, &'static str)]) {
2080            let inline = B::component_types_inline();
2081            assert_eq!(
2082                inline.iter().flatten().copied().collect::<Vec<_>>(),
2083                expected
2084            );
2085            assert!(inline[expected.len()..].iter().all(Option::is_none));
2086            // The old hidden public API still appends and preserves existing entries.
2087            let prefix = (TypeId::of::<()>(), type_name::<()>());
2088            let mut metadata = vec![prefix];
2089            B::component_types(&mut metadata);
2090            assert_eq!(metadata[0], prefix);
2091            assert_eq!(&metadata[1..], expected);
2092            assert_eq!(validate_bundle::<B>(), Ok(()));
2093        }
2094        check::<()>(&[]);
2095        macro_rules! check {
2096            ($($ty:ty),+) => {
2097                check::<($($ty,)+)>(&[$((TypeId::of::<$ty>(), type_name::<$ty>()),)+]);
2098            };
2099        }
2100        check!(u8);
2101        check!(u8, u16);
2102        check!(u8, u16, u32);
2103        check!(u8, u16, u32, u64);
2104        check!(u8, u16, u32, u64, i8);
2105        check!(u8, u16, u32, u64, i8, i16);
2106        check!(u8, u16, u32, u64, i8, i16, i32);
2107        check!(u8, u16, u32, u64, i8, i16, i32, i64);
2108    }
2109
2110    #[test]
2111    fn new_tuple_widths_support_spawn_insert_query_and_get_many() {
2112        macro_rules! check {
2113            ($($ty:ty => $value:expr),+) => {{
2114                let mut world = World::new();
2115                let entity = world.try_spawn(($($value,)+)).unwrap();
2116                assert_eq!(world.query::<($(&$ty,)+)>().iter().count(), 1);
2117                assert_eq!(world.get_many::<($(&$ty,)+), 1>([entity]).unwrap().len(), 1);
2118                world.insert(entity, ($($value,)+)).unwrap();
2119                $(assert_eq!(*world.get::<&$ty>(entity).unwrap(), $value);)+
2120                world.despawn(entity).unwrap();
2121                assert_eq!(world.query::<($(&$ty,)+)>().iter().count(), 0);
2122            }};
2123        }
2124        check!(u8 => 1_u8, u16 => 2_u16, u32 => 3_u32, u64 => 4_u64, i8 => 5_i8);
2125        check!(u8 => 1_u8, u16 => 2_u16, u32 => 3_u32, u64 => 4_u64, i8 => 5_i8, i16 => 6_i16);
2126        check!(u8 => 1_u8, u16 => 2_u16, u32 => 3_u32, u64 => 4_u64, i8 => 5_i8, i16 => 6_i16, i32 => 7_i32);
2127        check!(u8 => 1_u8, u16 => 2_u16, u32 => 3_u32, u64 => 4_u64, i8 => 5_i8, i16 => 6_i16, i32 => 7_i32, i64 => 8_i64);
2128    }
2129
2130    #[test]
2131    fn late_duplicate_bundles_prevalidate_without_writes_or_slot_changes() {
2132        fn rejects<B: Bundle>(world: &mut World, entity: Entity, bundle: B) {
2133            let slots = world.slots.len();
2134            let free = world.free.clone();
2135            let storages = world.storages.len();
2136            let len = world.len();
2137            assert_eq!(
2138                world.try_spawn(bundle),
2139                Err(Error::DuplicateComponent(type_name::<Part<0>>()))
2140            );
2141            assert_eq!(world.slots.len(), slots);
2142            assert_eq!(world.free, free);
2143            assert_eq!(world.storages.len(), storages);
2144            assert_eq!(world.len(), len);
2145            assert_eq!(world.get::<&Part<0>>(entity).unwrap().0, 10);
2146        }
2147        let mut world = World::new();
2148        let entity = world.spawn((Part::<0>(10),));
2149        let freed = world.spawn(());
2150        world.despawn(freed).unwrap();
2151        rejects(
2152            &mut world,
2153            entity,
2154            (
2155                Part::<0>(1),
2156                Part::<1>(1),
2157                Part::<2>(1),
2158                Part::<3>(1),
2159                Part::<0>(2),
2160            ),
2161        );
2162        rejects(
2163            &mut world,
2164            entity,
2165            (
2166                Part::<0>(1),
2167                Part::<1>(1),
2168                Part::<2>(1),
2169                Part::<3>(1),
2170                Part::<4>(1),
2171                Part::<0>(2),
2172            ),
2173        );
2174        rejects(
2175            &mut world,
2176            entity,
2177            (
2178                Part::<0>(1),
2179                Part::<1>(1),
2180                Part::<2>(1),
2181                Part::<3>(1),
2182                Part::<4>(1),
2183                Part::<5>(1),
2184                Part::<0>(2),
2185            ),
2186        );
2187        let duplicate = || {
2188            (
2189                Part::<0>(1),
2190                Part::<1>(1),
2191                Part::<2>(1),
2192                Part::<3>(1),
2193                Part::<4>(1),
2194                Part::<5>(1),
2195                Part::<6>(1),
2196                Part::<0>(2),
2197            )
2198        };
2199        rejects(&mut world, entity, duplicate());
2200        assert_eq!(
2201            world.insert(entity, duplicate()),
2202            Err(Error::DuplicateComponent(type_name::<Part<0>>()))
2203        );
2204        assert_eq!(world.get::<&Part<0>>(entity).unwrap().0, 10);
2205        assert!(!world.has::<Part<1>>(entity));
2206        assert_eq!(world.storages.len(), 1);
2207        assert_eq!(
2208            world.insert(freed, duplicate()),
2209            Err(Error::NoSuchEntity(freed))
2210        );
2211        let panic =
2212            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| world.spawn(duplicate())));
2213        assert!(panic.is_err());
2214        let next = world.spawn(());
2215        assert_eq!(next.id(), freed.id());
2216        assert_eq!(next.generation(), freed.generation() + 1);
2217        assert_eq!(
2218            validate_bundle::<(u8, u16, u32, u64, u8, i16, i32, u16)>(),
2219            Err(Error::DuplicateComponent(type_name::<u8>()))
2220        );
2221    }
2222
2223    #[test]
2224    fn late_query_aliases_validate_on_empty_worlds_filters_and_batches() {
2225        fn rejects<Q: Query>() {
2226            let world = World::new();
2227            let error = Error::ConflictingQuery(type_name::<Part<0>>());
2228            assert_eq!(world.try_query::<Q>().err(), Some(error.clone()));
2229            assert_eq!(
2230                world.try_query_filtered::<Q, Any<()>>().err(),
2231                Some(error.clone())
2232            );
2233            assert_eq!(world.get_many::<Q, 0>([]).err(), Some(error.clone()));
2234            assert_eq!(
2235                world.get_many::<Q, 1>([Entity::from_bits(u64::MAX)]).err(),
2236                Some(error)
2237            );
2238        }
2239        rejects::<(&mut Part<0>, Entity, Entity, Entity, &Part<0>)>();
2240        rejects::<(
2241            &Part<0>,
2242            Entity,
2243            Entity,
2244            Entity,
2245            Entity,
2246            Option<&mut Part<0>>,
2247        )>();
2248        rejects::<(
2249            Option<&mut Part<0>>,
2250            Entity,
2251            Entity,
2252            Entity,
2253            Entity,
2254            Entity,
2255            Option<&Part<0>>,
2256        )>();
2257        rejects::<(
2258            Entity,
2259            Entity,
2260            Entity,
2261            Entity,
2262            Entity,
2263            Entity,
2264            &mut Part<0>,
2265            Option<&mut Part<0>>,
2266        )>();
2267        assert_eq!(
2268            <(
2269                Entity,
2270                &mut Part<1>,
2271                Entity,
2272                Entity,
2273                &Part<0>,
2274                Entity,
2275                &mut Part<1>,
2276                &mut Part<0>
2277            ) as Query>::validate(),
2278            Err(Error::ConflictingQuery(type_name::<Part<1>>()))
2279        );
2280    }
2281
2282    #[test]
2283    fn eight_shared_or_identity_entries_remain_valid() {
2284        let mut world = World::new();
2285        let entity = world.spawn((Part::<0>(3),));
2286        let [(id, a, b, c, d, e, f, g)] = world
2287            .get_many::<(
2288                Entity,
2289                &Part<0>,
2290                Option<&Part<0>>,
2291                &Part<0>,
2292                &Part<0>,
2293                &Part<0>,
2294                &Part<0>,
2295                &Part<0>,
2296            ), 1>([entity])
2297            .unwrap();
2298        assert_eq!(id, entity);
2299        assert_eq!(
2300            (a.0, b.unwrap().0, c.0, d.0, e.0, f.0, g.0),
2301            (3, 3, 3, 3, 3, 3, 3)
2302        );
2303        assert_eq!(
2304            world
2305                .query::<(
2306                    Entity,
2307                    Entity,
2308                    Entity,
2309                    Entity,
2310                    Entity,
2311                    Entity,
2312                    Entity,
2313                    Entity
2314                )>()
2315                .iter()
2316                .next()
2317                .unwrap(),
2318            (
2319                entity, entity, entity, entity, entity, entity, entity, entity
2320            )
2321        );
2322    }
2323
2324    #[test]
2325    fn eighth_borrow_failure_releases_seven_guards_and_iteration_continues() {
2326        let mut world = World::new();
2327        let first = world.spawn(eight(1));
2328        let second = world.spawn(eight(2));
2329        let held = world.get_mut::<Part<7>>(first).unwrap();
2330        let mut rows = world.query::<MutableEight>().try_iter();
2331        assert!(
2332            matches!(rows.next().unwrap(), Err(Error::BorrowConflict(name)) if name == type_name::<Part<7>>())
2333        );
2334        macro_rules! released {
2335            ($($index:literal),+) => { $(assert!(world.get_mut::<Part<$index>>(first).is_ok());)+ };
2336        }
2337        released!(0, 1, 2, 3, 4, 5, 6);
2338        assert_eq!(held.0, 1);
2339        let (mut a, b, c, d, e, f, g, h) = rows.next().unwrap().unwrap();
2340        a.0 += 10;
2341        assert_eq!((b.0, c.0, d.0, e.0, f.0, g.0, h.0), (2, 2, 2, 2, 2, 2, 2));
2342        assert!(rows.next().is_none());
2343        assert!(rows.next().is_none());
2344        drop((a, b, c, d, e, f, g, h, held));
2345        assert_eq!(world.get::<&Part<0>>(second).unwrap().0, 12);
2346        assert!(world.get_many::<MutableEight, 2>([first, second]).is_ok());
2347        let held = world.get_mut::<Part<7>>(first).unwrap();
2348        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2349            world.query::<MutableEight>().iter().next();
2350        }));
2351        assert!(panic.is_err());
2352        released!(0, 1, 2, 3, 4, 5, 6);
2353        drop(held);
2354        assert!(world.get_many::<MutableEight, 1>([first]).is_ok());
2355    }
2356
2357    #[test]
2358    fn wide_get_many_cleans_completed_and_partial_rows_on_late_errors() {
2359        let mut world = World::new();
2360        let first = world.spawn(eight(1));
2361        let last = world.spawn(eight(2));
2362        world.remove::<Part<7>>(last).unwrap();
2363        assert!(matches!(world.get_many::<MutableEight, 2>([first, last]),
2364            Err(Error::MissingComponent(name)) if name == type_name::<Part<7>>()));
2365        assert!(world.get_many::<MutableEight, 1>([first]).is_ok());
2366        assert!(world.get_mut::<Part<0>>(last).is_ok());
2367        assert!(world.get_mut::<Part<6>>(last).is_ok());
2368        world.insert(last, (Part::<7>(2),)).unwrap();
2369        let held = world.get::<&Part<7>>(last).unwrap();
2370        assert!(matches!(world.get_many::<MutableEight, 2>([first, last]),
2371            Err(Error::BorrowConflict(name)) if name == type_name::<Part<7>>()));
2372        assert!(world.get_many::<MutableEight, 1>([first]).is_ok());
2373        assert!(world.get_mut::<Part<6>>(last).is_ok());
2374        assert_eq!(held.0, 2);
2375        drop(held);
2376        assert!(world.get_many::<MutableEight, 2>([last, first]).is_ok());
2377        assert!(matches!(
2378            world.get_many::<MutableEight, 2>([first, first]),
2379            Err(Error::BorrowConflict(_))
2380        ));
2381        assert!(world.get_many::<MutableEight, 1>([first]).is_ok());
2382        assert_eq!(world.get::<&Part<0>>(first).unwrap().0, 1);
2383    }
2384
2385    #[test]
2386    fn wide_optional_filtered_queries_prefilter_and_never_borrow_markers() {
2387        type Fetch = (
2388            Entity,
2389            &'static mut Part<0>,
2390            Option<&'static Part<1>>,
2391            &'static Part<2>,
2392            &'static Part<3>,
2393            &'static Part<4>,
2394            &'static Part<5>,
2395            Option<&'static mut Part<6>>,
2396        );
2397        let mut world = World::new();
2398        let excluded = world.spawn(eight(1));
2399        let missing_required = world.spawn(eight(2));
2400        world.remove::<Part<5>>(missing_required).unwrap();
2401        let full = world.spawn(eight(3));
2402        let partial = world.spawn(eight(4));
2403        world.remove::<Part<1>>(partial).unwrap();
2404        world.remove::<Part<6>>(partial).unwrap();
2405        world.insert(excluded, (false,)).unwrap();
2406        let excluded_guard = world.get_mut::<Part<0>>(excluded).unwrap();
2407        let missing_guard = world.get_mut::<Part<0>>(missing_required).unwrap();
2408        let marker = world.get_mut::<Part<7>>(full).unwrap();
2409        let mut visited = Vec::new();
2410        for row in world
2411            .query_filtered::<Fetch, (With<Part<7>>, Without<bool>)>()
2412            .try_iter()
2413        {
2414            let (id, mut a, b, c, d, e, f, g) = row.unwrap();
2415            assert_eq!((c.0, d.0, e.0, f.0), (a.0, a.0, a.0, a.0));
2416            assert_eq!(b.is_some(), id == full);
2417            assert_eq!(g.is_some(), id == full);
2418            a.0 += 10;
2419            if let Some(mut g) = g {
2420                g.0 += 20;
2421            }
2422            visited.push(id);
2423        }
2424        assert_eq!(visited, [full, partial]);
2425        assert_eq!(marker.0, 3);
2426        drop((marker, excluded_guard, missing_guard));
2427        assert_eq!(world.get::<&Part<0>>(full).unwrap().0, 13);
2428        assert_eq!(world.get::<&Part<6>>(full).unwrap().0, 23);
2429        assert_eq!(world.get::<&Part<0>>(partial).unwrap().0, 14);
2430        // Optional eighth fetches still report a present component's borrow failure.
2431        let held = world.get_mut::<Part<6>>(full).unwrap();
2432        let mut rows = world.query_filtered::<Fetch, Without<bool>>().try_iter();
2433        assert!(
2434            matches!(rows.next().unwrap(), Err(Error::BorrowConflict(name)) if name == type_name::<Part<6>>())
2435        );
2436        assert!(world.get_mut::<Part<0>>(full).is_ok());
2437        assert_eq!(rows.next().unwrap().unwrap().0, partial);
2438        assert!(rows.next().is_none());
2439        drop(held);
2440    }
2441
2442    #[test]
2443    fn wide_bundles_reuse_warmed_buffers_and_reset_through_despawn() {
2444        let mut world = World::new();
2445        let initial = world.spawn(eight(0));
2446        world.despawn(initial).unwrap(); // Warm the free-list and all eight storages.
2447        let capacities = (
2448            world.slots.capacity(),
2449            world.free.capacity(),
2450            world.storages.capacity(),
2451        );
2452        fn component_capacities(world: &World) -> [usize; 8] {
2453            macro_rules! capacities {
2454                ($($index:literal),+) => {
2455                    [$(world.storages[&TypeId::of::<Part<$index>>()]
2456                        .as_any().downcast_ref::<Storage<Part<$index>>>()
2457                        .unwrap().slots.capacity(),)+]
2458                };
2459            }
2460            capacities!(0, 1, 2, 3, 4, 5, 6, 7)
2461        }
2462        let storage_capacities = component_capacities(&world);
2463        let mut old = initial;
2464        for value in 1..=64 {
2465            let entity = world.try_spawn(eight(value)).unwrap();
2466            assert_eq!(entity.id(), initial.id());
2467            assert!(!world.contains(old));
2468            assert_eq!(
2469                world.get_many::<MutableEight, 1>([old]).err(),
2470                Some(Error::NoSuchEntity(old))
2471            );
2472            assert_eq!(world.get::<&Part<7>>(entity).unwrap().0, value);
2473            world.insert(entity, ()).unwrap();
2474            world.despawn(entity).unwrap();
2475            assert!(world.is_empty());
2476            assert_eq!(world.query::<MutableEight>().iter().count(), 0);
2477            old = entity;
2478        }
2479        assert_eq!(
2480            (
2481                world.slots.capacity(),
2482                world.free.capacity(),
2483                world.storages.capacity()
2484            ),
2485            capacities
2486        );
2487        assert_eq!(world.storages.len(), 8);
2488        assert_eq!(component_capacities(&world), storage_capacities);
2489        let empty = world.try_spawn(()).unwrap();
2490        assert_eq!(empty.id(), initial.id());
2491        assert!(world.get::<Option<&Part<0>>>(empty).unwrap().is_none());
2492        assert!(world.get::<Option<&Part<7>>>(empty).unwrap().is_none());
2493        assert_eq!(world.query::<Entity>().iter().collect::<Vec<_>>(), [empty]);
2494    }
2495}
2496
2497#[cfg(test)]
2498mod tests {
2499    use super::*;
2500    use std::cell::Cell;
2501    use std::rc::Rc;
2502
2503    #[derive(Debug, PartialEq)]
2504    struct Position(f32, f32);
2505    #[derive(Debug, PartialEq)]
2506    struct Velocity(f32, f32);
2507    #[derive(Debug, PartialEq)]
2508    struct Health(i32);
2509
2510    fn filtered_ids<F: QueryFilter>(world: &World) -> Vec<Entity> {
2511        world.query_filtered::<Entity, F>().iter().collect()
2512    }
2513
2514    #[test]
2515    fn filtered_logic_matches_all_component_presence_combinations() {
2516        let mut world = World::new();
2517        let entities: Vec<_> = (0..16)
2518            .map(|mask| {
2519                let entity = world.spawn(());
2520                if mask & 1 != 0 {
2521                    world.insert(entity, (Health(1),)).unwrap();
2522                }
2523                if mask & 2 != 0 {
2524                    world.insert(entity, (Position(0.0, 0.0),)).unwrap();
2525                }
2526                if mask & 4 != 0 {
2527                    world.insert(entity, (Velocity(0.0, 0.0),)).unwrap();
2528                }
2529                if mask & 8 != 0 {
2530                    world.insert(entity, (true,)).unwrap();
2531                }
2532                entity
2533            })
2534            .collect();
2535        macro_rules! check {
2536            ($filter:ty, $predicate:expr) => {
2537                assert_eq!(
2538                    filtered_ids::<$filter>(&world),
2539                    entities
2540                        .iter()
2541                        .enumerate()
2542                        .filter_map(|(mask, &entity)| { ($predicate)(mask).then_some(entity) })
2543                        .collect::<Vec<_>>()
2544                );
2545            };
2546        }
2547        check!(With<Health>, |m: usize| m & 1 != 0);
2548        check!(Without<Health>, |m: usize| m & 1 == 0);
2549        check!((With<Health>,), |m: usize| m & 1 != 0);
2550        check!((With<Health>, With<Position>), |m: usize| m & 3 == 3);
2551        check!(
2552            (With<Health>, With<Position>, With<Velocity>),
2553            |m: usize| m & 7 == 7
2554        );
2555        check!(
2556            (With<Health>, With<Position>, With<Velocity>, With<bool>),
2557            |m| m == 15
2558        );
2559        check!(All<(With<Health>,)>, |m: usize| m & 1 != 0);
2560        check!(All<(With<Health>, With<Position>)>, |m: usize| m & 3 == 3);
2561        check!(
2562            All<(With<Health>, With<Position>, With<Velocity>)>,
2563            |m: usize| m & 7 == 7
2564        );
2565        check!(
2566            All<(With<Health>, With<Position>, With<Velocity>, With<bool>)>,
2567            |m| m == 15
2568        );
2569        check!(Any<(With<Health>,)>, |m: usize| m & 1 != 0);
2570        check!(Any<(With<Health>, With<Position>)>, |m: usize| m & 3 != 0);
2571        check!(
2572            Any<(With<Health>, With<Position>, With<Velocity>)>,
2573            |m: usize| m & 7 != 0
2574        );
2575        check!(
2576            Any<(With<Health>, With<Position>, With<Velocity>, With<bool>)>,
2577            |m| m != 0
2578        );
2579        type Nested = All<(
2580            Any<(With<Health>, With<Position>)>,
2581            Not<Any<(With<Velocity>, With<bool>)>>,
2582        )>;
2583        check!(Nested, |m: usize| m & 3 != 0 && m & 12 == 0);
2584        check!(Not<Nested>, |m: usize| m & 3 == 0 || m & 12 != 0);
2585        check!(Not<Not<With<Health>>>, |m: usize| m & 1 != 0);
2586        check!((With<Health>, Without<Health>), |_| false);
2587    }
2588
2589    #[test]
2590    fn filtered_empty_groups_have_logical_identities() {
2591        let mut world = World::new();
2592        assert!(filtered_ids::<Not<Any<()>>>(&world).is_empty());
2593        let empty = world.spawn(());
2594        let present = world.spawn((Health(1),));
2595        let dead = world.spawn(());
2596        world.despawn(dead).unwrap();
2597        for ids in [
2598            filtered_ids::<()>(&world),
2599            filtered_ids::<All<()>>(&world),
2600            filtered_ids::<Not<Any<()>>>(&world),
2601            filtered_ids::<Any<(With<Health>, Without<Health>)>>(&world),
2602        ] {
2603            assert_eq!(ids, [empty, present]);
2604        }
2605        assert!(filtered_ids::<Any<()>>(&world).is_empty());
2606        assert!(filtered_ids::<Not<()>>(&world).is_empty());
2607        assert!(filtered_ids::<Not<All<()>>>(&world).is_empty());
2608        assert_eq!(filtered_ids::<All<((), With<Health>)>>(&world), [present]);
2609        assert_eq!(
2610            filtered_ids::<Any<(Any<()>, Without<Health>)>>(&world),
2611            [empty]
2612        );
2613    }
2614
2615    #[test]
2616    fn filtered_presence_never_borrows_marker_values() {
2617        struct Marker;
2618        let mut world = World::new();
2619        let marked = world.spawn((Marker, Health(10)));
2620        let unmarked = world.spawn((Health(20),));
2621        let marker = world.get_mut::<Marker>(marked).unwrap();
2622        assert_eq!(filtered_ids::<With<Marker>>(&world), [marked]);
2623        assert_eq!(filtered_ids::<Without<Marker>>(&world), [unmarked]);
2624        assert_eq!(filtered_ids::<Not<Without<Marker>>>(&world), [marked]);
2625        let mut health = world
2626            .query_filtered::<&mut Health, With<Marker>>()
2627            .iter()
2628            .next()
2629            .unwrap();
2630        health.0 += 1;
2631        // Filtering never leaves a marker guard behind, even while a fetched guard lives.
2632        drop(marker);
2633        assert!(world.get_mut::<Marker>(marked).is_ok());
2634        drop(health);
2635        // The very same type may be a mutable fetch and repeated presence clause.
2636        for _marker in world.query_filtered::<&mut Marker, (With<Marker>, With<Marker>)>() {}
2637        assert_eq!(world.get::<&Health>(marked).unwrap().0, 11);
2638    }
2639
2640    #[test]
2641    fn filtered_required_optional_accesses_and_exclusions_match_before_fetch() {
2642        let mut world = World::new();
2643        let excluded = world.spawn((Health(10), Position(1.0, 2.0), true));
2644        let missing_required = world.spawn((Health(20),));
2645        let included = world.spawn((Position(3.0, 4.0),));
2646        let excluded_guard = world.get_mut::<Health>(excluded).unwrap();
2647        let missing_guard = world.get_mut::<Health>(missing_required).unwrap();
2648        let mut rows = world
2649            .query_filtered::<(
2650                Entity,
2651                Option<&mut Health>,
2652                &mut Position,
2653                Option<&Velocity>,
2654            ), Without<bool>>()
2655            .try_iter();
2656        let (id, health, mut position, velocity) = rows.next().unwrap().unwrap();
2657        assert_eq!(id, included);
2658        assert!(health.is_none() && velocity.is_none());
2659        position.0 += 5.0;
2660        assert!(rows.next().is_none());
2661        drop((excluded_guard, missing_guard, position));
2662        assert_eq!(world.get::<&Position>(included).unwrap().0, 8.0);
2663        // Optional-only fetches still respect structural exclusion.
2664        assert_eq!(
2665            world
2666                .query_filtered::<Option<&Velocity>, With<bool>>()
2667                .iter()
2668                .count(),
2669            1
2670        );
2671    }
2672
2673    #[test]
2674    fn filtered_alias_validation_is_independent_of_filter_matches() {
2675        fn rejects<F: QueryFilter>(world: &World) {
2676            for result in [
2677                world
2678                    .try_query_filtered::<(&mut Health, Option<&Health>), F>()
2679                    .map(|_| ()),
2680                world
2681                    .try_query_filtered::<(Option<&mut Health>, &mut Health), F>()
2682                    .map(|_| ()),
2683                world
2684                    .try_query_filtered::<(Option<&mut Health>, Option<&mut Health>), F>()
2685                    .map(|_| ()),
2686            ] {
2687                assert_eq!(result, Err(Error::ConflictingQuery(type_name::<Health>())));
2688            }
2689        }
2690        let mut world = World::new();
2691        rejects::<Any<()>>(&world);
2692        rejects::<(With<Health>, Without<Health>)>(&world);
2693        world.spawn((Health(1),));
2694        rejects::<With<Health>>(&world);
2695        rejects::<Any<()>>(&world);
2696        let (a, b) = world
2697            .query_filtered::<(&Health, Option<&Health>), With<Health>>()
2698            .iter()
2699            .next()
2700            .unwrap();
2701        assert_eq!(a.0, b.unwrap().0);
2702        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2703            world.query_filtered::<(&mut Health, &Health), Any<()>>();
2704        }));
2705        assert!(panic.is_err());
2706    }
2707
2708    #[test]
2709    fn filtered_fallible_iteration_releases_partial_guards_and_continues() {
2710        let mut world = World::new();
2711        let first = world.spawn((Health(1), Position(1.0, 2.0), true));
2712        let excluded = world.spawn((Health(2), Position(3.0, 4.0)));
2713        let last = world.spawn((Health(3), true));
2714        let marker = world.get_mut::<bool>(first).unwrap();
2715        let conflict = world.get_mut::<Position>(first).unwrap();
2716        let (mut health, position) = {
2717            let mut rows = world
2718                .query_filtered::<(&mut Health, Option<&Position>), With<bool>>()
2719                .try_iter();
2720            assert!(matches!(rows.next().unwrap(),
2721                Err(Error::BorrowConflict(name)) if name == type_name::<Position>()));
2722            assert!(world.get_mut::<Health>(first).is_ok());
2723            let last_row = rows.next().unwrap().unwrap();
2724            assert!(rows.next().is_none());
2725            assert!(rows.next().is_none());
2726            assert_eq!(rows.size_hint(), (0, Some(0)));
2727            last_row
2728        };
2729        // Result guards retain the world lifetime after iterator destruction.
2730        assert!(position.is_none());
2731        health.0 += 10;
2732        assert!(matches!(
2733            world.get::<&Health>(last),
2734            Err(Error::BorrowConflict(_))
2735        ));
2736        assert_eq!(world.get::<&Health>(excluded).unwrap().0, 2);
2737        drop((health, marker, conflict));
2738        assert_eq!(
2739            world
2740                .query_filtered::<(&mut Health, Option<&Position>), With<bool>>()
2741                .try_iter()
2742                .filter(Result::is_ok)
2743                .count(),
2744            2
2745        );
2746    }
2747
2748    #[test]
2749    fn filtered_fetch_of_a_marker_still_reports_borrow_conflicts() {
2750        let mut world = World::new();
2751        let present = world.spawn((Health(1),));
2752        let absent = world.spawn(());
2753        let held = world.get_mut::<Health>(present).unwrap();
2754        assert_eq!(filtered_ids::<With<Health>>(&world), [present]);
2755        let mut rows = world
2756            .query_filtered::<Option<&Health>, With<Health>>()
2757            .try_iter();
2758        assert!(matches!(
2759            rows.next().unwrap(),
2760            Err(Error::BorrowConflict(_))
2761        ));
2762        assert!(rows.next().is_none());
2763        assert_eq!(filtered_ids::<Without<Health>>(&world), [absent]);
2764        drop(held);
2765        assert!(
2766            world
2767                .query_filtered::<Option<&Health>, With<Health>>()
2768                .try_iter()
2769                .next()
2770                .unwrap()
2771                .unwrap()
2772                .is_some()
2773        );
2774    }
2775
2776    #[test]
2777    fn filtered_panicking_iteration_releases_partial_guards() {
2778        let mut world = World::new();
2779        let entity = world.spawn((Health(1), Position(1.0, 2.0), true));
2780        let held = world.get_mut::<Position>(entity).unwrap();
2781        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2782            world
2783                .query_filtered::<(&mut Health, Option<&Position>), With<bool>>()
2784                .iter()
2785                .next();
2786        }));
2787        assert!(panic.is_err());
2788        assert!(world.get_mut::<Health>(entity).is_ok());
2789        drop(held);
2790        assert!(
2791            world
2792                .query_filtered::<(&mut Health, Option<&Position>), With<bool>>()
2793                .iter()
2794                .next()
2795                .is_some()
2796        );
2797    }
2798
2799    #[test]
2800    fn filtered_membership_tracks_structural_changes_and_slot_reuse() {
2801        let mut world = World::new();
2802        let early = world.spawn(());
2803        let later = world.spawn((Health(2),));
2804        world.insert(early, (Health(1),)).unwrap();
2805        assert_eq!(filtered_ids::<With<Health>>(&world), [early, later]);
2806        world.remove::<Health>(early).unwrap();
2807        assert_eq!(filtered_ids::<With<Health>>(&world), [later]);
2808        assert_eq!(filtered_ids::<Without<Health>>(&world), [early]);
2809        world.despawn(early).unwrap();
2810        let reused = world.spawn((Health(3),));
2811        assert_eq!(reused.id(), early.id());
2812        assert_ne!(reused, early);
2813        assert_eq!(filtered_ids::<With<Health>>(&world), [reused, later]);
2814        assert!(!<Not<Without<Health>> as QueryFilter>::matches(
2815            &world, early
2816        ));
2817        world.despawn_many(&[later, reused]).unwrap();
2818        assert!(filtered_ids::<Not<Any<()>>>(&world).is_empty());
2819        let restarted = world.spawn(());
2820        assert!(filtered_ids::<With<Health>>(&world).is_empty());
2821        assert_eq!(filtered_ids::<Without<Health>>(&world), [restarted]);
2822    }
2823
2824    #[test]
2825    fn filtered_queries_do_not_register_storage_or_grow_buffers() {
2826        struct NeverRegistered;
2827        let mut world = World::new();
2828        world.spawn((Health(1),));
2829        for _ in 0..127 {
2830            world.spawn(());
2831        }
2832        let before = (
2833            world.slots.capacity(),
2834            world.free.capacity(),
2835            world.storages.capacity(),
2836            world.storages.len(),
2837        );
2838        let health_capacity = world
2839            .storages
2840            .get(&TypeId::of::<Health>())
2841            .unwrap()
2842            .as_any()
2843            .downcast_ref::<Storage<Health>>()
2844            .unwrap()
2845            .slots
2846            .capacity();
2847        type Filter = All<(
2848            Without<NeverRegistered>,
2849            Any<(With<Health>, Not<With<Health>>)>,
2850        )>;
2851        for _ in 0..4 {
2852            assert_eq!(
2853                world
2854                    .query_filtered::<(Entity, Option<&mut NeverRegistered>), Filter>()
2855                    .try_iter()
2856                    .map(|row| {
2857                        assert!(row.unwrap().1.is_none());
2858                    })
2859                    .count(),
2860                128
2861            );
2862            assert_eq!(world.query_filtered::<&Health, Filter>().iter().count(), 1);
2863            assert!(filtered_ids::<With<NeverRegistered>>(&world).is_empty());
2864        }
2865        assert_eq!(
2866            (
2867                world.slots.capacity(),
2868                world.free.capacity(),
2869                world.storages.capacity(),
2870                world.storages.len()
2871            ),
2872            before
2873        );
2874        assert_eq!(
2875            world
2876                .storages
2877                .get(&TypeId::of::<Health>())
2878                .unwrap()
2879                .as_any()
2880                .downcast_ref::<Storage<Health>>()
2881                .unwrap()
2882                .slots
2883                .capacity(),
2884            health_capacity
2885        );
2886        assert!(
2887            !world
2888                .storages
2889                .contains_key(&TypeId::of::<NeverRegistered>())
2890        );
2891        assert_eq!(std::mem::size_of::<With<Health>>(), 0);
2892        assert_eq!(std::mem::size_of::<Filter>(), 0);
2893        assert_eq!(
2894            std::mem::size_of::<QueryBorrow<'_, Entity, Filter>>(),
2895            std::mem::size_of::<QueryBorrow<'_, Entity>>()
2896        );
2897        assert_eq!(
2898            std::mem::size_of::<TryQueryIter<'_, Entity, Filter>>(),
2899            std::mem::size_of::<TryQueryIter<'_, Entity>>()
2900        );
2901    }
2902
2903    #[test]
2904    fn filtered_iterator_forms_and_default_type_arguments_remain_usable() {
2905        fn fused<I: std::iter::FusedIterator>(_: &I) {}
2906        let mut world = World::new();
2907        let first = world.spawn((Health(1),));
2908        world.spawn(());
2909        let last = world.spawn((Health(3),));
2910        let unfiltered: QueryBorrow<'_, Entity> = world.try_query().unwrap();
2911        let _: QueryIter<'_, Entity> = unfiltered.iter();
2912        let _: TryQueryIter<'_, Entity> = unfiltered.try_iter();
2913        let mut query: QueryBorrow<'_, Entity, With<Health>> = world.try_query_filtered().unwrap();
2914        assert_eq!((&query).into_iter().collect::<Vec<_>>(), [first, last]);
2915        assert_eq!((&mut query).into_iter().collect::<Vec<_>>(), [first, last]);
2916        assert_eq!(query.into_iter().collect::<Vec<_>>(), [first, last]);
2917        let mut rows = world.query_filtered::<Entity, With<Health>>().try_iter();
2918        fused(&rows);
2919        assert_eq!(rows.size_hint(), (0, Some(3)));
2920        assert_eq!(rows.next(), Some(Ok(first)));
2921        assert_eq!(rows.size_hint(), (0, Some(2)));
2922        assert_eq!(rows.next(), Some(Ok(last)));
2923        assert_eq!(rows.size_hint(), (0, Some(0)));
2924        assert_eq!(rows.next(), None);
2925        assert_eq!(rows.next(), None);
2926        let iter = world.query_filtered::<Entity, With<Health>>().iter();
2927        fused(&iter);
2928    }
2929
2930    #[test]
2931    fn reused_slot_rejects_every_stale_handle_operation() {
2932        let mut world = World::new();
2933        let old = world.spawn((Position(1.0, 2.0), Health(10)));
2934        world.despawn(old).unwrap();
2935        let new = world.spawn((Position(8.0, 9.0),));
2936        assert_eq!(old.id(), new.id());
2937        assert_ne!(old.generation(), new.generation());
2938        assert!(!world.contains(old));
2939        assert!(world.contains(new));
2940        assert_eq!(Entity::from_bits(new.to_bits()), new);
2941        assert!(matches!(
2942            world.get::<&Position>(old),
2943            Err(Error::NoSuchEntity(_))
2944        ));
2945        assert!(matches!(
2946            world.get_mut::<Position>(old),
2947            Err(Error::NoSuchEntity(_))
2948        ));
2949        assert!(matches!(
2950            world.insert(old, (Health(50),)),
2951            Err(Error::NoSuchEntity(_))
2952        ));
2953        assert!(matches!(
2954            world.remove::<Position>(old),
2955            Err(Error::NoSuchEntity(_))
2956        ));
2957        assert!(matches!(world.despawn(old), Err(Error::NoSuchEntity(_))));
2958        assert!(!world.has::<Health>(new));
2959        assert_eq!(*world.get::<&Position>(new).unwrap(), Position(8.0, 9.0));
2960        assert_eq!(world.len(), 1);
2961    }
2962
2963    #[test]
2964    fn exhausted_generations_retire_slots_instead_of_wrapping() {
2965        let mut world = World::new();
2966        let first = world.spawn((7_i32,));
2967        world.slots[first.id() as usize].generation = u32::MAX;
2968        let final_handle = Entity {
2969            index: first.id(),
2970            generation: u32::MAX,
2971        };
2972        world.despawn(final_handle).unwrap();
2973        let next = world.spawn((8_i32,));
2974        assert_ne!(next.id(), first.id());
2975        assert!(!world.contains(first));
2976        assert!(!world.contains(final_handle));
2977    }
2978
2979    #[test]
2980    fn despawn_many_removes_duplicates_once_in_first_occurrence_order() {
2981        struct RecordDrop(u32, Rc<RefCell<Vec<u32>>>);
2982        impl Drop for RecordDrop {
2983            fn drop(&mut self) {
2984                self.1.borrow_mut().push(self.0);
2985            }
2986        }
2987        let drops = Rc::new(RefCell::new(Vec::new()));
2988        let mut world = World::new();
2989        let first = world.spawn((RecordDrop(1, drops.clone()), Health(10)));
2990        let survivor = world.spawn((Health(20), Position(2.0, 3.0)));
2991        let last = world.spawn((RecordDrop(3, drops.clone()), Velocity(4.0, 5.0)));
2992        let empty = world.spawn(());
2993
2994        assert_eq!(
2995            world.despawn_many(&[last, first, last, empty, first]),
2996            Ok(3)
2997        );
2998        assert_eq!(*drops.borrow(), [3, 1]);
2999        assert_eq!(world.len(), 1);
3000        assert_eq!(world.entities().collect::<Vec<_>>(), [survivor]);
3001        assert_eq!(world.query::<&Health>().iter().count(), 1);
3002        assert_eq!(world.query::<&Velocity>().iter().count(), 0);
3003        let [(mut health, position)] = world
3004            .get_many::<(&mut Health, &Position), 1>([survivor])
3005            .unwrap();
3006        health.0 += 1;
3007        assert_eq!(*position, Position(2.0, 3.0));
3008        drop((health, position));
3009
3010        // Sequential despawns push first occurrences onto the free-slot stack.
3011        for old in [empty, first, last] {
3012            let replacement = world.spawn(());
3013            assert_eq!(replacement.id(), old.id());
3014            assert_eq!(replacement.generation(), old.generation() + 1);
3015            assert!(!world.has::<RecordDrop>(replacement));
3016            assert!(!world.has::<Health>(replacement));
3017            assert!(!world.has::<Velocity>(replacement));
3018            assert!(matches!(
3019                world.get_many::<Entity, 1>([old]),
3020                Err(Error::NoSuchEntity(entity)) if entity == old
3021            ));
3022        }
3023        assert_eq!(world.get::<&Health>(survivor).unwrap().0, 21);
3024        drop(world);
3025        assert_eq!(*drops.borrow(), [3, 1]);
3026    }
3027
3028    #[test]
3029    fn despawn_many_validation_failure_preserves_components_generations_and_free_slots() {
3030        struct CountDrop(Rc<Cell<usize>>);
3031        impl Drop for CountDrop {
3032            fn drop(&mut self) {
3033                self.0.set(self.0.get() + 1);
3034            }
3035        }
3036        let drops = Rc::new(Cell::new(0));
3037        let mut world = World::new();
3038        let first = world.spawn((Health(10), CountDrop(drops.clone())));
3039        let second = world.spawn((Health(20), CountDrop(drops.clone())));
3040        let stale = world.spawn(());
3041        world.despawn(stale).unwrap();
3042        let invalid = Entity::from_bits(u64::MAX);
3043        let wrong_generation = Entity {
3044            index: first.id(),
3045            generation: first.generation() + 1,
3046        };
3047        let slots_before: Vec<_> = world
3048            .slots
3049            .iter()
3050            .map(|slot| (slot.alive, slot.generation))
3051            .collect();
3052        let free_before = world.free.clone();
3053
3054        for (batch, expected) in [
3055            ([first, second, first, stale, invalid], stale),
3056            ([first, second, first, invalid, stale], invalid),
3057            ([stale, first, second, stale, invalid], stale),
3058            (
3059                [first, second, first, wrong_generation, stale],
3060                wrong_generation,
3061            ),
3062        ] {
3063            assert_eq!(
3064                world.despawn_many(&batch),
3065                Err(Error::NoSuchEntity(expected))
3066            );
3067            assert_eq!(world.len(), 2);
3068            assert_eq!(world.entities().collect::<Vec<_>>(), [first, second]);
3069            assert_eq!(drops.get(), 0);
3070            assert_eq!(world.free, free_before);
3071            assert_eq!(
3072                world
3073                    .slots
3074                    .iter()
3075                    .map(|slot| (slot.alive, slot.generation))
3076                    .collect::<Vec<_>>(),
3077                slots_before
3078            );
3079            let [a, b] = world.get_many::<&mut Health, 2>([first, second]).unwrap();
3080            assert_eq!((a.0, b.0), (10, 20));
3081        }
3082        let replacement = world.spawn(());
3083        assert_eq!(replacement.id(), stale.id());
3084        assert_eq!(replacement.generation(), stale.generation() + 1);
3085        assert_eq!(world.despawn_many(&[first, second, first]), Ok(2));
3086        assert_eq!(drops.get(), 2);
3087        assert!(world.contains(replacement));
3088    }
3089
3090    #[test]
3091    fn despawn_many_rejects_stale_handles_even_when_the_replacement_is_in_the_batch() {
3092        let mut world = World::new();
3093        let stale = world.spawn((Health(10),));
3094        world.despawn(stale).unwrap();
3095        let replacement = world.spawn((Health(20),));
3096        let other = world.spawn((Health(30),));
3097        assert_eq!(stale.id(), replacement.id());
3098        for batch in [
3099            [replacement, other, stale],
3100            [other, stale, replacement],
3101            [stale, replacement, other],
3102        ] {
3103            assert_eq!(world.despawn_many(&batch), Err(Error::NoSuchEntity(stale)));
3104            assert_eq!(world.len(), 2);
3105            let [a, b] = world
3106                .get_many::<&mut Health, 2>([replacement, other])
3107                .unwrap();
3108            assert_eq!((a.0, b.0), (20, 30));
3109        }
3110        assert_eq!(world.despawn_many(&[replacement, other]), Ok(2));
3111        assert!(world.is_empty());
3112    }
3113
3114    #[test]
3115    fn despawn_many_empty_batches_are_noops_and_componentless_entities_are_removed() {
3116        let mut world = World::new();
3117        assert_eq!(world.despawn_many(&[]), Ok(0));
3118        let entity = world.spawn(());
3119        assert_eq!(world.despawn_many(&[]), Ok(0));
3120        assert!(world.contains(entity));
3121        assert_eq!(world.len(), 1);
3122        assert_eq!(world.despawn_many(&[entity, entity]), Ok(1));
3123        assert!(world.is_empty());
3124        assert_eq!(world.despawn_many(&[]), Ok(0));
3125        assert_eq!(
3126            world.despawn_many(&[entity, entity]),
3127            Err(Error::NoSuchEntity(entity))
3128        );
3129    }
3130
3131    #[test]
3132    fn despawn_many_retires_exhausted_generations_without_recycling_duplicates() {
3133        let mut world = World::new();
3134        let first = world.spawn((Health(10),));
3135        world.slots[first.id() as usize].generation = u32::MAX;
3136        let exhausted = Entity {
3137            index: first.id(),
3138            generation: u32::MAX,
3139        };
3140        let ordinary = world.spawn((Health(20),));
3141        assert_eq!(
3142            world.despawn_many(&[exhausted, ordinary, exhausted, ordinary]),
3143            Ok(2)
3144        );
3145        assert!(world.is_empty());
3146        let reused = world.spawn(());
3147        assert_eq!(reused.id(), ordinary.id());
3148        assert_eq!(reused.generation(), ordinary.generation() + 1);
3149        let fresh = world.spawn(());
3150        assert_ne!(fresh.id(), exhausted.id());
3151        assert_ne!(fresh.id(), reused.id());
3152        assert!(!world.contains(first));
3153        assert!(!world.contains(exhausted));
3154        assert!(!world.contains(ordinary));
3155    }
3156
3157    #[test]
3158    fn despawn_many_destructor_panic_preserves_later_entities_and_retires_current_slot() {
3159        struct PanicOnDrop;
3160        impl Drop for PanicOnDrop {
3161            fn drop(&mut self) {
3162                panic!("component destructor failed");
3163            }
3164        }
3165        let mut world = World::new();
3166        let before = world.spawn((Health(10),));
3167        let panicking = world.spawn((PanicOnDrop, Health(20)));
3168        let after = world.spawn((Health(30),));
3169        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3170            world.despawn_many(&[before, panicking, after]).unwrap();
3171        }));
3172        assert!(result.is_err());
3173        assert!(!world.contains(before));
3174        assert!(!world.contains(panicking));
3175        assert_eq!(world.entities().collect::<Vec<_>>(), [after]);
3176        assert_eq!(world.len(), 1);
3177        assert_eq!(world.get::<&Health>(after).unwrap().0, 30);
3178        let reused = world.spawn(());
3179        assert_eq!(reused.id(), before.id());
3180        let fresh = world.spawn(());
3181        assert_ne!(fresh.id(), panicking.id());
3182        assert!(!world.has::<Health>(reused));
3183        assert!(!world.has::<Health>(fresh));
3184        assert_eq!(world.despawn_many(&[after, reused, fresh]), Ok(3));
3185        assert!(world.is_empty());
3186    }
3187
3188    #[test]
3189    fn tuple_queries_update_only_matching_entities_and_return_ids() {
3190        let mut world = World::new();
3191        let matching = world.spawn((Position(2.0, 3.0), Velocity(4.0, -1.0), Health(30), "pilot"));
3192        let stationary = world.spawn((Position(20.0, 30.0), Health(100)));
3193        let removed = world.spawn((Position(9.0, 9.0), Velocity(1.0, 1.0)));
3194        world.despawn(removed).unwrap();
3195        for (entity, mut position, mut velocity) in
3196            &mut world.query::<(Entity, &mut Position, &mut Velocity)>()
3197        {
3198            assert_eq!(entity, matching);
3199            position.0 += velocity.0;
3200            position.1 += velocity.1;
3201            velocity.0 *= 0.5;
3202        }
3203        assert_eq!(
3204            *world.get::<&Position>(matching).unwrap(),
3205            Position(6.0, 2.0)
3206        );
3207        assert_eq!(
3208            *world.get::<&Velocity>(matching).unwrap(),
3209            Velocity(2.0, -1.0)
3210        );
3211        assert_eq!(
3212            *world.get::<&Position>(stationary).unwrap(),
3213            Position(20.0, 30.0)
3214        );
3215        assert_eq!(
3216            world
3217                .query::<(&Position, &Velocity, &Health, &&str)>()
3218                .iter()
3219                .count(),
3220            1
3221        );
3222        assert_eq!(world.query::<&Position>().iter().count(), 2);
3223        assert_eq!(
3224            world.entities().collect::<Vec<_>>(),
3225            vec![matching, stationary]
3226        );
3227    }
3228
3229    #[test]
3230    fn guards_can_outlive_iterators_and_other_entity_guards() {
3231        let mut world = World::new();
3232        let a = world.spawn((Health(1),));
3233        let b = world.spawn((Health(2),));
3234        let (mut first, mut second) = {
3235            let mut items = world.query::<&mut Health>().iter();
3236            let first = items.next().unwrap();
3237            let second = items.next().unwrap();
3238            assert!(items.next().is_none());
3239            (first, second)
3240        };
3241        first.0 += 10;
3242        second.0 += 20;
3243        assert!(matches!(
3244            world.get::<&Health>(a),
3245            Err(Error::BorrowConflict(_))
3246        ));
3247        drop(first);
3248        assert_eq!(world.get::<&Health>(a).unwrap().0, 11);
3249        assert!(matches!(
3250            world.get::<&Health>(b),
3251            Err(Error::BorrowConflict(_))
3252        ));
3253        drop(second);
3254        assert_eq!(world.get::<&Health>(b).unwrap().0, 22);
3255    }
3256
3257    #[test]
3258    fn borrow_conflicts_are_fallible_and_release_on_drop() {
3259        let mut world = World::new();
3260        let entity = world.spawn((Health(7), Position(2.0, 3.0)));
3261        let shared = world.get::<&Health>(entity).unwrap();
3262        let other_shared = world.get::<&Health>(entity).unwrap();
3263        assert!(matches!(
3264            world.get::<&mut Health>(entity),
3265            Err(Error::BorrowConflict(_))
3266        ));
3267        assert!(world.get_mut::<Position>(entity).is_ok());
3268        drop((shared, other_shared));
3269        let mut exclusive = world.get_mut::<Health>(entity).unwrap();
3270        exclusive.0 = 9;
3271        assert!(matches!(
3272            world.get::<&Health>(entity),
3273            Err(Error::BorrowConflict(_))
3274        ));
3275        assert!(matches!(
3276            world.get_mut::<Health>(entity),
3277            Err(Error::BorrowConflict(_))
3278        ));
3279        drop(exclusive);
3280        assert_eq!(world.get::<&Health>(entity).unwrap().0, 9);
3281    }
3282
3283    #[test]
3284    fn get_many_borrows_tuples_in_requested_order_and_updates_selected_entities() {
3285        let mut world = World::new();
3286        let first = world.spawn((Health(10), Velocity(1.0, 0.0)));
3287        let untouched = world.spawn((Health(20), Velocity(2.0, 0.0)));
3288        let last = world.spawn((Health(30), Velocity(3.0, 0.0)));
3289        let [
3290            (last_id, mut last_health, last_speed),
3291            (first_id, mut first_health, first_speed),
3292        ] = world
3293            .get_many::<(Entity, &mut Health, &Velocity), 2>([last, first])
3294            .unwrap();
3295        assert_eq!((last_id, first_id), (last, first));
3296        last_health.0 -= last_speed.0 as i32;
3297        first_health.0 += first_speed.0 as i32;
3298        assert!(matches!(
3299            world.get::<&Health>(first),
3300            Err(Error::BorrowConflict(_))
3301        ));
3302        assert_eq!(world.get::<&Health>(untouched).unwrap().0, 20);
3303        drop((last_health, first_health, last_speed, first_speed));
3304        assert_eq!(world.get::<&Health>(last).unwrap().0, 27);
3305        assert_eq!(world.get::<&Health>(first).unwrap().0, 11);
3306    }
3307
3308    #[test]
3309    fn get_many_allows_repeated_shared_access_and_identity_only_queries() {
3310        let mut world = World::new();
3311        let entity = world.spawn((Health(10),));
3312        let [(a, b), (c, d)] = world
3313            .get_many::<(&Health, &Health), 2>([entity, entity])
3314            .unwrap();
3315        assert_eq!((a.0, b.0, c.0, d.0), (10, 10, 10, 10));
3316        assert!(matches!(
3317            world.get_mut::<Health>(entity),
3318            Err(Error::BorrowConflict(_))
3319        ));
3320        drop((a, b, c, d));
3321        let held = world.get_mut::<Health>(entity).unwrap();
3322        assert_eq!(
3323            world.get_many::<Entity, 2>([entity, entity]).unwrap(),
3324            [entity, entity]
3325        );
3326        assert_eq!(held.0, 10);
3327    }
3328
3329    #[test]
3330    fn get_many_rejects_duplicate_mutable_access_and_releases_all_prior_guards() {
3331        let mut world = World::new();
3332        let first = world.spawn((Health(10), Position(1.0, 2.0)));
3333        let second = world.spawn((Health(20), Position(3.0, 4.0)));
3334        assert!(matches!(
3335            world.get_many::<(&Position, &mut Health), 3>([first, second, first]),
3336            Err(Error::BorrowConflict(name)) if name == type_name::<Health>()
3337        ));
3338        // Both earlier entities and the shared borrow from the partial final tuple
3339        // must be released when duplicate mutable access fails.
3340        for entity in [first, second] {
3341            assert!(world.get_mut::<Position>(entity).is_ok());
3342            assert!(world.get_mut::<Health>(entity).is_ok());
3343        }
3344        assert!(matches!(
3345            world.get_many::<(&mut Health, &Health), 1>([first]),
3346            Err(Error::ConflictingQuery(name)) if name == type_name::<Health>()
3347        ));
3348        assert!(matches!(
3349            world.get_many::<(&mut Health, &mut Health), 1>([first]),
3350            Err(Error::ConflictingQuery(_))
3351        ));
3352        assert_eq!(world.get::<&Health>(first).unwrap().0, 10);
3353        assert_eq!(world.get::<&Health>(second).unwrap().0, 20);
3354    }
3355
3356    #[test]
3357    fn get_many_missing_component_releases_completed_and_partial_tuples() {
3358        let mut world = World::new();
3359        let complete = world.spawn((Health(10), Position(1.0, 2.0)));
3360        let incomplete = world.spawn((Health(20),));
3361        assert!(matches!(
3362            world.get_many::<(&mut Health, &mut Position), 2>([complete, incomplete]),
3363            Err(Error::MissingComponent(name)) if name == type_name::<Position>()
3364        ));
3365        assert!(world.get_mut::<Position>(complete).is_ok());
3366        assert_eq!(world.get_mut::<Health>(complete).unwrap().0, 10);
3367        assert_eq!(world.get_mut::<Health>(incomplete).unwrap().0, 20);
3368        world.insert(incomplete, (Position(3.0, 4.0),)).unwrap();
3369        assert!(
3370            world
3371                .get_many::<(&mut Health, &mut Position), 2>([complete, incomplete])
3372                .is_ok()
3373        );
3374    }
3375
3376    #[test]
3377    fn get_many_external_conflict_preserves_existing_guard_and_releases_new_ones() {
3378        let mut world = World::new();
3379        let first = world.spawn((Health(10), Position(1.0, 2.0)));
3380        let second = world.spawn((Health(20), Position(3.0, 4.0)));
3381        let held = world.get::<&Position>(second).unwrap();
3382        assert!(matches!(
3383            world.get_many::<(&mut Health, &mut Position), 2>([first, second]),
3384            Err(Error::BorrowConflict(name)) if name == type_name::<Position>()
3385        ));
3386        assert_eq!(*held, Position(3.0, 4.0));
3387        assert!(world.get_mut::<Position>(first).is_ok());
3388        assert_eq!(world.get_mut::<Health>(first).unwrap().0, 10);
3389        assert_eq!(world.get_mut::<Health>(second).unwrap().0, 20);
3390        assert!(matches!(
3391            world.get_mut::<Position>(second),
3392            Err(Error::BorrowConflict(_))
3393        ));
3394        drop(held);
3395        assert!(
3396            world
3397                .get_many::<(&mut Health, &mut Position), 2>([first, second])
3398                .is_ok()
3399        );
3400    }
3401
3402    #[test]
3403    fn get_many_checks_all_identities_before_borrowing_and_rejects_reused_handles() {
3404        let mut world = World::new();
3405        let alive = world.spawn((Health(10),));
3406        let stale = world.spawn((Health(20),));
3407        world.despawn(stale).unwrap();
3408        assert!(matches!(
3409            world.get_many::<&mut Health, 2>([alive, stale]),
3410            Err(Error::NoSuchEntity(entity)) if entity == stale
3411        ));
3412        let replacement = world.spawn((Health(30),));
3413        assert_eq!(stale.id(), replacement.id());
3414        assert_ne!(stale.generation(), replacement.generation());
3415        let held = world.get_mut::<Health>(alive).unwrap();
3416        // Invalid identity wins even when an earlier entity is already borrowed.
3417        for invalid in [stale, Entity::from_bits(u64::MAX)] {
3418            assert!(matches!(
3419                world.get_many::<&mut Health, 2>([alive, invalid]),
3420                Err(Error::NoSuchEntity(entity)) if entity == invalid
3421            ));
3422        }
3423        assert!(matches!(
3424            world.get_many::<&mut Health, 2>([replacement, stale]),
3425            Err(Error::NoSuchEntity(entity)) if entity == stale
3426        ));
3427        assert!(matches!(
3428            world.get_many::<Entity, 1>([stale]),
3429            Err(Error::NoSuchEntity(entity)) if entity == stale
3430        ));
3431        assert_eq!(held.0, 10);
3432        drop(held);
3433        let [mut health] = world.get_many::<&mut Health, 1>([replacement]).unwrap();
3434        health.0 += 1;
3435        drop(health);
3436        assert_eq!(world.get::<&Health>(replacement).unwrap().0, 31);
3437    }
3438
3439    #[test]
3440    fn get_many_empty_input_still_validates_query_signature() {
3441        let world = World::new();
3442        assert!(world.get_many::<&mut Health, 0>([]).unwrap().is_empty());
3443        assert!(matches!(
3444            world.get_many::<(&mut Health, &Health), 0>([]),
3445            Err(Error::ConflictingQuery(_))
3446        ));
3447    }
3448
3449    #[test]
3450    fn query_aliases_reject_mutable_duplicates_allow_shared_duplicates() {
3451        let mut world = World::new();
3452        world.spawn((Health(10),));
3453        assert!(matches!(
3454            world.try_query::<(&mut Health, &Health)>(),
3455            Err(Error::ConflictingQuery(_))
3456        ));
3457        assert!(matches!(
3458            world.try_query::<(&mut Health, &mut Health)>(),
3459            Err(Error::ConflictingQuery(_))
3460        ));
3461        let values = world.query::<(&Health, &Health)>().iter().next().unwrap();
3462        assert_eq!(values.0.0, values.1.0);
3463        assert_eq!(world.query::<(Entity, Entity)>().iter().count(), 1);
3464    }
3465
3466    #[test]
3467    fn tuple_borrow_failure_releases_partial_borrows_and_continues() {
3468        let mut world = World::new();
3469        let first = world.spawn((Health(1), Position(1.0, 1.0)));
3470        let second = world.spawn((Health(2), Position(2.0, 2.0)));
3471        let lock = world.get_mut::<Position>(first).unwrap();
3472        let mut iterator = world.query::<(&mut Health, &mut Position)>().try_iter();
3473        assert!(matches!(
3474            iterator.next().unwrap(),
3475            Err(Error::BorrowConflict(_))
3476        ));
3477        // Fetching Health succeeded before Position failed, so it must have been released.
3478        assert!(world.get_mut::<Health>(first).is_ok());
3479        let (mut health, _) = iterator.next().unwrap().unwrap();
3480        health.0 = 12;
3481        drop((iterator, health, lock));
3482        assert_eq!(world.get::<&Health>(second).unwrap().0, 12);
3483    }
3484
3485    #[test]
3486    fn missing_components_are_filtered_before_any_borrow_attempt() {
3487        let mut world = World::new();
3488        let entity = world.spawn((Health(10),));
3489        let guard = world.get_mut::<Health>(entity).unwrap();
3490        let mut query = world.query::<(&mut Health, &Position)>().try_iter();
3491        assert!(query.next().is_none());
3492        drop(guard);
3493    }
3494
3495    #[test]
3496    fn optional_members_retain_required_matches_and_update_present_components() {
3497        let mut world = World::new();
3498        let moving = world.spawn((Position(1.0, 2.0), Velocity(3.0, 4.0), Health(10)));
3499        let stationary = world.spawn((Position(5.0, 6.0),));
3500        let no_position = world.spawn((Velocity(9.0, 9.0), Health(20)));
3501        let held = world.get_mut::<Velocity>(no_position).unwrap();
3502        let mut visited = Vec::new();
3503        for row in world
3504            .query::<(
3505                Entity,
3506                &mut Position,
3507                Option<&Velocity>,
3508                Option<&mut Health>,
3509            )>()
3510            .try_iter()
3511        {
3512            let (entity, mut position, velocity, health) = row.unwrap();
3513            visited.push(entity);
3514            if let Some(velocity) = velocity {
3515                position.0 += velocity.0;
3516                position.1 += velocity.1;
3517            }
3518            if let Some(mut health) = health {
3519                health.0 -= 1;
3520            }
3521        }
3522        assert_eq!(visited, [moving, stationary]);
3523        assert_eq!(*world.get::<&Position>(moving).unwrap(), Position(4.0, 6.0));
3524        assert_eq!(
3525            *world.get::<&Position>(stationary).unwrap(),
3526            Position(5.0, 6.0)
3527        );
3528        assert_eq!(world.get::<&Health>(moving).unwrap().0, 9);
3529        assert_eq!(world.get::<&Health>(no_position).unwrap().0, 20);
3530        assert!(!world.has::<Health>(stationary));
3531        assert_eq!(*held, Velocity(9.0, 9.0));
3532    }
3533
3534    #[test]
3535    fn optional_only_queries_visit_every_live_slot_in_order() {
3536        let mut world = World::new();
3537        assert!(world.query::<Option<&Health>>().iter().next().is_none());
3538        let before_storage = world.spawn(());
3539        let present = world.spawn((Health(10),));
3540        let dead = world.spawn((Health(20),));
3541        let beyond_storage = world.spawn(());
3542        world.despawn(dead).unwrap();
3543
3544        let rows: Vec<_> = world
3545            .query::<(Entity, Option<&Health>, Option<&Velocity>)>()
3546            .iter()
3547            .map(|(entity, health, velocity)| {
3548                assert!(velocity.is_none()); // This type has never been registered.
3549                (entity, health.map(|health| health.0))
3550            })
3551            .collect();
3552        assert_eq!(
3553            rows,
3554            [
3555                (before_storage, None),
3556                (present, Some(10)),
3557                (beyond_storage, None)
3558            ]
3559        );
3560        let mut iter = world.query::<Option<&mut Health>>().try_iter();
3561        assert!(iter.next().unwrap().unwrap().is_none());
3562        iter.next().unwrap().unwrap().unwrap().0 += 1;
3563        assert!(iter.next().unwrap().unwrap().is_none());
3564        assert!(iter.next().is_none());
3565        assert!(iter.next().is_none());
3566        assert_eq!(iter.size_hint(), (0, Some(0)));
3567        assert_eq!(world.get::<&Health>(present).unwrap().0, 11);
3568        assert_eq!(world.query::<Option<&mut Velocity>>().iter().count(), 3);
3569    }
3570
3571    #[test]
3572    fn optional_aliases_are_rejected_even_on_empty_worlds_and_batches() {
3573        fn rejects<Q: Query>(world: &World, entities: [Entity; 1]) {
3574            assert!(matches!(world.try_query::<Q>(),
3575                Err(Error::ConflictingQuery(name)) if name == type_name::<Health>()));
3576            assert!(matches!(world.get_many::<Q, 0>([]),
3577                Err(Error::ConflictingQuery(name)) if name == type_name::<Health>()));
3578            assert!(matches!(world.get_many::<Q, 1>(entities),
3579                Err(Error::ConflictingQuery(name)) if name == type_name::<Health>()));
3580        }
3581        let mut world = World::new();
3582        // Signature errors precede identity errors, even without any components.
3583        for entities in [[Entity::from_bits(u64::MAX)], [world.spawn(())]] {
3584            rejects::<(&Health, Option<&mut Health>)>(&world, entities);
3585            rejects::<(Option<&mut Health>, &Health)>(&world, entities);
3586            rejects::<(&mut Health, Option<&Health>)>(&world, entities);
3587            rejects::<(Option<&Health>, &mut Health)>(&world, entities);
3588            rejects::<(&mut Health, Option<&mut Health>)>(&world, entities);
3589            rejects::<(Option<&mut Health>, &mut Health)>(&world, entities);
3590            rejects::<(Option<&Health>, Option<&mut Health>)>(&world, entities);
3591            rejects::<(Option<&mut Health>, Option<&Health>)>(&world, entities);
3592            rejects::<(Option<&mut Health>, Option<&mut Health>)>(&world, entities);
3593        }
3594        let empty = World::new();
3595        rejects::<(Option<&mut Health>, Option<&Health>)>(&empty, [Entity::from_bits(0)]);
3596    }
3597
3598    #[test]
3599    fn optional_get_distinguishes_absence_from_incompatible_borrows() {
3600        let mut world = World::new();
3601        let present = world.spawn((Health(10),));
3602        let absent = world.spawn(());
3603        let shared = world.get::<Option<&Health>>(present).unwrap().unwrap();
3604        assert!(matches!(world.get::<Option<&mut Health>>(present),
3605            Err(Error::BorrowConflict(name)) if name == type_name::<Health>()));
3606        assert!(world.get::<Option<&mut Health>>(absent).unwrap().is_none());
3607        assert_eq!(
3608            world.get::<Option<&Health>>(present).unwrap().unwrap().0,
3609            10
3610        );
3611        drop(shared);
3612        let mut exclusive = world.get::<Option<&mut Health>>(present).unwrap().unwrap();
3613        exclusive.0 += 1;
3614        assert!(matches!(
3615            world.get::<Option<&Health>>(present),
3616            Err(Error::BorrowConflict(_))
3617        ));
3618        assert!(matches!(
3619            world.get::<Option<&mut Health>>(present),
3620            Err(Error::BorrowConflict(_))
3621        ));
3622        assert!(world.get::<Option<&Health>>(absent).unwrap().is_none());
3623        drop(exclusive);
3624        assert_eq!(
3625            world.get::<Option<&Health>>(present).unwrap().unwrap().0,
3626            11
3627        );
3628    }
3629
3630    #[test]
3631    fn optional_iterator_conflicts_release_partial_guards_and_continue() {
3632        let mut world = World::new();
3633        let first = world.spawn((Health(10), Position(1.0, 2.0)));
3634        let absent = world.spawn(());
3635        let last = world.spawn((Health(30), Position(3.0, 4.0)));
3636        let held = world.get_mut::<Position>(first).unwrap();
3637        let (health, position) = {
3638            let mut iter = world
3639                .query::<(Option<&mut Health>, Option<&Position>)>()
3640                .try_iter();
3641            assert!(matches!(iter.next().unwrap(),
3642                Err(Error::BorrowConflict(name)) if name == type_name::<Position>()));
3643            assert_eq!(world.get_mut::<Health>(first).unwrap().0, 10);
3644            let (health, position) = iter.next().unwrap().unwrap();
3645            assert!(health.is_none() && position.is_none());
3646            assert!(!world.has::<Health>(absent));
3647            let row = iter.next().unwrap().unwrap();
3648            assert!(iter.next().is_none());
3649            row
3650        };
3651        // Guards outlive the iterator and conflict with a new one.
3652        assert!(matches!(
3653            world
3654                .query::<Option<&mut Health>>()
3655                .try_iter()
3656                .nth(2)
3657                .unwrap(),
3658            Err(Error::BorrowConflict(_))
3659        ));
3660        health.unwrap().0 += 1;
3661        assert!(matches!(
3662            world.get_mut::<Position>(last),
3663            Err(Error::BorrowConflict(_))
3664        ));
3665        drop((position, held));
3666        assert_eq!(world.get::<&Health>(last).unwrap().0, 31);
3667        assert_eq!(
3668            world
3669                .query::<(Option<&mut Health>, Option<&mut Position>)>()
3670                .iter()
3671                .count(),
3672            3
3673        );
3674    }
3675
3676    #[test]
3677    fn optional_members_still_prefilter_all_required_components_before_borrowing() {
3678        let mut world = World::new();
3679        let entity = world.spawn((Health(10),));
3680        let held = world.get_mut::<Health>(entity).unwrap();
3681        assert!(
3682            world
3683                .query::<(Option<&Health>, &Position)>()
3684                .try_iter()
3685                .next()
3686                .is_none()
3687        );
3688        assert!(
3689            world
3690                .query::<(Option<&mut Health>, &Position)>()
3691                .try_iter()
3692                .next()
3693                .is_none()
3694        );
3695        drop(held);
3696        // get_many retains its fetch-order semantics instead of filtering entities.
3697        assert!(
3698            matches!(world.get_many::<(Option<&mut Health>, &Position), 1>([entity]),
3699            Err(Error::MissingComponent(name)) if name == type_name::<Position>())
3700        );
3701        assert_eq!(world.get_mut::<Health>(entity).unwrap().0, 10);
3702    }
3703
3704    #[test]
3705    fn optional_get_many_keeps_order_and_allows_repeated_absent_mutable_access() {
3706        let mut world = World::new();
3707        let first = world.spawn((Health(10), Position(1.0, 2.0)));
3708        let absent = world.spawn(());
3709        let last = world.spawn((Health(30),));
3710        let rows = world
3711            .get_many::<(Entity, Option<&mut Health>, Option<&Position>), 4>([
3712                last, absent, first, absent,
3713            ])
3714            .unwrap();
3715        for ((entity, health, position), expected) in
3716            rows.into_iter().zip([last, absent, first, absent])
3717        {
3718            assert_eq!(entity, expected);
3719            assert_eq!(health.is_some(), entity != absent);
3720            assert_eq!(position.is_some(), entity == first);
3721            if let Some(mut health) = health {
3722                health.0 += 1;
3723            }
3724        }
3725        assert_eq!(world.get::<&Health>(first).unwrap().0, 11);
3726        assert_eq!(world.get::<&Health>(last).unwrap().0, 31);
3727        assert!(
3728            world
3729                .get_many::<Option<&mut Health>, 0>([])
3730                .unwrap()
3731                .is_empty()
3732        );
3733        assert!(
3734            world
3735                .get_many::<Option<&mut Health>, 2>([absent, absent])
3736                .unwrap()
3737                .iter()
3738                .all(Option::is_none)
3739        );
3740    }
3741
3742    #[test]
3743    fn optional_shared_duplicates_work_with_required_access_and_repeated_entities() {
3744        let mut world = World::new();
3745        let entity = world.spawn((Health(10),));
3746        let rows = world
3747            .get_many::<(Entity, &Health, Option<&Health>, Option<&Health>), 2>([entity, entity])
3748            .unwrap();
3749        for (id, required, optional_a, optional_b) in &rows {
3750            assert_eq!(*id, entity);
3751            assert_eq!(required.0, 10);
3752            assert_eq!(optional_a.as_ref().unwrap().0, 10);
3753            assert_eq!(optional_b.as_ref().unwrap().0, 10);
3754        }
3755        assert_eq!(
3756            world
3757                .query::<(&Health, Option<&Health>, Option<&Health>)>()
3758                .iter()
3759                .count(),
3760            1
3761        );
3762        assert!(matches!(
3763            world.get_mut::<Health>(entity),
3764            Err(Error::BorrowConflict(_))
3765        ));
3766        drop(rows);
3767        assert!(world.get_mut::<Health>(entity).is_ok());
3768    }
3769
3770    #[test]
3771    fn optional_get_many_duplicate_mutable_entities_release_completed_and_partial_guards() {
3772        let mut world = World::new();
3773        let first = world.spawn((Health(10), Position(1.0, 2.0)));
3774        let second = world.spawn((Health(20), Position(3.0, 4.0)));
3775        assert!(
3776            matches!(world.get_many::<(Option<&Position>, Option<&mut Health>), 3>([first, second, first]),
3777            Err(Error::BorrowConflict(name)) if name == type_name::<Health>())
3778        );
3779        for entity in [first, second] {
3780            assert!(world.get_mut::<Position>(entity).is_ok());
3781            assert!(world.get_mut::<Health>(entity).is_ok());
3782        }
3783        assert_eq!(world.get::<&Health>(first).unwrap().0, 10);
3784        assert_eq!(world.get::<&Health>(second).unwrap().0, 20);
3785        assert!(
3786            world
3787                .get_many::<(Option<&Position>, Option<&mut Health>), 2>([first, second])
3788                .is_ok()
3789        );
3790    }
3791
3792    #[test]
3793    fn optional_get_many_external_conflict_releases_new_guards_and_preserves_existing_one() {
3794        let mut world = World::new();
3795        let first = world.spawn((Health(10), Position(1.0, 2.0)));
3796        let second = world.spawn((Health(20), Position(3.0, 4.0)));
3797        let held = world.get::<&Position>(second).unwrap();
3798        assert!(
3799            matches!(world.get_many::<(Option<&mut Health>, Option<&mut Position>), 2>([first, second]),
3800            Err(Error::BorrowConflict(name)) if name == type_name::<Position>())
3801        );
3802        assert!(world.get_mut::<Position>(first).is_ok());
3803        assert_eq!(world.get_mut::<Health>(first).unwrap().0, 10);
3804        assert_eq!(world.get_mut::<Health>(second).unwrap().0, 20);
3805        assert_eq!(*held, Position(3.0, 4.0));
3806        assert!(matches!(
3807            world.get_mut::<Position>(second),
3808            Err(Error::BorrowConflict(_))
3809        ));
3810        drop(held);
3811        assert!(
3812            world
3813                .get_many::<(Option<&mut Health>, Option<&mut Position>), 2>([first, second])
3814                .is_ok()
3815        );
3816
3817        world.remove::<Position>(second).unwrap();
3818        assert!(matches!(
3819            world.get_many::<(Option<&mut Health>, &Position), 2>([first, second]),
3820            Err(Error::MissingComponent(_))
3821        ));
3822        assert!(world.get_mut::<Position>(first).is_ok());
3823        assert!(world.get_mut::<Health>(first).is_ok());
3824        assert!(world.get_mut::<Health>(second).is_ok());
3825    }
3826
3827    #[test]
3828    fn optional_access_observes_remove_reinsert_and_reuse_without_accepting_stale_handles() {
3829        let mut world = World::new();
3830        let stale = world.spawn((Health(10),));
3831        assert_eq!(world.remove::<Health>(stale).unwrap().0, 10);
3832        assert!(world.get::<Option<&Health>>(stale).unwrap().is_none());
3833        world.insert(stale, (Health(20),)).unwrap();
3834        assert_eq!(
3835            world.get::<Option<&mut Health>>(stale).unwrap().unwrap().0,
3836            20
3837        );
3838        world.despawn(stale).unwrap();
3839        let replacement = world.spawn(());
3840        assert_eq!(stale.id(), replacement.id());
3841        assert_ne!(stale.generation(), replacement.generation());
3842        assert!(world.get::<Option<&Health>>(replacement).unwrap().is_none());
3843        let alive = world.spawn((Health(30),));
3844        let held = world.get_mut::<Health>(alive).unwrap();
3845        for invalid in [stale, Entity::from_bits(u64::MAX)] {
3846            assert!(matches!(world.get::<Option<&Health>>(invalid),
3847                Err(Error::NoSuchEntity(entity)) if entity == invalid));
3848            assert!(matches!(world.get::<Option<&mut Health>>(invalid),
3849                Err(Error::NoSuchEntity(entity)) if entity == invalid));
3850            // All identities are checked before the earlier borrowed component.
3851            assert!(
3852                matches!(world.get_many::<Option<&mut Health>, 2>([alive, invalid]),
3853                Err(Error::NoSuchEntity(entity)) if entity == invalid)
3854            );
3855        }
3856        drop(held);
3857        let ids: Vec<_> = world
3858            .query::<(Entity, Option<&Health>)>()
3859            .iter()
3860            .map(|row| row.0)
3861            .collect();
3862        assert_eq!(ids, [replacement, alive]);
3863        world.despawn_many(&[replacement, alive]).unwrap();
3864        assert!(world.query::<Option<&mut Health>>().iter().next().is_none());
3865        let restarted = world.spawn((Health(40),));
3866        assert_eq!(
3867            world.get::<Option<&Health>>(restarted).unwrap().unwrap().0,
3868            40
3869        );
3870    }
3871
3872    #[test]
3873    fn optional_absence_does_not_register_storage_or_grow_world_buffers() {
3874        let mut world = World::new();
3875        let entity = world.spawn(());
3876        let capacities = (
3877            world.slots.capacity(),
3878            world.free.capacity(),
3879            world.storages.capacity(),
3880        );
3881        assert!(world.get::<Option<&Health>>(entity).unwrap().is_none());
3882        assert!(
3883            world
3884                .query::<Option<&mut Health>>()
3885                .iter()
3886                .next()
3887                .unwrap()
3888                .is_none()
3889        );
3890        let rows = world
3891            .get_many::<Option<&mut Health>, 128>([entity; 128])
3892            .unwrap();
3893        assert!(rows.iter().all(Option::is_none));
3894        drop(rows);
3895        assert!(world.storages.is_empty());
3896        assert_eq!(
3897            capacities,
3898            (
3899                world.slots.capacity(),
3900                world.free.capacity(),
3901                world.storages.capacity()
3902            )
3903        );
3904        assert_eq!(world.len(), 1);
3905        world.insert(entity, (Health(10),)).unwrap();
3906        assert_eq!(world.get::<Option<&Health>>(entity).unwrap().unwrap().0, 10);
3907    }
3908
3909    #[test]
3910    fn optional_panicking_iteration_releases_partial_guards() {
3911        let mut world = World::new();
3912        let entity = world.spawn((Health(10), Position(1.0, 2.0)));
3913        let held = world.get::<&Position>(entity).unwrap();
3914        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3915            let _ = world
3916                .query::<(Option<&mut Health>, Option<&mut Position>)>()
3917                .iter()
3918                .next();
3919        }));
3920        assert!(result.is_err());
3921        assert_eq!(world.get_mut::<Health>(entity).unwrap().0, 10);
3922        assert_eq!(*held, Position(1.0, 2.0));
3923        drop(held);
3924        assert!(world.get_mut::<Position>(entity).is_ok());
3925    }
3926
3927    #[test]
3928    fn duplicate_bundles_are_rejected_before_mutation() {
3929        let mut world = World::new();
3930        assert!(matches!(
3931            world.try_spawn((1_i32, 2_i32)),
3932            Err(Error::DuplicateComponent(_))
3933        ));
3934        assert!(world.is_empty());
3935        let entity = world.spawn((Health(10), 5_i32));
3936        assert!(matches!(
3937            world.insert(entity, (6_i32, 7_i32)),
3938            Err(Error::DuplicateComponent(_))
3939        ));
3940        assert_eq!(*world.get::<&i32>(entity).unwrap(), 5);
3941        assert_eq!(world.len(), 1);
3942    }
3943
3944    #[test]
3945    fn insert_replace_remove_and_empty_entities_work() {
3946        let mut world = World::new();
3947        let entity = world.spawn(());
3948        assert!(world.contains(entity));
3949        world
3950            .insert(entity, (Health(10), Position(1.0, 2.0)))
3951            .unwrap();
3952        world.insert(entity, (Health(25),)).unwrap();
3953        assert_eq!(world.remove::<Health>(entity).unwrap(), Health(25));
3954        assert!(matches!(
3955            world.remove::<Health>(entity),
3956            Err(Error::MissingComponent(_))
3957        ));
3958        assert!(matches!(
3959            world.get::<&Health>(entity),
3960            Err(Error::MissingComponent(_))
3961        ));
3962        assert_eq!(world.query::<&Position>().iter().count(), 1);
3963        world.despawn(entity).unwrap();
3964        assert!(world.is_empty());
3965    }
3966
3967    #[test]
3968    fn components_drop_exactly_once_when_replaced_removed_or_despawned() {
3969        struct CountDrop(Rc<Cell<usize>>);
3970        impl Drop for CountDrop {
3971            fn drop(&mut self) {
3972                self.0.set(self.0.get() + 1);
3973            }
3974        }
3975        let drops = Rc::new(Cell::new(0));
3976        let mut world = World::new();
3977        let entity = world.spawn((CountDrop(drops.clone()),));
3978        world.insert(entity, (CountDrop(drops.clone()),)).unwrap();
3979        assert_eq!(drops.get(), 1);
3980        let removed = world.remove::<CountDrop>(entity).unwrap();
3981        assert_eq!(drops.get(), 1);
3982        drop(removed);
3983        assert_eq!(drops.get(), 2);
3984        world.insert(entity, (CountDrop(drops.clone()),)).unwrap();
3985        world.despawn(entity).unwrap();
3986        assert_eq!(drops.get(), 3);
3987        drop(world);
3988        assert_eq!(drops.get(), 3);
3989    }
3990
3991    #[test]
3992    fn independently_overlapping_iterators_conflict_without_aliasing() {
3993        let mut world = World::new();
3994        world.spawn((Health(10),));
3995        let mut first = world.query::<&mut Health>().iter();
3996        let guard = first.next().unwrap();
3997        let mut second = world.query::<&mut Health>().try_iter();
3998        assert!(matches!(
3999            second.next().unwrap(),
4000            Err(Error::BorrowConflict(_))
4001        ));
4002        drop(guard);
4003        assert_eq!(world.query::<&Health>().iter().next().unwrap().0, 10);
4004    }
4005
4006    #[test]
4007    fn failed_panicking_query_does_not_poison_component_borrows() {
4008        let mut world = World::new();
4009        let entity = world.spawn((Health(10), Position(1.0, 2.0)));
4010        let lock = world.get_mut::<Position>(entity).unwrap();
4011        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4012            let _ = world.query::<(&mut Health, &mut Position)>().iter().next();
4013        }));
4014        assert!(result.is_err());
4015        assert!(world.get_mut::<Health>(entity).is_ok());
4016        drop(lock);
4017        assert!(world.get_mut::<Position>(entity).is_ok());
4018    }
4019
4020    #[test]
4021    fn thousands_of_reuse_cycles_preserve_counts_and_components() {
4022        let mut world = World::new();
4023        let mut stale = Vec::new();
4024        for i in 0_u32..2_000 {
4025            let entity = world.spawn((i,));
4026            assert_eq!(world.len(), 1);
4027            assert_eq!(*world.get::<&u32>(entity).unwrap(), i);
4028            assert!(stale.iter().all(|old| !world.contains(*old)));
4029            world.despawn(entity).unwrap();
4030            stale.push(entity);
4031            assert!(world.is_empty());
4032        }
4033        assert_eq!(world.slots.len(), 1);
4034    }
4035    #[test]
4036    fn panicking_destructor_does_not_recycle_partially_cleaned_slot() {
4037        struct PanicOnDrop;
4038        impl Drop for PanicOnDrop {
4039            fn drop(&mut self) {
4040                panic!("component destructor failed");
4041            }
4042        }
4043        let mut world = World::new();
4044        let entity = world.spawn((PanicOnDrop, Health(10)));
4045        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4046            world.despawn(entity).unwrap();
4047        }));
4048        assert!(result.is_err());
4049        assert!(!world.contains(entity));
4050        assert!(world.is_empty());
4051        let next = world.spawn((Position(1.0, 2.0),));
4052        assert_ne!(next.id(), entity.id());
4053        assert!(!world.has::<Health>(next));
4054    }
4055}
4056
4057#[cfg(test)]
4058mod journey400_213 {
4059    use super::*;
4060    use std::cell::Cell;
4061    use std::panic::{AssertUnwindSafe, catch_unwind};
4062    use std::rc::Rc;
4063
4064    const SENTINEL: Entity = Entity {
4065        index: u32::MAX,
4066        generation: u32::MAX,
4067    };
4068
4069    #[derive(Debug)]
4070    struct Part<const I: usize>(i32);
4071
4072    type Eight = (
4073        Part<0>,
4074        Part<1>,
4075        Part<2>,
4076        Part<3>,
4077        Part<4>,
4078        Part<5>,
4079        Part<6>,
4080        Part<7>,
4081    );
4082
4083    fn eight(value: i32) -> Eight {
4084        (
4085            Part(value),
4086            Part(value),
4087            Part(value),
4088            Part(value),
4089            Part(value),
4090            Part(value),
4091            Part(value),
4092            Part(value),
4093        )
4094    }
4095
4096    #[test]
4097    fn preparation_is_monotonic_preserves_values_and_is_independent() {
4098        let mut world = World::default();
4099        assert_eq!(world.prepared_entity_capacity(), 0);
4100        assert_eq!(world.prepared_component_capacity::<String>(), 0);
4101        let live = world.spawn((String::from("retained"),));
4102        let dead = world.spawn(());
4103        world.despawn(dead).unwrap();
4104        let free = world.free.clone();
4105        world.prepare_entities(12).unwrap();
4106        world.prepare_entities(2).unwrap();
4107        assert_eq!(world.prepared_entity_capacity(), 12);
4108        assert_eq!(world.prepared_component_capacity::<String>(), 0);
4109        world.prepare_component::<String>(20).unwrap();
4110        world.prepare_component::<String>(1).unwrap();
4111        world.prepare_component::<bool>(0).unwrap();
4112        assert_eq!(world.prepared_component_capacity::<String>(), 20);
4113        assert_eq!(world.prepared_component_capacity::<bool>(), 0);
4114        assert_eq!(world.prepared_entity_capacity(), 12);
4115        assert_eq!(world.free, free);
4116        assert_eq!(world.slots.len(), 2);
4117        assert_eq!(world.len(), 1);
4118        assert_eq!(&*world.get::<&String>(live).unwrap(), "retained");
4119        assert!(
4120            world.storages[&TypeId::of::<String>()]
4121                .as_any()
4122                .downcast_ref::<Storage<String>>()
4123                .unwrap()
4124                .slots[1..]
4125                .iter()
4126                .all(Option::is_none)
4127        );
4128        assert!(world.slots.capacity() >= 12);
4129        assert!(world.free.capacity() >= 12);
4130    }
4131
4132    #[test]
4133    fn nonclone_inputs_survive_every_capacity_error_and_can_be_retried() {
4134        #[derive(Debug)]
4135        struct Owned {
4136            value: String,
4137            drops: Rc<Cell<usize>>,
4138        }
4139        impl Drop for Owned {
4140            fn drop(&mut self) {
4141                self.drops.set(self.drops.get() + 1);
4142            }
4143        }
4144        let drops = Rc::new(Cell::new(0));
4145        let inputs = std::array::from_fn::<_, 2, _>(|i| {
4146            (Owned {
4147                value: format!("projectile {i}"),
4148                drops: drops.clone(),
4149            },)
4150        });
4151        let mut world = World::new();
4152        let mut output = [SENTINEL; 3];
4153        let (error, inputs) = world.try_spawn_batch(inputs, &mut output[..1]).unwrap_err();
4154        assert_eq!(
4155            error,
4156            SpawnError::OutputTooSmall {
4157                required: 2,
4158                available: 1
4159            }
4160        );
4161        let (error, inputs) = world.try_spawn_batch(inputs, &mut output).unwrap_err();
4162        assert_eq!(
4163            error,
4164            SpawnError::EntityCapacity {
4165                required: 2,
4166                prepared: 0
4167            }
4168        );
4169        world.prepare_entities(2).unwrap();
4170        let (error, inputs) = world.try_spawn_batch(inputs, &mut output).unwrap_err();
4171        assert_eq!(
4172            error,
4173            SpawnError::ComponentCapacity {
4174                component: type_name::<Owned>(),
4175                required: 2,
4176                prepared: 0,
4177            }
4178        );
4179        assert!(world.storages.is_empty());
4180        world.prepare_component::<Owned>(1).unwrap();
4181        let (error, inputs) = world.try_spawn_batch(inputs, &mut output).unwrap_err();
4182        assert_eq!(
4183            error,
4184            SpawnError::ComponentCapacity {
4185                component: type_name::<Owned>(),
4186                required: 2,
4187                prepared: 1,
4188            }
4189        );
4190        assert!(world.is_empty());
4191        assert!(world.slots.is_empty());
4192        assert!(world.free.is_empty());
4193        assert_eq!(output, [SENTINEL; 3]);
4194        assert_eq!(drops.get(), 0);
4195        assert_eq!(inputs[0].0.value, "projectile 0");
4196        assert_eq!(inputs[1].0.value, "projectile 1");
4197        world.prepare_component::<Owned>(2).unwrap();
4198        assert_eq!(world.try_spawn_batch(inputs, &mut output).unwrap(), 2);
4199        assert_eq!(output[2], SENTINEL);
4200        assert_eq!(
4201            world.get::<&Owned>(output[1]).unwrap().value,
4202            "projectile 1"
4203        );
4204        world.despawn_many(&output[..2]).unwrap();
4205        assert_eq!(drops.get(), 2);
4206    }
4207
4208    #[test]
4209    fn late_duplicate_precedes_all_other_errors_even_for_empty_batches() {
4210        type Duplicate = (u8, u16, u32, u64, i8, i16, i32, u8);
4211        let mut world = World::new();
4212        let live = world.spawn((9_u8,));
4213        let dead = world.spawn(());
4214        world.despawn(dead).unwrap();
4215        let free = world.free.clone();
4216        let capacities = (
4217            world.slots.capacity(),
4218            world.free.capacity(),
4219            world.storages.capacity(),
4220        );
4221        let inputs: [Duplicate; 2] = [(1, 2, 3, 4, 5, 6, 7, 8), (11, 12, 13, 14, 15, 16, 17, 18)];
4222        let (error, returned) = world.try_spawn_batch(inputs, &mut []).unwrap_err();
4223        assert_eq!(error, SpawnError::DuplicateComponent(type_name::<u8>()));
4224        assert_eq!(returned, inputs);
4225        let mut output = [SENTINEL; 1];
4226        let (error, _) = world
4227            .try_spawn_batch::<Duplicate, 0>([], &mut output)
4228            .unwrap_err();
4229        assert_eq!(error, SpawnError::DuplicateComponent(type_name::<u8>()));
4230        assert_eq!(output, [SENTINEL]);
4231        assert_eq!(world.free, free);
4232        assert_eq!(world.len(), 1);
4233        assert_eq!(world.slots.len(), 2);
4234        assert_eq!(world.storages.len(), 1);
4235        assert_eq!(*world.get::<&u8>(live).unwrap(), 9);
4236        assert_eq!(
4237            (
4238                world.slots.capacity(),
4239                world.free.capacity(),
4240                world.storages.capacity()
4241            ),
4242            capacities
4243        );
4244    }
4245
4246    #[test]
4247    fn every_component_budget_is_checked_before_any_spawn() {
4248        for missing in 0..8 {
4249            let mut world = World::new();
4250            world.prepare_entities(2).unwrap();
4251            macro_rules! prepare {
4252                ($($i:literal),+) => { $(
4253                    world.prepare_component::<Part<$i>>(if missing == $i { 1 } else { 2 }).unwrap();
4254                )+ };
4255            }
4256            prepare!(0, 1, 2, 3, 4, 5, 6, 7);
4257            let names = <Eight as sealed::Bundle>::component_types_inline();
4258            let mut output = [SENTINEL; 2];
4259            let (error, input) = world
4260                .try_spawn_batch([eight(10), eight(20)], &mut output)
4261                .unwrap_err();
4262            assert_eq!(
4263                error,
4264                SpawnError::ComponentCapacity {
4265                    component: names[missing].unwrap().1,
4266                    required: 2,
4267                    prepared: 1,
4268                }
4269            );
4270            assert_eq!((input[0].0.0, input[1].7.0), (10, 20));
4271            assert_eq!(output, [SENTINEL; 2]);
4272            assert_eq!(world.len(), 0);
4273            assert!(world.slots.is_empty());
4274            macro_rules! empty {
4275                ($($i:literal),+) => { $(
4276                    assert!(world.storages[&TypeId::of::<Part<$i>>()].as_any()
4277                        .downcast_ref::<Storage<Part<$i>>>().unwrap().slots.iter().all(Option::is_none));
4278                )+ };
4279            }
4280            empty!(0, 1, 2, 3, 4, 5, 6, 7);
4281        }
4282    }
4283
4284    #[test]
4285    fn mixed_free_and_new_slots_preserve_caller_order_and_generations() {
4286        let mut world = World::new();
4287        let initial = std::array::from_fn::<_, 4, _>(|i| world.spawn((i as i32,)));
4288        world.despawn_many(&[initial[1], initial[3]]).unwrap();
4289        world.prepare_entities(5).unwrap();
4290        world.prepare_component::<i32>(5).unwrap();
4291        let mut output = [SENTINEL; 5];
4292        assert_eq!(
4293            world.try_spawn_batch([(30_i32,), (10,), (40,)], &mut output),
4294            Ok(3)
4295        );
4296        assert_eq!(output.map(Entity::id), [3, 1, 4, u32::MAX, u32::MAX]);
4297        assert_eq!(
4298            output[..3]
4299                .iter()
4300                .map(|id| id.generation())
4301                .collect::<Vec<_>>(),
4302            [1, 1, 0]
4303        );
4304        assert!(!world.contains(initial[1]));
4305        assert!(!world.contains(initial[3]));
4306        for (id, expected) in output[..3].iter().zip([30, 10, 40]) {
4307            assert_eq!(*world.get::<&i32>(*id).unwrap(), expected);
4308        }
4309        assert_eq!(
4310            world.query::<&i32>().iter().map(|v| *v).collect::<Vec<_>>(),
4311            [0, 10, 2, 30, 40]
4312        );
4313        assert_eq!(output[3..], [SENTINEL; 2]);
4314    }
4315
4316    #[test]
4317    fn rejection_does_not_consume_an_available_free_prefix() {
4318        let mut world = World::new();
4319        world.prepare_entities(2).unwrap();
4320        world.prepare_component::<i32>(2).unwrap();
4321        let live = world.spawn((7_i32,));
4322        let freed = world.spawn((8_i32,));
4323        world.despawn(freed).unwrap();
4324        let mut output = [SENTINEL; 3];
4325        let input = [(10_i32,), (20,)];
4326        let (error, input) = world.try_spawn_batch(input, &mut output[..1]).unwrap_err();
4327        assert_eq!(
4328            error,
4329            SpawnError::OutputTooSmall {
4330                required: 2,
4331                available: 1
4332            }
4333        );
4334        let (error, input) = world.try_spawn_batch(input, &mut output).unwrap_err();
4335        assert_eq!(
4336            error,
4337            SpawnError::EntityCapacity {
4338                required: 3,
4339                prepared: 2
4340            }
4341        );
4342        world.prepare_entities(3).unwrap();
4343        let (error, input) = world.try_spawn_batch(input, &mut output).unwrap_err();
4344        assert_eq!(
4345            error,
4346            SpawnError::ComponentCapacity {
4347                component: type_name::<i32>(),
4348                required: 3,
4349                prepared: 2,
4350            }
4351        );
4352        assert_eq!(output, [SENTINEL; 3]);
4353        assert_eq!(world.free, [freed.id()]);
4354        assert_eq!(world.slots.len(), 2);
4355        assert_eq!(world.len(), 1);
4356        assert_eq!(*world.get::<&i32>(live).unwrap(), 7);
4357        world.prepare_component::<i32>(3).unwrap();
4358        assert_eq!(world.try_spawn_batch(input, &mut output), Ok(2));
4359        assert_eq!(output.map(Entity::id), [freed.id(), 2, u32::MAX]);
4360        assert_eq!(output[0].generation(), freed.generation() + 1);
4361    }
4362
4363    #[test]
4364    fn sparse_budgets_follow_selected_lifo_indices_not_live_count() {
4365        let mut world = World::new();
4366        let ids = std::array::from_fn::<_, 6, _>(|_| world.spawn(()));
4367        world.despawn_many(&[ids[5], ids[0]]).unwrap(); // Next selected index is 0.
4368        world.prepare_entities(1).unwrap();
4369        world.prepare_component::<i32>(1).unwrap();
4370        let mut output = [SENTINEL];
4371        assert_eq!(world.try_spawn_batch([(10_i32,)], &mut output), Ok(1));
4372        assert_eq!(output[0].id(), 0);
4373        let previous = output;
4374        let (error, _) = world.try_spawn_batch([(20_i32,)], &mut output).unwrap_err();
4375        assert_eq!(
4376            error,
4377            SpawnError::EntityCapacity {
4378                required: 6,
4379                prepared: 1
4380            }
4381        );
4382        assert_eq!(output, previous);
4383        assert_eq!(world.free, [5]);
4384        world.prepare_entities(6).unwrap();
4385        let (error, input) = world.try_spawn_batch([(20_i32,)], &mut output).unwrap_err();
4386        assert_eq!(
4387            error,
4388            SpawnError::ComponentCapacity {
4389                component: type_name::<i32>(),
4390                required: 6,
4391                prepared: 1,
4392            }
4393        );
4394        world.prepare_component::<i32>(6).unwrap();
4395        assert_eq!(world.try_spawn_batch(input, &mut output), Ok(1));
4396        assert_eq!(output[0].id(), 5);
4397        assert_eq!(world.len(), 6);
4398    }
4399
4400    #[test]
4401    fn unprepared_ordinary_growth_and_allocator_rounding_do_not_grant_budget() {
4402        let mut world = World::new();
4403        world.prepare_entities(1).unwrap();
4404        world.prepare_component::<i32>(1).unwrap();
4405        let first = world.spawn((1_i32,));
4406        let second = world.spawn((2_i32,)); // Ordinary spawn still grows.
4407        let mut output = [SENTINEL];
4408        let (error, _) = world.try_spawn_batch([(3_i32,)], &mut output).unwrap_err();
4409        assert_eq!(
4410            error,
4411            SpawnError::EntityCapacity {
4412                required: 3,
4413                prepared: 1
4414            }
4415        );
4416        world.prepare_entities(3).unwrap();
4417        let (error, _) = world.try_spawn_batch([(3_i32,)], &mut output).unwrap_err();
4418        assert_eq!(
4419            error,
4420            SpawnError::ComponentCapacity {
4421                component: type_name::<i32>(),
4422                required: 3,
4423                prepared: 1,
4424            }
4425        );
4426        assert_eq!(*world.get::<&i32>(first).unwrap(), 1);
4427        assert_eq!(*world.get::<&i32>(second).unwrap(), 2);
4428        assert_eq!(world.len(), 2);
4429        assert_eq!(world.prepared_component_capacity::<i32>(), 1);
4430        assert_eq!(output, [SENTINEL]);
4431    }
4432
4433    #[test]
4434    fn empty_batches_need_no_preparation_and_do_not_register_types() {
4435        let mut world = World::new();
4436        let mut output = [SENTINEL; 2];
4437        assert_eq!(
4438            world.try_spawn_batch::<(String,), 0>([], &mut output),
4439            Ok(0)
4440        );
4441        assert_eq!(world.try_spawn_batch::<(), 0>([], &mut []), Ok(0));
4442        assert_eq!(output, [SENTINEL; 2]);
4443        assert!(world.storages.is_empty());
4444        assert_eq!(world.slots.capacity(), 0);
4445        assert_eq!(world.free.capacity(), 0);
4446        world.prepare_entities(2).unwrap();
4447        assert_eq!(world.try_spawn_batch([(), ()], &mut output), Ok(2));
4448        assert_eq!(world.len(), 2);
4449        assert!(world.storages.is_empty());
4450        world.despawn_many(&output).unwrap();
4451        assert_eq!(world.try_spawn_batch([(), ()], &mut output), Ok(2));
4452        assert_eq!(output.map(Entity::id), [1, 0]);
4453    }
4454
4455    #[test]
4456    fn identity_arithmetic_preflights_without_allocating_huge_worlds() {
4457        assert_eq!(required_batch_slots(4, &[0, 3], 0), Ok(0));
4458        assert_eq!(required_batch_slots(4, &[0, 3], 1), Ok(4));
4459        assert_eq!(required_batch_slots(4, &[0, 3], 3), Ok(5));
4460        assert_eq!(
4461            required_batch_slots(usize::MAX, &[], 1),
4462            Err(SpawnError::IdentityCapacity)
4463        );
4464        assert_eq!(
4465            required_batch_slots(0, &[], usize::MAX),
4466            if usize::BITS > 32 {
4467                Err(SpawnError::IdentityCapacity)
4468            } else {
4469                Ok(usize::MAX)
4470            }
4471        );
4472        #[cfg(target_pointer_width = "64")]
4473        {
4474            let max = u32::MAX as usize + 1;
4475            assert_eq!(check_identity_capacity(max), Ok(()));
4476            assert_eq!(required_batch_slots(max - 1, &[], 1), Ok(max));
4477            assert_eq!(required_batch_slots(max, &[0], 1), Ok(1));
4478            assert_eq!(
4479                required_batch_slots(max, &[], 1),
4480                Err(SpawnError::IdentityCapacity)
4481            );
4482            let mut world = World::new();
4483            world.prepare_entities(2).unwrap();
4484            world.prepare_component::<i32>(2).unwrap();
4485            let live = world.spawn((5_i32,));
4486            assert_eq!(
4487                world.prepare_entities(max + 1),
4488                Err(SpawnError::IdentityCapacity)
4489            );
4490            assert_eq!(
4491                world.prepare_component::<i32>(max + 1),
4492                Err(SpawnError::IdentityCapacity)
4493            );
4494            assert_eq!(
4495                world.prepare_component::<bool>(max + 1),
4496                Err(SpawnError::IdentityCapacity)
4497            );
4498            assert_eq!(world.prepared_entity_capacity(), 2);
4499            assert_eq!(world.prepared_component_capacity::<i32>(), 2);
4500            assert_eq!(world.storages.len(), 1);
4501            assert_eq!(*world.get::<&i32>(live).unwrap(), 5);
4502        }
4503    }
4504
4505    #[test]
4506    fn reservation_overflow_returns_an_error_without_contents_or_budget_changes() {
4507        let mut storage = Storage::<u64>::default();
4508        prepare_storage(&mut storage, 2).unwrap();
4509        storage.slots[0] = Some(RefCell::new(99));
4510        assert_eq!(
4511            prepare_storage(&mut storage, usize::MAX),
4512            Err(SpawnError::AllocationFailed)
4513        );
4514        assert_eq!(storage.prepared, 2);
4515        assert_eq!(storage.slots.len(), 2);
4516        assert_eq!(*storage.slots[0].as_ref().unwrap().borrow(), 99);
4517        // Force Vec layout overflow at a representable identity count. No huge
4518        // allocation is attempted and no value of this component is constructed.
4519        #[cfg(target_pointer_width = "64")]
4520        {
4521            let mut world = World::new();
4522            assert_eq!(
4523                world.prepare_component::<[u8; 1 << 31]>(u32::MAX as usize + 1),
4524                Err(SpawnError::AllocationFailed)
4525            );
4526            assert!(world.storages.is_empty());
4527            assert!(world.is_empty());
4528        }
4529    }
4530
4531    #[test]
4532    fn retired_generation_slots_still_consume_sparse_budget() {
4533        let mut world = World::new();
4534        world.prepare_entities(1).unwrap();
4535        let initial = world.spawn(());
4536        world.slots[0].generation = u32::MAX;
4537        let exhausted = Entity {
4538            index: 0,
4539            generation: u32::MAX,
4540        };
4541        world.despawn(exhausted).unwrap();
4542        assert!(world.is_empty());
4543        assert!(world.free.is_empty());
4544        let mut output = [SENTINEL];
4545        let (error, input) = world.try_spawn_batch([()], &mut output).unwrap_err();
4546        assert_eq!(
4547            error,
4548            SpawnError::EntityCapacity {
4549                required: 2,
4550                prepared: 1
4551            }
4552        );
4553        assert_eq!(output, [SENTINEL]);
4554        world.prepare_entities(2).unwrap();
4555        assert_eq!(world.try_spawn_batch(input, &mut output), Ok(1));
4556        assert_eq!((output[0].id(), output[0].generation()), (1, 0));
4557        assert!(!world.contains(initial));
4558        assert!(!world.contains(exhausted));
4559    }
4560
4561    #[test]
4562    fn prepared_cold_spawn_and_repeated_resets_keep_all_ecs_buffers() {
4563        let mut world = World::new();
4564        world.prepare_entities(16).unwrap();
4565        macro_rules! prepare {
4566            ($($i:literal),+) => { $(world.prepare_component::<Part<$i>>(16).unwrap();)+ };
4567        }
4568        prepare!(0, 1, 2, 3, 4, 5, 6, 7);
4569        fn buffers(world: &World) -> Vec<(usize, usize, usize)> {
4570            let mut result = vec![
4571                (world.slots.as_ptr() as usize, world.slots.capacity(), 0),
4572                (world.free.as_ptr() as usize, world.free.capacity(), 0),
4573                (0, world.storages.capacity(), world.storages.len()),
4574            ];
4575            macro_rules! storage {
4576                ($($i:literal),+) => { $(
4577                    let storage = world.storages[&TypeId::of::<Part<$i>>()].as_any()
4578                        .downcast_ref::<Storage<Part<$i>>>().unwrap();
4579                    result.push((storage.slots.as_ptr() as usize, storage.slots.capacity(),
4580                        storage as *const Storage<Part<$i>> as usize));
4581                )+ };
4582            }
4583            storage!(0, 1, 2, 3, 4, 5, 6, 7);
4584            result
4585        }
4586        let prepared = buffers(&world);
4587        let mut output = [SENTINEL; 12];
4588        let mut old = None;
4589        for cycle in 0..64 {
4590            let inputs = std::array::from_fn::<_, 12, _>(|i| eight(cycle * 100 + i as i32));
4591            assert_eq!(world.try_spawn_batch(inputs, &mut output).unwrap(), 12);
4592            if let Some(old) = old {
4593                assert!(!world.contains(old));
4594            }
4595            assert_eq!(world.len(), 12);
4596            assert_eq!(world.get::<&Part<0>>(output[0]).unwrap().0, cycle * 100);
4597            assert_eq!(
4598                world.get::<&Part<7>>(output[11]).unwrap().0,
4599                cycle * 100 + 11
4600            );
4601            assert_eq!(buffers(&world), prepared); // Includes the very first spawn.
4602            old = Some(output[0]);
4603            world.despawn_many(&output).unwrap();
4604            assert!(world.is_empty());
4605            assert_eq!(world.query::<Option<&Part<7>>>().iter().count(), 0);
4606            assert_eq!(buffers(&world), prepared);
4607        }
4608    }
4609
4610    #[test]
4611    fn prepared_spawn_does_not_grow_a_full_storage_map() {
4612        let mut world = World::new();
4613        world.prepare_entities(1).unwrap();
4614        world.prepare_component::<u8>(1).unwrap();
4615        world.prepare_component::<u16>(1).unwrap();
4616        world.prepare_component::<u32>(1).unwrap();
4617        world.storages.shrink_to_fit();
4618        assert_eq!(world.storages.len(), world.storages.capacity());
4619        let capacity = world.storages.capacity();
4620        let mut output = [SENTINEL];
4621        assert_eq!(
4622            world.try_spawn_batch([(1_u8, 2_u16, 3_u32)], &mut output),
4623            Ok(1)
4624        );
4625        assert_eq!(world.storages.capacity(), capacity);
4626        world.despawn(output[0]).unwrap();
4627        assert_eq!(
4628            world.try_spawn_batch([(4_u8, 5_u16, 6_u32)], &mut output),
4629            Ok(1)
4630        );
4631        assert_eq!(world.storages.capacity(), capacity);
4632    }
4633
4634    #[test]
4635    fn rejection_returns_panicking_drop_value_without_running_destructor() {
4636        #[derive(Debug)]
4637        struct PanicDrop(Rc<Cell<bool>>);
4638        impl Drop for PanicDrop {
4639            fn drop(&mut self) {
4640                self.0.set(true);
4641                panic!("caller dropped rejected input");
4642            }
4643        }
4644        let dropped = Rc::new(Cell::new(false));
4645        let mut world = World::new();
4646        let mut output = [SENTINEL];
4647        let (error, input) = world
4648            .try_spawn_batch([(PanicDrop(dropped.clone()),)], &mut output)
4649            .unwrap_err();
4650        assert_eq!(
4651            error,
4652            SpawnError::EntityCapacity {
4653                required: 1,
4654                prepared: 0
4655            }
4656        );
4657        assert!(!dropped.get());
4658        assert_eq!(output, [SENTINEL]);
4659        assert!(catch_unwind(AssertUnwindSafe(|| drop(input))).is_err());
4660        assert!(dropped.get());
4661        assert!(world.is_empty());
4662        assert_eq!(world.spawn(()).id(), 0);
4663    }
4664}
4665
4666#[cfg(test)]
4667mod journey400_214 {
4668    use super::*;
4669    use std::cell::Cell;
4670    use std::panic::{AssertUnwindSafe, catch_unwind};
4671    use std::rc::Rc;
4672
4673    #[derive(Clone, Debug, PartialEq, Eq)]
4674    struct Part<const I: usize>(i32);
4675
4676    #[derive(Debug)]
4677    struct Counted {
4678        value: i32,
4679        clones: Rc<Cell<usize>>,
4680        drops: Rc<Cell<usize>>,
4681    }
4682    impl Clone for Counted {
4683        fn clone(&self) -> Self {
4684            self.clones.set(self.clones.get() + 1);
4685            Self {
4686                value: self.value,
4687                clones: self.clones.clone(),
4688                drops: self.drops.clone(),
4689            }
4690        }
4691    }
4692    impl Drop for Counted {
4693        fn drop(&mut self) {
4694            self.drops.set(self.drops.get() + 1);
4695        }
4696    }
4697    fn counted(value: i32) -> Counted {
4698        Counted {
4699            value,
4700            clones: Rc::new(Cell::new(0)),
4701            drops: Rc::new(Cell::new(0)),
4702        }
4703    }
4704
4705    fn buffers<T: 'static>(world: &World) -> [usize; 12] {
4706        let storage = world.storages[&TypeId::of::<T>()]
4707            .as_any()
4708            .downcast_ref::<Storage<T>>()
4709            .unwrap();
4710        [
4711            world.slots.len(),
4712            world.slots.capacity(),
4713            world.slots.as_ptr() as usize,
4714            world.free.len(),
4715            world.free.capacity(),
4716            world.free.as_ptr() as usize,
4717            world.storages.len(),
4718            world.storages.capacity(),
4719            storage.slots.len(),
4720            storage.slots.capacity(),
4721            storage.slots.as_ptr() as usize,
4722            std::ptr::from_ref(storage) as usize,
4723        ]
4724    }
4725
4726    #[test]
4727    fn selected_values_are_independent_and_references_require_explicit_remapping() {
4728        struct Transient;
4729        #[derive(Clone)]
4730        struct Link(Entity);
4731        let mut world = World::new();
4732        let first = world.spawn((String::from("actor"), Part::<0>(10), Transient));
4733        let second = world.spawn((String::from("partner"), Part::<0>(20), Transient));
4734        world.insert(first, (Link(second), second)).unwrap();
4735        world.insert(second, (Link(first), first)).unwrap();
4736        world.prepare_entities(4).unwrap();
4737        world.prepare_component::<String>(4).unwrap();
4738        world.prepare_component::<Link>(4).unwrap();
4739        world.prepare_component::<Entity>(4).unwrap();
4740        let plan = world
4741            .plan_duplication::<(String, Link, Entity), 2>([second, first])
4742            .unwrap();
4743        let map = plan.try_spawn(&mut world).map_err(|(e, _)| e).unwrap();
4744        assert_eq!(map.map(|(old, _)| old), [second, first]);
4745        for (old, new) in map {
4746            assert_ne!(old, new);
4747            assert!(![first, second].contains(&new));
4748            assert!(!world.has::<Transient>(new));
4749            assert!(!world.has::<Part<0>>(new));
4750            let original_link = world.get::<&Link>(old).unwrap().0;
4751            assert_eq!(world.get::<&Link>(new).unwrap().0, original_link);
4752            assert_eq!(*world.get::<&Entity>(new).unwrap(), original_link);
4753            let replacement = map.iter().find(|(id, _)| *id == original_link).unwrap().1;
4754            world.get::<&mut Link>(new).unwrap().0 = replacement;
4755            world.get::<&mut String>(new).unwrap().push_str(" copy");
4756        }
4757        assert_eq!(&*world.get::<&String>(first).unwrap(), "actor");
4758        assert_eq!(&*world.get::<&String>(map[1].1).unwrap(), "actor copy");
4759        assert_eq!(world.get::<&Link>(map[0].1).unwrap().0, map[1].1);
4760        assert_eq!(world.get::<&Link>(second).unwrap().0, first);
4761        assert_eq!(world.len(), 4);
4762    }
4763
4764    #[test]
4765    fn every_supported_selection_width_including_empty_clones_only_that_bundle() {
4766        macro_rules! width {
4767            ($($i:literal),*) => {{
4768                let mut world = World::new();
4769                let source = world.spawn(($(Part::<$i>($i),)*));
4770                world.prepare_entities(2).unwrap();
4771                $(world.prepare_component::<Part<$i>>(2).unwrap();)*
4772                let plan = world.plan_duplication::<($(Part<$i>,)*), 1>([source]).unwrap();
4773                let [(old, new)] = plan.try_spawn(&mut world).unwrap();
4774                assert_eq!(old, source);
4775                assert_ne!(old, new);
4776                $(assert_eq!(*world.get::<&Part<$i>>(new).unwrap(), Part::<$i>($i));)*
4777                assert_eq!(world.len(), 2);
4778            }};
4779        }
4780        width!();
4781        width!(0);
4782        width!(0, 1);
4783        width!(0, 1, 2);
4784        width!(0, 1, 2, 3);
4785        width!(0, 1, 2, 3, 4);
4786        width!(0, 1, 2, 3, 4, 5);
4787        width!(0, 1, 2, 3, 4, 5, 6);
4788        width!(0, 1, 2, 3, 4, 5, 6, 7);
4789    }
4790
4791    #[test]
4792    fn late_missing_component_calls_no_clone_and_releases_all_read_guards() {
4793        let mut world = World::new();
4794        let component = counted(10);
4795        let (clones, drops) = (component.clones.clone(), component.drops.clone());
4796        let first = world.spawn((component, 1_u8));
4797        let second = world.spawn((counted(20),));
4798        let freed = world.spawn(());
4799        world.despawn(freed).unwrap();
4800        let before = buffers::<Counted>(&world);
4801        assert_eq!(
4802            world
4803                .plan_duplication::<(Counted, u8), 2>([first, second])
4804                .err(),
4805            Some(DuplicationError::Access(Error::MissingComponent(
4806                type_name::<u8>()
4807            )))
4808        );
4809        assert_eq!(clones.get(), 0);
4810        assert_eq!(drops.get(), 0);
4811        assert_eq!(world.len(), 2);
4812        assert_eq!(buffers::<Counted>(&world), before);
4813        assert_eq!(world.free, [freed.id()]);
4814        assert!(world.get_mut::<Counted>(first).is_ok());
4815        assert!(world.get_mut::<Counted>(second).is_ok());
4816        assert!(world.get_mut::<u8>(first).is_ok());
4817        world.insert(second, (2_u8,)).unwrap();
4818        drop(
4819            world
4820                .plan_duplication::<(Counted, u8), 2>([first, second])
4821                .unwrap(),
4822        );
4823        assert_eq!(clones.get(), 1);
4824        assert_eq!(drops.get(), 1); // Discarded captured clone only.
4825        assert_eq!(world.len(), 2);
4826    }
4827
4828    #[test]
4829    fn last_source_eighth_borrow_conflict_prevents_all_clones_and_cleans_partial_rows() {
4830        type Selected = (Counted, u8, u16, u32, u64, i8, i16, i32);
4831        let mut world = World::new();
4832        let component = counted(10);
4833        let clones = component.clones.clone();
4834        let first = world.spawn((component, 1_u8, 2_u16, 3_u32, 4_u64, 5_i8, 6_i16, 7_i32));
4835        let second = world.spawn((counted(20), 1_u8, 2_u16, 3_u32, 4_u64, 5_i8, 6_i16, 7_i32));
4836        let held = world.get_mut::<i32>(second).unwrap();
4837        let before = buffers::<Counted>(&world);
4838        assert_eq!(
4839            world.plan_duplication::<Selected, 2>([first, second]).err(),
4840            Some(DuplicationError::Access(Error::BorrowConflict(
4841                type_name::<i32>()
4842            )))
4843        );
4844        assert_eq!(clones.get(), 0);
4845        assert_eq!(world.len(), 2);
4846        assert_eq!(buffers::<Counted>(&world), before);
4847        macro_rules! released {
4848            ($($t:ty),+) => { $(
4849                assert!(world.get_mut::<$t>(first).is_ok());
4850                assert!(world.get_mut::<$t>(second).is_ok());
4851            )+ };
4852        }
4853        released!(Counted, u8, u16, u32, u64, i8, i16);
4854        assert!(world.get_mut::<i32>(first).is_ok());
4855        assert_eq!(*held, 7);
4856        drop(held);
4857        drop(
4858            world
4859                .plan_duplication::<Selected, 2>([first, second])
4860                .unwrap(),
4861        );
4862        assert_eq!(clones.get(), 1);
4863    }
4864
4865    #[test]
4866    fn shared_selected_and_mutable_unselected_guards_allow_capture() {
4867        let mut world = World::new();
4868        let source = world.spawn((String::from("actor"), 10_i32));
4869        let selected = world.get::<&String>(source).unwrap();
4870        let mut unselected = world.get_mut::<i32>(source).unwrap();
4871        let plan = world.plan_duplication::<(String,), 1>([source]).unwrap();
4872        *unselected += 1;
4873        assert_eq!(&*selected, "actor");
4874        drop((selected, unselected));
4875        assert!(world.get_mut::<String>(source).is_ok());
4876        world.prepare_entities(2).unwrap();
4877        world.prepare_component::<String>(2).unwrap();
4878        let [(_, copy)] = plan.try_spawn(&mut world).unwrap();
4879        assert!(!world.has::<i32>(copy));
4880        assert_eq!(&*world.get::<&String>(copy).unwrap(), "actor");
4881    }
4882
4883    #[test]
4884    fn validation_precedence_covers_duplicate_types_sources_and_all_identities() {
4885        let mut world = World::new();
4886        let source = world.spawn((counted(1),));
4887        let stale = world.spawn(());
4888        world.despawn(stale).unwrap();
4889        let replacement = world.spawn(());
4890        type Duplicate = (Counted, u8, u16, u32, u64, i8, i16, Counted);
4891        let duplicate = DuplicationError::Access(Error::DuplicateComponent(type_name::<Counted>()));
4892        assert_eq!(
4893            world.plan_duplication::<Duplicate, 0>([]).err(),
4894            Some(duplicate.clone())
4895        );
4896        assert_eq!(
4897            world.plan_duplication::<Duplicate, 1>([stale]).err(),
4898            Some(duplicate)
4899        );
4900        let held = world.get_mut::<Counted>(source).unwrap();
4901        for invalid in [stale, Entity::from_bits(u64::MAX)] {
4902            assert_eq!(
4903                world
4904                    .plan_duplication::<(Counted,), 3>([source, source, invalid])
4905                    .err(),
4906                Some(DuplicationError::Access(Error::NoSuchEntity(invalid)))
4907            );
4908        }
4909        assert_eq!(
4910            world
4911                .plan_duplication::<(Counted,), 2>([source, source])
4912                .err(),
4913            Some(DuplicationError::DuplicateSource(source))
4914        );
4915        assert_eq!(held.clones.get(), 0);
4916        assert!(world.contains(replacement));
4917        assert_eq!(world.len(), 2);
4918        drop(held);
4919        // Selecting Entity requires a stored component; identity isn't selected implicitly.
4920        assert_eq!(
4921            world.plan_duplication::<(Entity,), 1>([source]).err(),
4922            Some(DuplicationError::Access(Error::MissingComponent(
4923                type_name::<Entity>()
4924            )))
4925        );
4926    }
4927
4928    #[test]
4929    fn empty_plans_need_no_preparation_or_storage_registration() {
4930        let world = World::new();
4931        let plan = world.plan_duplication::<(Counted,), 0>([]).unwrap();
4932        assert!(world.storages.is_empty());
4933        let mut target = World::new();
4934        assert_eq!(plan.try_spawn(&mut target).unwrap(), []);
4935        assert!(target.is_empty());
4936        assert!(target.storages.is_empty());
4937        assert_eq!(target.prepared_entities, 0);
4938    }
4939
4940    #[test]
4941    fn captured_snapshot_survives_source_mutation_despawn_and_reuse() {
4942        let mut world = World::new();
4943        let source = world.spawn((String::from("captured"),));
4944        let plan = world.plan_duplication::<(String,), 1>([source]).unwrap();
4945        world
4946            .get::<&mut String>(source)
4947            .unwrap()
4948            .push_str(" edited");
4949        world.remove::<String>(source).unwrap();
4950        world.despawn(source).unwrap();
4951        world.prepare_entities(1).unwrap();
4952        world.prepare_component::<String>(1).unwrap();
4953        let [(old, new)] = plan.try_spawn(&mut world).unwrap();
4954        assert_eq!(old, source);
4955        assert_eq!(new.id(), source.id());
4956        assert_ne!(old, new);
4957        assert!(!world.contains(old));
4958        assert_eq!(&*world.get::<&String>(new).unwrap(), "captured");
4959    }
4960
4961    #[test]
4962    fn a_detached_template_can_spawn_into_a_different_world() {
4963        let plan = {
4964            let mut source = World::new();
4965            let entity = source.spawn((42_i32,));
4966            source.plan_duplication::<(i32,), 1>([entity]).unwrap()
4967        };
4968        let mut target = World::new();
4969        target.prepare_entities(1).unwrap();
4970        target.prepare_component::<i32>(1).unwrap();
4971        let [(old, new)] = plan.try_spawn(&mut target).unwrap();
4972        assert_eq!(old, new); // Equal bits in different worlds are permitted.
4973        assert_eq!(*target.get::<&i32>(new).unwrap(), 42);
4974    }
4975
4976    #[test]
4977    fn capacity_failure_returns_the_snapshot_without_drops_reclones_or_free_slot_consumption() {
4978        let mut world = World::new();
4979        let component = counted(10);
4980        let (clones, drops) = (component.clones.clone(), component.drops.clone());
4981        let first = world.spawn((component,));
4982        let second = world.spawn((counted(20),));
4983        let free = world.spawn(());
4984        world.despawn(free).unwrap();
4985        let plan = world
4986            .plan_duplication::<(Counted,), 2>([first, second])
4987            .unwrap();
4988        assert_eq!(clones.get(), 1);
4989        let before = buffers::<Counted>(&world);
4990        let (error, plan) = plan.try_spawn(&mut world).unwrap_err();
4991        assert_eq!(
4992            error,
4993            SpawnError::EntityCapacity {
4994                required: 4,
4995                prepared: 0
4996            }
4997        );
4998        assert_eq!(buffers::<Counted>(&world), before);
4999        world.prepare_entities(4).unwrap();
5000        let before = buffers::<Counted>(&world);
5001        let (error, plan) = plan.try_spawn(&mut world).unwrap_err();
5002        assert_eq!(
5003            error,
5004            SpawnError::ComponentCapacity {
5005                component: type_name::<Counted>(),
5006                required: 4,
5007                prepared: 0,
5008            }
5009        );
5010        assert_eq!(buffers::<Counted>(&world), before);
5011        assert_eq!(world.free, [free.id()]);
5012        assert_eq!(world.len(), 2);
5013        assert_eq!(clones.get(), 1);
5014        assert_eq!(drops.get(), 0);
5015        world.get_mut::<Counted>(first).unwrap().value = 99;
5016        world.prepare_component::<Counted>(4).unwrap();
5017        let map = plan.try_spawn(&mut world).unwrap();
5018        assert_eq!(map.map(|(old, _)| old), [first, second]);
5019        assert_eq!(map.map(|(_, new)| new.id()), [free.id(), 3]);
5020        assert_eq!(map[0].1.generation(), free.generation() + 1);
5021        assert_eq!(world.get::<&Counted>(map[0].1).unwrap().value, 10);
5022        assert_eq!(world.get::<&Counted>(map[1].1).unwrap().value, 20);
5023        assert_eq!(clones.get(), 1);
5024        assert_eq!(drops.get(), 0);
5025        world.despawn_many(&map.map(|(_, new)| new)).unwrap();
5026        assert_eq!(drops.get(), 1);
5027    }
5028
5029    #[test]
5030    fn last_selected_component_budget_is_required_and_retry_preserves_all_values() {
5031        type Eight = (u8, u16, u32, u64, i8, i16, i32, i64);
5032        let mut world = World::new();
5033        let source = world.spawn((1_u8, 2_u16, 3_u32, 4_u64, 5_i8, 6_i16, 7_i32, 8_i64));
5034        world.prepare_entities(2).unwrap();
5035        macro_rules! prepare {
5036            ($($t:ty),+) => { $(world.prepare_component::<$t>(2).unwrap();)+ };
5037        }
5038        prepare!(u8, u16, u32, u64, i8, i16, i32);
5039        let plan = world.plan_duplication::<Eight, 1>([source]).unwrap();
5040        let (error, plan) = plan.try_spawn(&mut world).unwrap_err();
5041        assert_eq!(
5042            error,
5043            SpawnError::ComponentCapacity {
5044                component: type_name::<i64>(),
5045                required: 2,
5046                prepared: 0,
5047            }
5048        );
5049        assert_eq!(world.len(), 1);
5050        world.prepare_component::<i64>(2).unwrap();
5051        let [(_, copy)] = plan.try_spawn(&mut world).unwrap();
5052        assert_eq!(*world.get::<&u8>(copy).unwrap(), 1);
5053        assert_eq!(*world.get::<&i64>(copy).unwrap(), 8);
5054    }
5055
5056    #[test]
5057    fn cold_and_reused_duplication_keep_prepared_ecs_buffers_and_reset_generations() {
5058        let mut world = World::new();
5059        let sources = [world.spawn((1_i32,)), world.spawn((2_i32,))];
5060        world.prepare_entities(4).unwrap();
5061        world.prepare_component::<i32>(4).unwrap();
5062        // Compare pointers/capacities while allowing entity/free lengths to change.
5063        let mut baseline = buffers::<i32>(&world);
5064        baseline[0] = 0;
5065        baseline[3] = 0;
5066        let mut previous = None;
5067        for _ in 0..64 {
5068            let plan = world.plan_duplication::<(i32,), 2>(sources).unwrap();
5069            let map = plan.try_spawn(&mut world).unwrap();
5070            let copies = map.map(|(_, copy)| copy);
5071            if let Some(old) = previous {
5072                for old in old {
5073                    assert!(!world.contains(old));
5074                }
5075            }
5076            assert_eq!(world.len(), 4);
5077            for (source, copy) in map {
5078                assert_eq!(
5079                    *world.get::<&i32>(source).unwrap(),
5080                    *world.get::<&i32>(copy).unwrap()
5081                );
5082            }
5083            world.despawn_many(&copies).unwrap();
5084            assert_eq!(world.len(), 2);
5085            let mut current = buffers::<i32>(&world);
5086            current[0] = 0;
5087            current[3] = 0;
5088            assert_eq!(current, baseline);
5089            previous = Some(copies);
5090        }
5091        world.despawn_many(&sources).unwrap();
5092        assert!(world.is_empty());
5093        let template = world.spawn((3_i32,));
5094        let plan = world.plan_duplication::<(i32,), 1>([template]).unwrap();
5095        assert!(plan.try_spawn(&mut world).is_ok());
5096        assert_eq!(world.prepared_entity_capacity(), 4);
5097        assert_eq!(world.prepared_component_capacity::<i32>(), 4);
5098        let fresh = World::new();
5099        assert_eq!(fresh.prepared_entity_capacity(), 0);
5100    }
5101
5102    #[test]
5103    fn clone_panic_unwinds_completed_clones_and_releases_every_source_guard() {
5104        #[derive(Debug)]
5105        struct PanicClone;
5106        impl Clone for PanicClone {
5107            fn clone(&self) -> Self {
5108                panic!("user clone failed");
5109            }
5110        }
5111        let mut world = World::new();
5112        let component = counted(7);
5113        let (clones, drops) = (component.clones.clone(), component.drops.clone());
5114        let source = world.spawn((component, PanicClone));
5115        let before = buffers::<Counted>(&world);
5116        let panic = catch_unwind(AssertUnwindSafe(|| {
5117            let _ = world.plan_duplication::<(Counted, PanicClone), 1>([source]);
5118        }));
5119        assert!(panic.is_err());
5120        assert_eq!(clones.get(), 1);
5121        assert_eq!(drops.get(), 1);
5122        assert_eq!(buffers::<Counted>(&world), before);
5123        assert_eq!(world.len(), 1);
5124        assert_eq!(world.get_mut::<Counted>(source).unwrap().value, 7);
5125        assert!(world.get_mut::<PanicClone>(source).is_ok());
5126        drop(world);
5127        assert_eq!(drops.get(), 2);
5128    }
5129
5130    #[test]
5131    fn rejected_plan_retains_panicking_drop_values_until_the_caller_discards_it() {
5132        #[derive(Debug)]
5133        struct PanicDrop {
5134            cloned: bool,
5135            dropped: Rc<Cell<bool>>,
5136        }
5137        impl Clone for PanicDrop {
5138            fn clone(&self) -> Self {
5139                Self {
5140                    cloned: true,
5141                    dropped: self.dropped.clone(),
5142                }
5143            }
5144        }
5145        impl Drop for PanicDrop {
5146            fn drop(&mut self) {
5147                if self.cloned {
5148                    self.dropped.set(true);
5149                    panic!("user drop failed");
5150                }
5151            }
5152        }
5153        let dropped = Rc::new(Cell::new(false));
5154        let mut world = World::new();
5155        let source = world.spawn((PanicDrop {
5156            cloned: false,
5157            dropped: dropped.clone(),
5158        },));
5159        let plan = world.plan_duplication::<(PanicDrop,), 1>([source]).unwrap();
5160        let (error, plan) = plan.try_spawn(&mut world).unwrap_err();
5161        assert_eq!(
5162            error,
5163            SpawnError::EntityCapacity {
5164                required: 2,
5165                prepared: 0
5166            }
5167        );
5168        assert!(!dropped.get());
5169        assert_eq!(world.len(), 1);
5170        let panic = catch_unwind(AssertUnwindSafe(|| drop(plan)));
5171        assert!(panic.is_err());
5172        assert!(dropped.get());
5173        assert!(world.get_mut::<PanicDrop>(source).is_ok());
5174        assert_eq!(world.len(), 1);
5175    }
5176}