flecs_ecs 0.2.2

Rust API for the C/CPP flecs ECS library <https://github.com/SanderMertens/flecs>
Documentation
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
use core::{
    ffi::CStr,
    sync::atomic::{AtomicU32, Ordering},
};

use crate::core::*;
use crate::sys;

use hashbrown::hash_map::Entry;

/// A marker trait to indicate that a component represents a trait
#[cfg(feature = "flecs_query_rust_traits")]
pub trait RustTrait {}

/// Indicates that the type is a tag component. A tag component is a component that does not have any data. Is a zero-sized type.
pub trait TagComponent {}

#[doc(hidden)]
impl<T, U> TagComponent for (T, U)
where
    T: TagComponent,
    U: TagComponent,
{
}

#[diagnostic::on_unimplemented(
    message = "the size of type `{Self}` should not be zero, should not be a tag.",
    label = "Supports only non-empty components"
)]
/// Indicates that the type is a non-tag component. A non-tag component contains data, is not a zero-sized type.
pub trait DataComponent {}

#[doc(hidden)]
impl<T> DataComponent for &T where T: DataComponent {}
#[doc(hidden)]
impl<T> DataComponent for &mut T where T: DataComponent {}
#[doc(hidden)]
impl<T> DataComponent for Option<&T> where T: DataComponent {}
#[doc(hidden)]
impl<T> DataComponent for Option<&mut T> where T: DataComponent {}
#[doc(hidden)]
impl<T, U> DataComponent for (T, U)
where
    T: ComponentId,
    U: ComponentId,
    (T, U): ComponentOrPairId,
    <(T, U) as ComponentOrPairId>::CastType: DataComponent,
    registration_types::ConditionalTypePairSelector<
        <<(T, U) as ComponentOrPairId>::First as ComponentInfo>::TagType,
        T,
        U,
    >: FlecsPairType,
{
}

/// Indicates what component types are supported by the ECS.
pub trait ECSComponentType {}

impl ECSComponentType for Enum {}
impl ECSComponentType for Struct {}

/// Indicates what the type of the component is.
pub trait ComponentType<T: ECSComponentType> {}

#[doc(hidden)]
impl<T> ComponentType<Enum> for &T where T: ComponentType<Enum> {}
#[doc(hidden)]
impl<T> ComponentType<Enum> for &mut T where T: ComponentType<Enum> {}

fn try_register_component<'a, const MANUAL_REGISTRATION_CHECK: bool, T>(
    world: impl WorldProvider<'a>,
) -> sys::ecs_entity_t
where
    T: ComponentId,
{
    use crate::core::component_registration::registration;
    // when a component is registered through [`Component`], manual registration check is set to false
    // thus for `try_register_component` we set the flag that it uses const component_registration to true
    if MANUAL_REGISTRATION_CHECK {
        registration::try_register_component::<false, T>(world)
    } else {
        registration::try_register_component::<true, T>(world)
    }
}

fn try_register_component_named<'a, const MANUAL_REGISTRATION_CHECK: bool, T>(
    world: impl WorldProvider<'a>,
    name: &str,
) -> sys::ecs_entity_t
where
    T: ComponentId,
{
    use crate::core::component_registration::registration;
    // when a component is registered through [`Component`], manual registration check is set to false
    // thus for `try_register_component` we set the flag that it uses const component_registration to true
    if MANUAL_REGISTRATION_CHECK {
        registration::try_register_component_named::<false, T>(world, name)
    } else {
        registration::try_register_component_named::<true, T>(world, name)
    }
}

#[doc(hidden)]
pub trait InternalComponentHooks {
    fn internal_pre_registration_name() -> Option<&'static str> {
        None
    }

    fn internal_on_component_registration(_world: WorldRef, _component_id: Entity) {}
}

/// A trait that holds a fn `on_component_registration`. This automatically gets implemented
/// on types with the `Component` derive macro, unless the attribute `flecs(on_registration)` is used.
/// When it is used, the user can specify what should happen when a component is registered.
///
/// # See also
/// * [`component_macro`](crate::component_macro) documentation for examples and more info
pub trait OnComponentRegistration: InternalComponentHooks {
    /// This function is called when a component is first registered.
    /// Implementing it allows for custom injectable code to be executed on component registration
    fn on_component_registration(_world: WorldRef, _component_id: Entity) {}
}

/// Trait that manages component IDs across multiple worlds & binaries.
///
/// proc macro Component should be used to implement this trait automatically
///
/// ```
/// # use flecs_ecs::prelude::Component;
/// #[derive(Component)] //this will implement the trait for the type
/// struct Position {
///     vec: Vec<i32>,
/// }
/// ```
///
/// The `ComponentId` trait is designed to maintain component IDs for a Rust type
/// in a manner that is consistent across different worlds (or instances).
/// When a component is utilized, this trait will determine whether it has already been registered.
/// If it hasn't, it registers the component with the current world.
///
/// If the ID has been previously established, the trait ensures the world recognizes it.
/// If the world doesn't, this implies the component was registered by a different world.
/// In such a case, the component is registered with the present world using the pre-existing ID.
/// If the ID is already known, the trait takes care of the component registration and checks for consistency in the input.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a flecs component.",
    label = "use `#[derive(Component)]` on `{Self}` to mark it as one."
)]
pub trait ComponentId:
    Sized + ComponentInfo + 'static + Send + Sync + OnComponentRegistration
{
    #[doc(hidden)]
    type UnderlyingType: ComponentId;
    #[doc(hidden)]
    type UnderlyingEnumType: ComponentId + EnumComponentInfo;
    #[doc(hidden)]
    type UnderlyingTypeOfEnum: ComponentId + Copy;

    /// attempts to register the component with the world. If it's already registered, it does nothing.
    #[doc(hidden)]
    #[inline(always)]
    fn __register_or_get_id<'a, const MANUAL_REGISTRATION_CHECK: bool>(
        world: impl WorldProvider<'a>,
    ) -> sys::ecs_entity_t {
        if !Self::IS_GENERIC {
            let index = Self::index() as usize;
            let world = world.world();
            let components_array = world.components_array();
            let len = components_array.len();

            if len > index {
                let component_id = components_array[index];
                if component_id == 0 || !world.is_alive(component_id) {
                    if MANUAL_REGISTRATION_CHECK {
                        #[cfg(feature = "flecs_manual_registration")]
                        {
                            ecs_assert!(
                                false,
                                FlecsErrorCode::InvalidOperation,
                                "Component {} is not registered with the world before usage",
                                Self::name()
                            );
                        }
                    }

                    let id = if let Some(name) = Self::internal_pre_registration_name() {
                        try_register_component_named::<MANUAL_REGISTRATION_CHECK, Self>(world, name)
                    } else {
                        try_register_component::<MANUAL_REGISTRATION_CHECK, Self>(world)
                    };

                    components_array[index] = id;
                    #[cfg(feature = "flecs_meta")]
                    {
                        world
                            .components_map()
                            .insert(core::any::TypeId::of::<Self>(), id);
                    }

                    Self::internal_on_component_registration(world, Entity::new(id));

                    return id;
                }
                components_array[index]
            } else {
                components_array.reserve(len);
                let capacity = components_array.capacity();
                unsafe {
                    core::ptr::write_bytes(
                        components_array.as_mut_ptr().add(len),
                        0,
                        capacity - len,
                    );
                    components_array.set_len(capacity);
                }

                let id = if let Some(name) = Self::internal_pre_registration_name() {
                    try_register_component_named::<MANUAL_REGISTRATION_CHECK, Self>(world, name)
                } else {
                    try_register_component::<MANUAL_REGISTRATION_CHECK, Self>(world)
                };

                components_array[index] = id;

                Self::internal_on_component_registration(world, Entity::new(id));

                id
            }
        } else {
            let world = world.world();
            let components_map = world.components_map();

            match components_map.entry(core::any::TypeId::of::<Self>()) {
                Entry::Occupied(mut entry) => {
                    if !world.is_alive(*entry.get()) {
                        if MANUAL_REGISTRATION_CHECK {
                            #[cfg(feature = "flecs_manual_registration")]
                            {
                                ecs_assert!(
                                    false,
                                    FlecsErrorCode::InvalidOperation,
                                    "Component {} is not registered with the world before usage",
                                    Self::name()
                                );
                            }
                        }

                        let id = if let Some(name) = Self::internal_pre_registration_name() {
                            try_register_component_named::<MANUAL_REGISTRATION_CHECK, Self>(
                                world, name,
                            )
                        } else {
                            try_register_component::<MANUAL_REGISTRATION_CHECK, Self>(world)
                        };

                        let id = entry.insert(id);

                        Self::internal_on_component_registration(world, Entity::new(id));
                        id
                    } else {
                        *entry.into_mut()
                    }
                }
                Entry::Vacant(entry) => {
                    if MANUAL_REGISTRATION_CHECK {
                        #[cfg(feature = "flecs_manual_registration")]
                        {
                            ecs_assert!(
                                false,
                                FlecsErrorCode::InvalidOperation,
                                "Component {} is not registered with the world before usage",
                                Self::name()
                            );
                        }
                    }

                    let id = if let Some(name) = Self::internal_pre_registration_name() {
                        try_register_component_named::<MANUAL_REGISTRATION_CHECK, Self>(world, name)
                    } else {
                        try_register_component::<MANUAL_REGISTRATION_CHECK, Self>(world)
                    };

                    let id = entry.insert(id);

                    Self::internal_on_component_registration(world, Entity::new(*id));
                    *id
                }
            }
        }
    }

    /// attempts to register the component with name with the world. If it's already registered, it does nothing.
    #[inline(always)]
    #[doc(hidden)]
    fn __register_or_get_id_named<'a, const MANUAL_REGISTRATION_CHECK: bool>(
        world: impl WorldProvider<'a>,
        name: &str,
    ) -> sys::ecs_entity_t {
        if !Self::IS_GENERIC {
            let index = Self::index() as usize;
            let world = world.world();
            let components_array = world.components_array();
            let len = components_array.len();

            if len > index {
                let component_id = components_array[index];
                if components_array[index] == 0 || !world.is_alive(component_id) {
                    if MANUAL_REGISTRATION_CHECK {
                        #[cfg(feature = "flecs_manual_registration")]
                        {
                            ecs_assert!(
                                false,
                                FlecsErrorCode::InvalidOperation,
                                "Component {} is not registered with the world before usage",
                                Self::name()
                            );
                        }
                    }

                    let id = try_register_component_named::<MANUAL_REGISTRATION_CHECK, Self>(
                        world, name,
                    );

                    components_array[index] = id;

                    #[cfg(feature = "flecs_meta")]
                    {
                        world
                            .components_map()
                            .insert(core::any::TypeId::of::<Self>(), id);
                    }

                    Self::internal_on_component_registration(world, Entity::new(id));

                    return id;
                }
                components_array[index]
            } else {
                components_array.reserve(len);
                let capacity = components_array.capacity();
                unsafe {
                    core::ptr::write_bytes(
                        components_array.as_mut_ptr().add(len),
                        0,
                        capacity - len,
                    );
                    components_array.set_len(capacity);
                }
                let id =
                    try_register_component_named::<MANUAL_REGISTRATION_CHECK, Self>(world, name);

                components_array[index] = id;

                Self::internal_on_component_registration(world, Entity::new(id));

                id
            }
        } else {
            let world = world.world();
            let components_map = world.components_map();

            match components_map.entry(core::any::TypeId::of::<Self>()) {
                Entry::Occupied(mut entry) => {
                    if !world.is_alive(*entry.get()) {
                        if MANUAL_REGISTRATION_CHECK {
                            #[cfg(feature = "flecs_manual_registration")]
                            {
                                ecs_assert!(
                                    false,
                                    FlecsErrorCode::InvalidOperation,
                                    "Component {} is not registered with the world before usage",
                                    Self::name()
                                );
                            }
                        }

                        let id = try_register_component_named::<MANUAL_REGISTRATION_CHECK, Self>(
                            world, name,
                        );

                        let id = entry.insert(id);

                        Self::internal_on_component_registration(world, Entity::new(id));
                        id
                    } else {
                        *entry.into_mut()
                    }
                }
                Entry::Vacant(entry) => {
                    if MANUAL_REGISTRATION_CHECK {
                        #[cfg(feature = "flecs_manual_registration")]
                        {
                            ecs_assert!(
                                false,
                                FlecsErrorCode::InvalidOperation,
                                "Component {} is not registered with the world before usage",
                                Self::name()
                            );
                        }
                    }

                    let id = try_register_component_named::<MANUAL_REGISTRATION_CHECK, Self>(
                        world, name,
                    );

                    let id = entry.insert(id);

                    Self::internal_on_component_registration(world, Entity::new(*id));
                    *id
                }
            }
        }
    }

    /// checks if the component is registered with a world.
    #[inline(always)]
    fn is_registered_with_world<'a>(world: impl WorldProvider<'a>) -> bool {
        if !Self::IS_GENERIC {
            let index = Self::index();
            let world = world.world();
            let components_array = world.components_array();
            let len = components_array.len();

            if len > index as usize {
                components_array[index as usize] != 0
            } else {
                false
            }
        } else {
            let world = world.world();
            let components_map = world.components_map();
            components_map.contains_key(&core::any::TypeId::of::<Self>())
        }
    }

    /// utility function to returning an Id object which is used for fn's that take `IntoEntity` or `IntoId` variable
    #[inline(always)]
    fn id() -> utility::id::Id<Self> {
        utility::id::Id::<Self>::new()
    }

    /// returns the component id registered with a particular world. If the component is not registered, it will register it.
    /// # Note
    /// Each world has it's own unique id for the component.
    #[inline(always)]
    fn entity_id<'a>(world: impl WorldProvider<'a>) -> sys::ecs_entity_t {
        Self::UnderlyingType::__register_or_get_id::<true>(world)
    }

    // Not public API.
    #[doc(hidden)]
    fn __register_lifecycle_hooks(_type_hooks: &mut sys::ecs_type_hooks_t) {}

    // Not public API.
    #[doc(hidden)]
    fn __register_default_hooks(_type_hooks: &mut sys::ecs_type_hooks_t) {}

    // Not public API.
    #[doc(hidden)]
    fn __register_clone_hooks(_type_hooks: &mut sys::ecs_type_hooks_t) {}

    // Not public API.
    #[doc(hidden)]
    fn __register_compare_hooks(_type_hooks: &mut sys::ecs_type_hooks_t) {}

    // Not public API.
    #[doc(hidden)]
    fn __register_equals_hooks(_type_hooks: &mut sys::ecs_type_hooks_t) {}

    fn register_ctor_hook<'a>(world: impl WorldProvider<'a>)
    where
        Self: Default,
    {
        ecs_assert!(
            Self::IS_GENERIC,
            FlecsErrorCode::InvalidOperation,
            "There is no need to register default hooks for non generic components. This is done automatically if a type has Default implemented"
        );
        let world_ptr = world.world_ptr_mut();
        let id = Self::entity_id(world);
        let hooks = unsafe { flecs_ecs_sys::ecs_get_hooks_id(world_ptr, id) };
        if hooks.is_null() {
            let mut hooks = Default::default();
            register_ctor_lifecycle_actions::<Self>(&mut hooks);
            unsafe { flecs_ecs_sys::ecs_set_hooks_id(world_ptr, id, &hooks) }
        } else {
            let hooks = &mut unsafe { *hooks };
            register_ctor_lifecycle_actions::<Self>(hooks);
            unsafe { flecs_ecs_sys::ecs_set_hooks_id(world_ptr, id, hooks) }
        }
    }

    fn register_clone_hook<'a>(world: impl WorldProvider<'a>)
    where
        Self: Clone,
    {
        ecs_assert!(
            Self::IS_GENERIC,
            FlecsErrorCode::InvalidOperation,
            "There is no need to register clone hooks for non generic components. This is done automatically if a type has Clone implemented"
        );
        let world_ptr = world.world_ptr_mut();
        let id = Self::entity_id(world);
        let hooks = unsafe { flecs_ecs_sys::ecs_get_hooks_id(world_ptr, id) };
        if hooks.is_null() {
            let mut hooks = Default::default();
            register_copy_lifecycle_action::<Self>(&mut hooks);
            unsafe { flecs_ecs_sys::ecs_set_hooks_id(world_ptr, id, &hooks) }
        } else {
            let hooks = &mut unsafe { *hooks };
            register_copy_lifecycle_action::<Self>(hooks);
            unsafe { flecs_ecs_sys::ecs_set_hooks_id(world_ptr, id, hooks) }
        }
    }

    fn register_compare_hook<'a>(world: impl WorldProvider<'a>)
    where
        Self: PartialOrd,
    {
        ecs_assert!(
            Self::IS_GENERIC,
            FlecsErrorCode::InvalidOperation,
            "There is no need to register compare hooks for non generic components. This is done automatically if a type has PartialEq implemented"
        );
        let world_ptr = world.world_ptr_mut();
        let id = Self::entity_id(world);
        let hooks = unsafe { flecs_ecs_sys::ecs_get_hooks_id(world_ptr, id) };
        if hooks.is_null() {
            let mut hooks = Default::default();
            register_partial_ord_lifecycle_action::<Self>(&mut hooks);
            unsafe { flecs_ecs_sys::ecs_set_hooks_id(world_ptr, id, &hooks) }
        } else {
            let hooks = &mut unsafe { *hooks };
            register_partial_ord_lifecycle_action::<Self>(hooks);
            unsafe { flecs_ecs_sys::ecs_set_hooks_id(world_ptr, id, hooks) }
        }
    }

    fn register_equals_hook<'a>(world: impl WorldProvider<'a>)
    where
        Self: PartialEq,
    {
        ecs_assert!(
            Self::IS_GENERIC,
            FlecsErrorCode::InvalidOperation,
            "There is no need to register equals hooks for non generic components. This is done automatically if a type has PartialEq implemented"
        );
        let world_ptr = world.world_ptr_mut();
        let id = Self::entity_id(world);
        let hooks = unsafe { flecs_ecs_sys::ecs_get_hooks_id(world_ptr, id) };
        if hooks.is_null() {
            let mut hooks = Default::default();
            register_partial_eq_lifecycle_action::<Self>(&mut hooks);
            unsafe { flecs_ecs_sys::ecs_set_hooks_id(world_ptr, id, &hooks) }
        } else {
            let hooks = &mut unsafe { *hooks };
            register_partial_eq_lifecycle_action::<Self>(hooks);
            unsafe { flecs_ecs_sys::ecs_set_hooks_id(world_ptr, id, hooks) }
        }
    }

    #[doc(hidden)]
    #[inline(always)]
    fn fetch_new_index() -> u32 {
        static INDEX_POOL: AtomicU32 = AtomicU32::new(1);
        INDEX_POOL.fetch_add(1, Ordering::Relaxed)
    }

    #[doc(hidden)]
    #[inline(always)]
    fn get_or_init_index(id: &AtomicU32) -> u32 {
        match id.fetch_update(Ordering::Acquire, Ordering::Relaxed, |v| {
            if v != u32::MAX {
                None
            } else {
                Some(Self::fetch_new_index())
            }
        }) {
            Ok(_) => id.load(Ordering::Acquire),
            Err(old) => old,
        }
    }

    #[doc(hidden)]
    fn index() -> u32;
}

/// Component information trait.
pub trait ComponentInfo: Sized {
    const IS_GENERIC: bool;
    const IS_ENUM: bool;
    const IS_TAG: bool;
    const NEEDS_DROP: bool = core::mem::needs_drop::<Self>();
    const IMPLS_CLONE: bool;
    const IMPLS_DEFAULT: bool;
    const IMPLS_PARTIAL_ORD: bool;
    const IMPLS_PARTIAL_EQ: bool;
    #[doc(hidden)]
    const IS_REF: bool;
    #[doc(hidden)]
    const IS_MUT: bool;
    #[doc(hidden)]
    type TagType;
}

/// Caches the ids, index and name of the enum variants.
pub trait EnumComponentInfo: ComponentType<Enum> + ComponentId {
    const SIZE_ENUM_FIELDS: u32;
    type VariantIterator: Iterator<Item = Self>;

    /// # Note
    /// this function is used to pass the name to the C API.
    fn name_cstr(&self) -> &CStr;

    fn enum_index(&self) -> usize;

    fn iter() -> Self::VariantIterator;

    /// # Note
    /// it only means that the enum is registered with a particular world, not necessarily yours.
    fn are_fields_registered_as_entities() -> bool {
        let mut result = true;
        let ptr = Self::__enum_data_mut();
        for i in 0..Self::SIZE_ENUM_FIELDS {
            unsafe {
                if *ptr.add(i as usize) == 0 {
                    result = false;
                    break;
                }
            }
        }
        result
    }

    fn is_field_registered_as_entity(&self) -> bool {
        let index = self.enum_index();
        unsafe { *Self::__enum_data_mut().add(index) != 0 }
    }

    fn is_index_registered_as_entity(index: usize) -> bool {
        unsafe { *Self::__enum_data_mut().add(index) != 0 }
    }

    /// get the entity id of the variant of the enum. This function will register the enum with the world if it's not registered.
    fn id_variant<'a>(&self, world: impl WorldProvider<'a>) -> EntityView<'a> {
        use crate::core::component_registration::registration;
        let world = world.world();
        if !<Self as ComponentId>::is_registered_with_world(world) {
            const COMPONENT_REGISTRATION: bool = false;
            registration::try_register_component::<COMPONENT_REGISTRATION, Self>(world);
        }
        let index = self.enum_index();
        EntityView::new_from(world, unsafe { *Self::__enum_data_mut().add(index) })
    }

    /// # Safety
    ///
    /// This function is unsafe because it assumes the enum has been registered as a component with the world.
    /// if uncertain, use `try_register_component::<T>` to try and register it
    unsafe fn id_variant_unchecked<'a>(&self, world: impl WorldProvider<'a>) -> EntityView<'a> {
        let index = self.enum_index();
        EntityView::new_from(world, unsafe { *Self::__enum_data_mut().add(index) })
    }

    fn id_variant_of_index(index: usize) -> Option<u64> {
        if index < Self::SIZE_ENUM_FIELDS as usize {
            Some(unsafe { *Self::__enum_data_mut().add(index) })
        } else {
            None
        }
    }

    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer and you must ensure that the
    /// index is within the bounds of the number of variants in the enum.
    /// if uncertain, use `SIZE_ENUM_FIELDS` to check the number of variants.
    unsafe fn id_variant_of_index_unchecked(index: usize) -> u64 {
        unsafe { *Self::__enum_data_mut().add(index) }
    }

    #[doc(hidden)]
    fn __enum_data_mut() -> *mut u64;
}

#[doc(hidden)]
impl<T: ComponentInfo> ComponentInfo for &T {
    const IS_GENERIC: bool = T::IS_GENERIC;
    const IS_ENUM: bool = T::IS_ENUM;
    const IS_TAG: bool = T::IS_TAG;
    const IMPLS_CLONE: bool = T::IMPLS_CLONE;
    const IMPLS_DEFAULT: bool = T::IMPLS_DEFAULT;
    const IMPLS_PARTIAL_ORD: bool = T::IMPLS_PARTIAL_ORD;
    const IMPLS_PARTIAL_EQ: bool = T::IMPLS_PARTIAL_EQ;
    const IS_REF: bool = true;
    const IS_MUT: bool = false;
    type TagType = T::TagType;
}

#[doc(hidden)]
impl<T: ComponentInfo> ComponentInfo for &mut T {
    const IS_GENERIC: bool = T::IS_GENERIC;
    const IS_ENUM: bool = T::IS_ENUM;
    const IS_TAG: bool = T::IS_TAG;
    const IMPLS_CLONE: bool = T::IMPLS_CLONE;
    const IMPLS_DEFAULT: bool = T::IMPLS_DEFAULT;
    const IMPLS_PARTIAL_ORD: bool = T::IMPLS_PARTIAL_ORD;
    const IMPLS_PARTIAL_EQ: bool = T::IMPLS_PARTIAL_EQ;
    const IS_REF: bool = false;
    const IS_MUT: bool = true;
    type TagType = T::TagType;
}

#[doc(hidden)]
impl<T: InternalComponentHooks> InternalComponentHooks for &T {
    fn internal_on_component_registration(world: WorldRef, component_id: Entity) {
        T::internal_on_component_registration(world, component_id);
    }
}

#[doc(hidden)]
impl<T: OnComponentRegistration> OnComponentRegistration for &T {
    fn on_component_registration(world: WorldRef, component_id: Entity) {
        T::on_component_registration(world, component_id);
    }
}

#[doc(hidden)]
impl<T: InternalComponentHooks> InternalComponentHooks for &mut T {
    fn internal_on_component_registration(world: WorldRef, component_id: Entity) {
        T::internal_on_component_registration(world, component_id);
    }
}

#[doc(hidden)]
impl<T: OnComponentRegistration> OnComponentRegistration for &mut T {
    fn on_component_registration(world: WorldRef, component_id: Entity) {
        T::on_component_registration(world, component_id);
    }
}

#[doc(hidden)]
impl<T: ComponentId> ComponentId for &'static T {
    #[inline(always)]
    fn index() -> u32 {
        T::UnderlyingType::index()
    }

    type UnderlyingType = T::UnderlyingType;
    type UnderlyingEnumType = T::UnderlyingEnumType;
    type UnderlyingTypeOfEnum = T::UnderlyingTypeOfEnum;
}

#[doc(hidden)]
impl<T: ComponentId> ComponentId for &'static mut T {
    #[inline(always)]
    fn index() -> u32 {
        T::UnderlyingType::index()
    }

    type UnderlyingType = T::UnderlyingType;
    type UnderlyingEnumType = T::UnderlyingEnumType;
    type UnderlyingTypeOfEnum = T::UnderlyingTypeOfEnum;
}

#[doc(hidden)]
pub trait FlecsDefaultType {
    #[doc(hidden)]
    type Type: Default;
}

#[doc(hidden)]
pub trait FlecsCloneType {
    type Type: Clone;
}

#[doc(hidden)]
pub trait FlecsPartialEqType {
    type Type: PartialEq;
}

#[doc(hidden)]
pub trait FlecsPartialOrdType {
    type Type: PartialOrd;
}

#[doc(hidden)]
pub trait FlecsPairType {
    type Type: ComponentId;
    const IS_FIRST: bool;
}

#[doc(hidden)]
pub trait FlecsCachedRefPairType {
    type Type;
}

#[doc(hidden)]
impl<T> FlecsDefaultType for ConditionalTypeSelector<false, T> {
    type Type = FlecsNoneDefaultDummy;
}

#[doc(hidden)]
impl<T> FlecsDefaultType for ConditionalTypeSelector<true, T>
where
    T: Default,
{
    type Type = T;
}

#[doc(hidden)]
impl<T> FlecsCloneType for ConditionalTypeSelector<false, T> {
    type Type = FlecsNoneCloneDummy;
}

#[doc(hidden)]
impl<T> FlecsCloneType for ConditionalTypeSelector<true, T>
where
    T: Clone,
{
    type Type = T;
}

#[doc(hidden)]
impl<T> FlecsPartialEqType for ConditionalTypeSelector<false, T> {
    type Type = FlecsNonePartialEqDummy;
}

#[doc(hidden)]
impl<T> FlecsPartialEqType for ConditionalTypeSelector<true, T>
where
    T: PartialEq,
{
    type Type = T;
}

#[doc(hidden)]
impl<T> FlecsPartialOrdType for ConditionalTypeSelector<false, T> {
    type Type = FlecsNonePartialOrdDummy;
}

#[doc(hidden)]
impl<T> FlecsPartialOrdType for ConditionalTypeSelector<true, T>
where
    T: PartialOrd,
{
    type Type = T;
}

#[doc(hidden)]
pub struct FlecsIsATag;
#[doc(hidden)]
pub struct FlecsNotATag;

#[doc(hidden)]
pub struct FlecsIsTyped;

#[doc(hidden)]
pub struct FlecsIsNotTyped;

#[doc(hidden)]
impl<T, U> FlecsPairType for ConditionalTypePairSelector<FlecsNotATag, T, U>
where
    T: ComponentId,
    U: ComponentId,
{
    type Type = T;
    const IS_FIRST: bool = true;
}

#[doc(hidden)]
impl<T, U> FlecsPairType for ConditionalTypePairSelector<FlecsIsATag, T, U>
where
    T: ComponentId,
    U: ComponentId,
{
    type Type = U;
    const IS_FIRST: bool = false;
}

#[doc(hidden)]
impl<IsFirstTyped, IsSecondTyped, T, U> FlecsCachedRefPairType
    for ConditionalCachedRefTypeSelector<
        IsFirstTyped,
        IsSecondTyped,
        FlecsIsATag,
        FlecsIsATag,
        T,
        U,
    >
where
    T: InternalIntoEntity,
    U: InternalIntoEntity,
{
    type Type = core::ffi::c_void;
}

#[doc(hidden)]
impl<IsFirstTyped, IsSecondTyped, IsSecondATag, T, U> FlecsCachedRefPairType
    for ConditionalCachedRefTypeSelector<
        IsFirstTyped,
        IsSecondTyped,
        FlecsNotATag,
        IsSecondATag,
        T,
        U,
    >
where
    T: InternalIntoEntity,
    U: InternalIntoEntity,
{
    type Type = T::CastType;
}

#[doc(hidden)]
impl<IsSecondTyped, T, U> FlecsCachedRefPairType
    for ConditionalCachedRefTypeSelector<
        FlecsIsNotTyped,
        IsSecondTyped,
        FlecsIsATag,
        FlecsNotATag,
        T,
        U,
    >
where
    T: InternalIntoEntity,
    U: InternalIntoEntity,
{
    type Type = core::ffi::c_void;
}

#[doc(hidden)]
impl<IsSecondTyped, T, U> FlecsCachedRefPairType
    for ConditionalCachedRefTypeSelector<
        FlecsIsTyped,
        IsSecondTyped,
        FlecsIsATag,
        FlecsNotATag,
        T,
        U,
    >
where
    T: InternalIntoEntity,
    U: InternalIntoEntity,
{
    type Type = U::CastType;
}

// #[doc(hidden)]
// impl<IsSecondTyped, IsSecondTag, T, U> FlecsCachedRefPairType
//     for ConditionalCachedRefTypeSelector<
//         FlecsIsTyped,
//         IsSecondTyped,
//         FlecsNotATag,
//         IsSecondTag,
//         T,
//         U,
//     >
// where
//     T: InternalIntoEntity,
//     U: InternalIntoEntity,
// {
//     type Type = T::CastType;
// }

// #[doc(hidden)]
// impl<IsFirstTyped, T, U> FlecsCachedRefPairType
//     for ConditionalCachedRefTypeSelector<
//         IsFirstTyped,
//         FlecsIsTyped,
//         FlecsIsATag,
//         FlecsNotATag,
//         T,
//         U,
//     >
// where
//     T: InternalIntoEntity,
//     U: InternalIntoEntity,
// {
//     type Type = U::CastType;
// }