flecs_ecs 0.2.0

Rust API for the C/CPP flecs ECS library <https://github.com/SanderMertens/flecs>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
mod id_operations;
mod inout_oper;
mod into_component_id;
mod into_entity;
mod into_id;
mod into_table;
mod query_api;
mod system_api;
mod world_provider;

pub use id_operations::*;
pub use inout_oper::*;
pub use into_component_id::*;
pub use into_entity::*;
pub use into_id::*;
pub use into_table::*;
pub use query_api::*;
pub use system_api::*;
pub use world_provider::*;

use crate::core::{
    ComponentId, ComponentPointers, EntityView, FieldIndex, ImplementsClone, ImplementsDefault,
    ImplementsPartialEq, ImplementsPartialOrd, QueryTuple, TableIter, ecs_assert,
};
#[cfg(feature = "flecs_safety_locks")]
use crate::core::{DECREMENT, INCREMENT, do_read_write_locks};
#[cfg(any(debug_assertions, feature = "flecs_force_enable_ecs_asserts"))]
use crate::core::{FlecsErrorCode, table_lock, table_unlock};
use crate::sys;

#[doc(hidden)]
pub mod private {

    use crate::core::*;
    use crate::sys;
    use core::ffi::c_void;

    #[cfg(feature = "std")]
    extern crate std;

    extern crate alloc;
    use alloc::boxed::Box;
    use flecs_ecs_derive::extern_abi;

    #[allow(non_camel_case_types)]
    #[doc(hidden)]
    pub trait internal_SystemAPI<'a, P, T>
    where
        T: QueryTuple,
        P: ComponentId,
    {
        fn set_callback_binding_context(&mut self, binding_ctx: *mut c_void) -> &mut Self;

        fn set_callback_binding_context_free(
            &mut self,
            binding_ctx_free: sys::ecs_ctx_free_t,
        ) -> &mut Self;

        fn set_run_binding_context(&mut self, binding_ctx: *mut c_void) -> &mut Self;

        fn set_run_binding_context_free(
            &mut self,
            run_ctx_free: flecs_ecs_sys::ecs_ctx_free_t,
        ) -> &mut Self;

        fn desc_binding_context(&self) -> *mut c_void;

        fn set_desc_callback(&mut self, callback: Option<ExternIterFn>);

        fn set_desc_run(&mut self, callback: Option<ExternIterFn>);

        /// Callback of the each functionality
        ///
        /// # Arguments
        ///
        /// * `iter` - The iterator which gets passed in from `C`
        ///
        /// # See also
        #[expect(clippy::not_unsafe_ptr_arg_deref, reason = "iter will always be valid")]
        #[extern_abi]
        fn execute_each<const CALLED_FROM_RUN: bool, Func>(iter: *mut sys::ecs_iter_t)
        where
            Func: FnMut(T::TupleType<'_>),
        {
            unsafe {
                let iter = &mut *iter;
                let each = &mut *(iter.callback_ctx as *mut Func);
                let world = WorldRef::from_ptr(iter.world);
                #[cfg(feature = "flecs_safety_locks")]
                if iter.row_fields == 0 {
                    internal_each_iter_next::<T, CALLED_FROM_RUN, false>(iter, &world, each);
                } else {
                    internal_each_iter_next::<T, CALLED_FROM_RUN, true>(iter, &world, each);
                }

                #[cfg(not(feature = "flecs_safety_locks"))]
                {
                    internal_each_iter_next::<T, CALLED_FROM_RUN, false>(iter, &world, each);
                }
            }
        }

        /// Callback of the `each_entity` functionality
        ///
        /// # Arguments
        ///
        /// * `iter` - The iterator which gets passed in from `C`
        ///
        /// # See also
        #[expect(clippy::not_unsafe_ptr_arg_deref, reason = "iter will always be valid")]
        #[extern_abi]
        fn execute_each_entity<const CALLED_FROM_RUN: bool, Func>(iter: *mut sys::ecs_iter_t)
        where
            Func: FnMut(EntityView, T::TupleType<'_>),
        {
            unsafe {
                let iter = &mut *iter;
                let world = WorldRef::from_ptr(iter.world);
                let each_entity = &mut *(iter.callback_ctx as *mut Func);
                #[cfg(feature = "flecs_safety_locks")]
                if iter.row_fields == 0 {
                    internal_each_entity_iter_next::<T, CALLED_FROM_RUN, false>(
                        iter,
                        &world,
                        each_entity,
                    );
                } else {
                    internal_each_entity_iter_next::<T, CALLED_FROM_RUN, true>(
                        iter,
                        &world,
                        each_entity,
                    );
                }

                #[cfg(not(feature = "flecs_safety_locks"))]
                {
                    internal_each_entity_iter_next::<T, CALLED_FROM_RUN, false>(
                        iter,
                        &world,
                        each_entity,
                    );
                }
            }
        }

        #[expect(clippy::not_unsafe_ptr_arg_deref, reason = "iter will always be valid")]
        #[extern_abi]
        fn execute_each_iter<const CALLED_FROM_RUN: bool, Func>(iter: *mut sys::ecs_iter_t)
        where
            Func: FnMut(TableIter<CALLED_FROM_RUN, P>, FieldIndex, T::TupleType<'_>),
        {
            unsafe {
                let iter = &mut *iter;
                let world = WorldRef::from_ptr(iter.world);
                let each_iter = &mut *(iter.callback_ctx as *mut Func);
                #[cfg(feature = "flecs_safety_locks")]
                if iter.row_fields == 0 {
                    internal_each_iter::<T, P, CALLED_FROM_RUN, false>(iter, &world, each_iter);
                } else {
                    internal_each_iter::<T, P, CALLED_FROM_RUN, true>(iter, &world, each_iter);
                }

                #[cfg(not(feature = "flecs_safety_locks"))]
                {
                    internal_each_iter::<T, P, CALLED_FROM_RUN, false>(iter, &world, each_iter);
                }
            }
        }

        /// Callback of the `iter_only` functionality
        ///
        /// # Arguments
        ///
        /// * `iter` - The iterator which gets passed in from `C`
        ///
        /// # See also
        #[expect(clippy::not_unsafe_ptr_arg_deref, reason = "iter will always be valid")]
        #[extern_abi]
        fn execute_run<Func>(iter: *mut sys::ecs_iter_t)
        where
            Func: FnMut(TableIter<true, P>),
        {
            unsafe {
                let iter = &mut *iter;
                let run = &mut *(iter.run_ctx as *mut Func);
                let world = WorldRef::from_ptr(iter.world);
                internal_run::<P>(iter, run, world);
            }
        }

        #[extern_abi]
        fn free_callback<Func>(ptr: *mut c_void) {
            unsafe {
                drop(Box::from_raw(ptr as *mut Func));
            };
        }

        #[expect(clippy::not_unsafe_ptr_arg_deref, reason = "iter will always be valid")]
        #[extern_abi]
        fn execute_run_each<Func, const CHECKED: bool>(iter: *mut sys::ecs_iter_t)
        where
            Func: FnMut(T::TupleType<'_>),
        {
            unsafe {
                let iter = &mut *iter;
                iter.flags &= !sys::EcsIterIsValid;
                let world = WorldRef::from_ptr(iter.world);
                let each = &mut *(iter.run_ctx as *mut Func);
                let mut table_iter = TableIter::<true, ()>::new(iter, world);

                #[cfg(feature = "flecs_safety_locks")]
                if CHECKED {
                    if table_iter.iter.row_fields == 0 {
                        while table_iter.internal_next() {
                            internal_each_iter_next::<T, true, false>(
                                table_iter.iter,
                                &world,
                                each,
                            );
                        }
                    } else {
                        while table_iter.internal_next() {
                            internal_each_iter_next::<T, true, true>(table_iter.iter, &world, each);
                        }
                    }
                } else {
                    // Unchecked: always use false for sparse terms check
                    while table_iter.internal_next() {
                        internal_each_iter_next::<T, true, false>(table_iter.iter, &world, each);
                    }
                }

                #[cfg(not(feature = "flecs_safety_locks"))]
                {
                    while table_iter.internal_next() {
                        internal_each_iter_next::<T, true, false>(table_iter.iter, &world, each);
                    }
                }
            }
        }

        #[expect(clippy::not_unsafe_ptr_arg_deref, reason = "iter will always be valid")]
        #[extern_abi]
        fn execute_run_each_entity<Func, const CHECKED: bool>(iter: *mut sys::ecs_iter_t)
        where
            Func: FnMut(EntityView, T::TupleType<'_>),
        {
            unsafe {
                let iter = &mut *iter;
                iter.flags &= !sys::EcsIterIsValid;
                let world = WorldRef::from_ptr(iter.world);
                let each_entity = &mut *(iter.run_ctx as *mut Func);
                let mut table_iter = TableIter::<true, ()>::new(iter, world);

                #[cfg(feature = "flecs_safety_locks")]
                if CHECKED {
                    if table_iter.iter.row_fields == 0 {
                        while table_iter.internal_next() {
                            internal_each_entity_iter_next::<T, true, false>(
                                table_iter.iter,
                                &world,
                                each_entity,
                            );
                        }
                    } else {
                        while table_iter.internal_next() {
                            internal_each_entity_iter_next::<T, true, true>(
                                table_iter.iter,
                                &world,
                                each_entity,
                            );
                        }
                    }
                } else {
                    // Unchecked: always use false for sparse terms check
                    while table_iter.internal_next() {
                        internal_each_entity_iter_next::<T, true, false>(
                            table_iter.iter,
                            &world,
                            each_entity,
                        );
                    }
                }

                #[cfg(not(feature = "flecs_safety_locks"))]
                {
                    while table_iter.internal_next() {
                        internal_each_entity_iter_next::<T, true, false>(
                            table_iter.iter,
                            &world,
                            each_entity,
                        );
                    }
                }
            }
        }

        #[expect(
            clippy::not_unsafe_ptr_arg_deref,
            reason = "this doesn't actually deref the pointer"
        )]
        #[extern_abi]
        fn execute_run_each_iter<Func, const CHECKED: bool>(iter: *mut sys::ecs_iter_t)
        where
            Func: FnMut(TableIter<false, P>, FieldIndex, T::TupleType<'_>) + 'static,
        {
            unsafe {
                let iter = &mut *iter;
                iter.flags &= !sys::EcsIterIsValid;
                let world = WorldRef::from_ptr(iter.world);
                let each_iter = &mut *(iter.run_ctx as *mut Func);
                let mut table_iter = TableIter::<true, ()>::new(iter, world);

                #[cfg(feature = "flecs_safety_locks")]
                if CHECKED {
                    if table_iter.iter.row_fields == 0 {
                        while table_iter.internal_next() {
                            internal_each_iter::<T, P, false, false>(
                                table_iter.iter,
                                &world,
                                each_iter,
                            );
                        }
                    } else {
                        while table_iter.internal_next() {
                            internal_each_iter::<T, P, false, true>(
                                table_iter.iter,
                                &world,
                                each_iter,
                            );
                        }
                    }
                } else {
                    // Unchecked: always use false for sparse terms check
                    while table_iter.internal_next() {
                        internal_each_iter::<T, P, false, false>(
                            table_iter.iter,
                            &world,
                            each_iter,
                        );
                    }
                }

                #[cfg(not(feature = "flecs_safety_locks"))]
                {
                    while table_iter.internal_next() {
                        internal_each_iter::<T, P, false, false>(
                            table_iter.iter,
                            &world,
                            each_iter,
                        );
                    }
                }
            }
        }

        // /// Get the binding context
        // fn get_binding_context(&mut self, is_run: bool) -> &mut ReactorBindingType {
        //     let mut binding_ctx: *mut ReactorBindingType = self.desc_binding_context() as *mut _;

        //     if binding_ctx.is_null() {
        //         let new_binding_ctx = Box::<ReactorBindingType>::default();
        //         let static_ref = Box::leak(new_binding_ctx);
        //         binding_ctx = static_ref;
        //         if is_run {
        //             self.set_run_binding_context(binding_ctx as *mut c_void);
        //             self.set_run_binding_context_free(Some(Self::binding_ctx_drop));
        //         } else {
        //             self.set_callback_binding_context(binding_ctx as *mut c_void);
        //             self.set_callback_binding_context_free(Some(Self::binding_ctx_drop));
        //         }
        //     }
        //     unsafe { &mut *binding_ctx }
        // }

        // /// drop the binding context
        // extern "C-unwind" fn binding_ctx_drop(ptr: *mut c_void) {
        //     let ptr_struct: *mut ReactorBindingType = ptr as *mut ReactorBindingType;
        //     unsafe {
        //         ptr::drop_in_place(ptr_struct);
        //     }
        // }
    }

    #[allow(non_camel_case_types)]
    #[doc(hidden)]
    pub trait internal_ParSystemAPI<'a, P, T>: internal_SystemAPI<'a, P, T>
    where
        T: QueryTuple,
        P: ComponentId,
    {
        fn set_multi_threaded(&mut self, multi_threaded: bool);
    }
}

pub trait DoesNotImpl {
    const IMPLS: bool = false;
}

impl<T> DoesNotImpl for T {}

impl<T: Clone> ImplementsClone<T> {
    pub const IMPLS: bool = true;
}

impl<T: Default> ImplementsDefault<T> {
    pub const IMPLS: bool = true;
}

impl<T: PartialEq> ImplementsPartialEq<T> {
    pub const IMPLS: bool = true;
}

impl<T: PartialOrd> ImplementsPartialOrd<T> {
    pub const IMPLS: bool = true;
}

pub trait FlecsConstantId {
    const ID: u64;
}
/// A little “extractor” trait: given the iterator and an index,
/// produce whatever you want to pass as the first argument to the user‑closure.
pub(crate) trait EntityExtractor {
    const CONTAINS_ENTITY: bool;
    /// The type of the “extra” first parameter to the callback.
    type Output;

    /// Called inside the per‑element loop to build that argument.
    unsafe fn extract(&self, iter: &sys::ecs_iter_t, idx: usize) -> Self::Output;
}

/// When you don’t want to pass an entity, use this ZST.
pub(crate) struct NoEntity;
impl EntityExtractor for NoEntity {
    const CONTAINS_ENTITY: bool = false;
    type Output = ();
    #[inline(always)]
    unsafe fn extract(&self, _iter: &sys::ecs_iter_t, _idx: usize) {}
}

/// When you do want an `EntityView`, carry your `&WorldRef` here.
pub(crate) struct WithEntity<'w>(pub &'w WorldRef<'w>);
impl<'w> EntityExtractor for WithEntity<'w> {
    const CONTAINS_ENTITY: bool = true;
    type Output = EntityView<'w>;
    #[inline(always)]
    unsafe fn extract(&self, iter: &sys::ecs_iter_t, idx: usize) -> EntityView<'w> {
        // SAFETY: same as your original
        let raw = unsafe { *iter.entities.add(idx) };
        EntityView::new_from_raw(self.0, raw)
    }
}

#[inline(always)]
pub(crate) fn internal_run<P: ComponentId>(
    iter: &mut sys::ecs_iter_t,
    func: &mut impl FnMut(TableIter<true, P>),
    world: WorldRef<'_>,
) {
    iter.flags &= !sys::EcsIterIsValid;
    let iter_t = unsafe { TableIter::new(iter, world) };
    func(iter_t);
}

#[inline(always)]
fn each_plain<T: QueryTuple, E: EntityExtractor, F: FnMut(E::Output, T::TupleType<'_>)>(
    extractor: &E,
    components_data: &mut <T as QueryTuple>::Pointers,
    iter: &mut sys::ecs_iter_t,
    count: usize,
    func: &mut F,
) {
    // No “ref” or “row” – plain case
    for i in 0..count {
        let extra = unsafe { extractor.extract(iter, i) };
        let tuple = components_data.get_tuple(i);
        func(extra, tuple);
    }
}

#[inline(always)]
fn each_row<T: QueryTuple, E: EntityExtractor, F: FnMut(E::Output, T::TupleType<'_>)>(
    extractor: &E,
    components_data: &mut <T as QueryTuple>::Pointers,
    iter: &mut sys::ecs_iter_t,
    count: usize,
    func: &mut F,
) {
    // “row” case: sparse components
    for i in 0..count {
        let extra = unsafe { extractor.extract(iter, i) };
        let tuple = components_data.get_tuple_with_row(iter, i);
        func(extra, tuple);
    }
}

#[inline(always)]
fn each_ref<T: QueryTuple, E: EntityExtractor, F: FnMut(E::Output, T::TupleType<'_>)>(
    extractor: &E,
    components_data: &mut <T as QueryTuple>::Pointers,
    iter: &mut sys::ecs_iter_t,
    count: usize,
    func: &mut F,
) {
    // “ref” case: singleton and inherited components
    for i in 0..count {
        let extra = unsafe { extractor.extract(iter, i) };
        let tuple = components_data.get_tuple_with_ref(i);
        func(extra, tuple);
    }
}

#[inline(always)]
pub(crate) fn internal_each_generic<
    T: QueryTuple,
    E: EntityExtractor,
    const CALLED_FROM_RUN: bool,
    const ANY_SPARSE_TERMS: bool,
    F: FnMut(E::Output, T::TupleType<'_>),
>(
    iter: &mut sys::ecs_iter_t,
    extractor: E,
    mut func: F,
    _world: &WorldRef<'_>,
) {
    const {
        assert!(
            !T::CONTAINS_ANY_TAG_TERM,
            "a type provided in the query signature is a Tag and cannot be used with \
             `.each`. use `.run` instead or provide the tag with `.with()`"
        );
    }

    // #[cfg(feature = "flecs_safety_locks")]
    // let world = unsafe { WorldRef::from_ptr((iter).world) };
    #[cfg(any(debug_assertions, feature = "flecs_force_enable_ecs_asserts"))]
    let world_ptr = iter.world;
    iter.flags |= sys::EcsIterCppEach;
    let (is_any_array, mut components_data) = T::create_ptrs(iter);
    let count = if iter.count == 0 && iter.table.is_null() {
        1_usize
    } else {
        iter.count as usize
    };

    ecs_assert!(
        !(E::CONTAINS_ENTITY && iter.entities.is_null()),
        FlecsErrorCode::InvalidOperation,
        "query/system does not return entities ($this variable is not populated).\nSystem: {:?}",
        {
            let e = _world.entity_from_id(iter.system);
            (e.id(), e.get_name())
        }
    );

    #[cfg(feature = "flecs_safety_locks")]
    do_read_write_locks::<INCREMENT, ANY_SPARSE_TERMS, T>(
        _world,
        components_data.safety_table_records(),
    );

    // only lock/unlock in debug or forced‑assert builds, and only
    // if we’re not in the “called from run” path:
    #[cfg(any(debug_assertions, feature = "flecs_force_enable_ecs_asserts"))]
    if !CALLED_FROM_RUN {
        table_lock(world_ptr, iter.table);
    }

    if !is_any_array.a_ref && !is_any_array.a_row {
        each_plain::<T, E, F>(&extractor, &mut components_data, iter, count, &mut func);
    } else if is_any_array.a_row {
        each_row::<T, E, F>(&extractor, &mut components_data, iter, count, &mut func);
    } else {
        each_ref::<T, E, F>(&extractor, &mut components_data, iter, count, &mut func);
    }

    #[cfg(any(debug_assertions, feature = "flecs_force_enable_ecs_asserts"))]
    if !CALLED_FROM_RUN {
        table_unlock(world_ptr, iter.table);
    }

    #[cfg(feature = "flecs_safety_locks")]
    do_read_write_locks::<DECREMENT, ANY_SPARSE_TERMS, T>(
        _world,
        components_data.safety_table_records(),
    );
}

#[inline(always)]
pub(crate) fn internal_each_iter_next<
    T: QueryTuple,
    const CALLED_FROM_RUN: bool,
    const ANY_SPARSE_TERMS: bool,
>(
    iter: &mut sys::ecs_iter_t,
    world: &WorldRef<'_>,
    func: &mut impl FnMut(T::TupleType<'_>),
) {
    // drop the `()` from the call
    internal_each_generic::<T, NoEntity, CALLED_FROM_RUN, ANY_SPARSE_TERMS, _>(
        iter,
        NoEntity,
        move |(), t| func(t),
        world,
    );
}

#[inline(always)]
pub(crate) fn internal_each_entity_iter_next<
    T: QueryTuple,
    const CALLED_FROM_RUN: bool,
    const ANY_SPARSE_TERMS: bool,
>(
    iter: &mut sys::ecs_iter_t,
    world: &WorldRef<'_>,
    func: &mut impl FnMut(EntityView, T::TupleType<'_>),
) {
    // pass a WithEntity extractor so it builds the EntityView
    let extractor = WithEntity(world);
    internal_each_generic::<T, WithEntity<'_>, CALLED_FROM_RUN, ANY_SPARSE_TERMS, _>(
        iter, extractor, func, world,
    );
}

#[inline(always)]
pub(crate) fn internal_each_iter<
    T: QueryTuple,
    P: ComponentId,
    const CALLED_FROM_RUN: bool,
    const ANY_SPARSE_TERMS: bool,
>(
    iter: &mut sys::ecs_iter_t,
    world: &WorldRef<'_>,
    func: &mut impl FnMut(TableIter<CALLED_FROM_RUN, P>, FieldIndex, T::TupleType<'_>),
) {
    const {
        assert!(
            !T::CONTAINS_ANY_TAG_TERM,
            "a type provided in the query signature is a Tag and cannot be used with `.each`. use `.run` instead or provide the tag with `.with()`"
        );
    }

    unsafe {
        #[cfg(any(debug_assertions, feature = "flecs_force_enable_ecs_asserts"))]
        let world_ptr = iter.world;
        iter.flags |= sys::EcsIterCppEach;
        let (is_any_array, mut components_data) = T::create_ptrs(iter);
        let count = if iter.count == 0 && iter.table.is_null() {
            1_usize
        } else {
            iter.count as usize
        };

        #[cfg(feature = "flecs_safety_locks")]
        do_read_write_locks::<INCREMENT, ANY_SPARSE_TERMS, T>(
            world,
            components_data.safety_table_records(),
        );

        // only lock/unlock in debug or forced‑assert builds, and only
        // if we’re not in the “called from run” path:
        #[cfg(any(debug_assertions, feature = "flecs_force_enable_ecs_asserts"))]
        if !CALLED_FROM_RUN {
            table_lock(world_ptr, iter.table);
        }

        if !is_any_array.a_ref && !is_any_array.a_row {
            for i in 0..count {
                let tuple = components_data.get_tuple(i);
                let iter_t = TableIter::new(iter, *world);
                func(iter_t, FieldIndex(i), tuple);
            }
        } else if is_any_array.a_row {
            for i in 0..count {
                let tuple = components_data.get_tuple_with_row(iter, i);
                let iter_t = TableIter::new(iter, *world);
                func(iter_t, FieldIndex(i), tuple);
            }
        } else {
            for i in 0..count {
                let tuple = components_data.get_tuple_with_ref(i);
                let iter_t = TableIter::new(iter, *world);
                func(iter_t, FieldIndex(i), tuple);
            }
        }

        #[cfg(any(debug_assertions, feature = "flecs_force_enable_ecs_asserts"))]
        if !CALLED_FROM_RUN {
            table_unlock(world_ptr, iter.table);
        }

        #[cfg(feature = "flecs_safety_locks")]
        do_read_write_locks::<DECREMENT, ANY_SPARSE_TERMS, T>(
            world,
            components_data.safety_table_records(),
        );
    }
}