my-ecs 0.1.2

An Entity Component System (ECS) library
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
use crate::ecs::ent::{
    component::{Component, ComponentKey, Components},
    entity::{ContainEntity, Entity, EntityIndex, EntityName, EntityTag},
    storage::EntityContainerRef,
};
use my_utils::{
    ds::{
        ATypeId, Borrowed, FlatIter, FlatIterMut, Getter, GetterMut, ManagedConstPtr, NonNullExt,
        ParFlatIter, ParFlatIterMut, RawGetter, SendSyncPtr,
    },
    TakeRecur,
};
use rayon::iter::{plumbing::Producer, IntoParallelIterator};
use std::{
    any, fmt, iter,
    marker::PhantomData,
    ops::{Deref, DerefMut},
    ptr::NonNull,
    sync::Arc,
};

pub trait StoreSelectInfo: StoreFilterInfo {
    fn contains(&self, key: &SelectKey) -> bool;
    fn get(&self, key: &SelectKey) -> Option<&Arc<SelectInfo>>;
    fn insert(&mut self, key: SelectKey, info: Arc<SelectInfo>);
}

pub trait StoreFilterInfo {
    fn contains(&self, key: &FilterKey) -> bool;
    fn get(&self, key: &FilterKey) -> Option<&Arc<FilterInfo>>;
    fn insert(&mut self, key: FilterKey, info: Arc<FilterInfo>);
}

/// A trait for selecting a certain [`Target`](Select::Target) from entities that meet
/// [`All`](Filter::All), [`Any`](Filter::Any), and [`None`](Filter::None) conditions.
///
/// # Example
///
/// ```ignore
/// # use my_ecs::prelude::*;
///
/// #[derive(Component)] struct Ca;
/// #[derive(Component)] struct Cb;
/// #[derive(Component)] struct Cc;
/// #[derive(Component)] struct Cd;
///
/// struct Sa;
/// impl Select for Sa {
///     type Target = Ca;
///     type Filter = Fa;
/// }
/// struct Fa;
/// impl Filter for Fa {
///     type All = Cb;
///     type Any = (Cc, Cd);
///     type None = ();
/// }
///
/// // Or simply
/// filter!(Sb, Target = Ca, All = Cb, Any = (Cc, Cd));
/// ```
pub trait Select: 'static {
    type Target: Component;
    type Filter: Filter;

    #[doc(hidden)]
    fn key() -> SelectKey {
        SelectKey::of::<Self>()
    }

    #[doc(hidden)]
    fn get_info_from<S>(stor: &mut S) -> &Arc<SelectInfo>
    where
        S: StoreSelectInfo + StoreFilterInfo + ?Sized,
    {
        let key = Self::key();

        if !StoreSelectInfo::contains(stor, &key) {
            let sinfo = Arc::new(Self::info_from(stor));
            StoreSelectInfo::insert(stor, key, sinfo);
        }

        // Safety: Inserted right before.
        unsafe { StoreSelectInfo::get(stor, &key).unwrap_unchecked() }
    }

    #[doc(hidden)]
    fn info_from<S>(stor: &mut S) -> SelectInfo
    where
        S: StoreFilterInfo + ?Sized,
    {
        let target = ComponentKey::of::<Self::Target>();
        let finfo = Arc::clone(Self::Filter::get_info_from(stor));
        let name = any::type_name::<Self>();
        SelectInfo::new(target, finfo, name)
    }
}

/// A trait for selecting certain entities that meet [`All`](Filter::All), [`Any`](Filter::Any), and
/// [`None`](Filter::None) conditions.
///
/// # Example
///
/// ```ignore
/// # use my_ecs::prelude::*;
///
/// #[derive(Component)] struct Ca;
/// #[derive(Component)] struct Cb;
/// #[derive(Component)] struct Cc;
/// #[derive(Component)] struct Cd;
///
/// /// Filtering using All, Any, and None.
/// struct Fa;
/// impl Filter for Fa {
///     type All = Ca;
///     type Any = (Cb, Cc);
///     type None = Cd;
///     type Exact = ();
/// }
///
/// // Or simply
/// filter!(Fb, All = Ca, Any = (Cb, Cc));
///
/// /// Filtering using Exact.
/// struct Fb;
/// impl Filter for Fc {
///     type All = ();
///     type Any = ();
///     type None = ();
///     type Exact = (Ca, Cb);
/// }
///
/// // Or simply
/// filter!(Fd, Exact = (Ca, Cb));
/// ```
pub trait Filter: 'static {
    /// A [`Component`] group to select entities that contains all components in this group. It's
    /// something like *AND* condition. But if `All` is empty, then any entities won't be rejected.
    type All: Components;

    /// A [`Component`] group to select entities that contains any components in this group. It's
    /// something like *OR* condition. But if `Any` is empty, then any entities won't be rejected.
    type Any: Components;

    /// A [`Component`] group to select entities that don't contain any components in this group.
    /// It's something like *NOR* condition. Buf if `None` is empty, then any entities won't be
    /// rejected.
    type None: Components;

    /// A [`Component`] group to select a specific entity that consists of components in this group
    /// exactly.
    type Exact: Components;

    #[doc(hidden)]
    fn key() -> FilterKey {
        FilterKey::of::<Self>()
    }

    #[doc(hidden)]
    fn all_any_none() -> [Box<[ComponentKey]>; 3] {
        let all: Box<[ComponentKey]> = Self::All::keys().as_ref().into();
        let any: Box<[ComponentKey]> = Self::Any::keys().as_ref().into();
        let none: Box<[ComponentKey]> = Self::None::keys().as_ref().into();
        [all, any, none]
    }

    #[doc(hidden)]
    fn get_info_from<S>(stor: &mut S) -> &Arc<FilterInfo>
    where
        S: StoreFilterInfo + ?Sized,
    {
        let key = Self::key();

        if !stor.contains(&key) {
            let sinfo = Arc::new(Self::info());
            stor.insert(key, sinfo);
        }

        // Safety: Inserted right before.
        unsafe { stor.get(&key).unwrap_unchecked() }
    }

    #[doc(hidden)]
    fn info() -> FilterInfo {
        let [all, any, none] = Self::all_any_none();
        let exact = Self::Exact::keys().as_ref().into();
        let name = any::type_name::<Self>();
        FilterInfo::new(all, any, none, exact, name)
    }
}

/// An [`Entity`] is an exact [`Filter`].
impl<T: Entity> Filter for T {
    type All = ();
    type Any = ();
    type None = ();
    type Exact = T;
}

/// Unique identifier for a type implementing [`Select`].
pub type SelectKey = ATypeId<SelectKey_>;
pub struct SelectKey_;

/// Unique identifier for a type implementing [`Filter`].
pub type FilterKey = ATypeId<FilterKey_>;
pub struct FilterKey_;

#[derive(Clone)]
pub struct SelectInfo {
    target: ComponentKey,
    finfo: Arc<FilterInfo>,
    name: &'static str,
}

impl fmt::Debug for SelectInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SelectInfo")
            .field("name", &self.name())
            .field("target", &self.target())
            .field("finfo", &self.filter_info())
            .finish()
    }
}

impl SelectInfo {
    const fn new(target: ComponentKey, finfo: Arc<FilterInfo>, name: &'static str) -> Self {
        Self {
            target,
            finfo,
            name,
        }
    }

    pub(crate) const fn target(&self) -> &ComponentKey {
        &self.target
    }

    pub(crate) const fn filter_info(&self) -> &Arc<FilterInfo> {
        &self.finfo
    }

    pub(crate) const fn name(&self) -> &'static str {
        self.name
    }

    pub(crate) fn filter<F>(&self, contains: F, num_columns: usize) -> bool
    where
        F: Fn(&ComponentKey) -> bool,
    {
        contains(self.target()) && self.finfo.filter(contains, num_columns)
    }

    /// Determines that the given selector is disjoint with this selector.
    ///
    /// Disjoint filters mean that two filters don't overlap at all. Table below shows the disjoint
    /// conditions.
    /// - Two have different targets.
    /// - Two are disjoint filters.
    pub(crate) fn is_disjoint(&self, rhs: &Self) -> bool {
        (self.target != rhs.target) || self.finfo.is_disjoint(&rhs.finfo)
    }

    pub(crate) fn is_disjoint2(&self, rhs: &FilterInfo) -> bool {
        self.finfo.is_disjoint(rhs)
    }
}

#[derive(Clone)]
pub struct FilterInfo {
    all: Box<[ComponentKey]>,
    any: Box<[ComponentKey]>,
    none: Box<[ComponentKey]>,
    exact: Box<[ComponentKey]>,
    name: &'static str,
}

impl fmt::Debug for FilterInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FilterInfo")
            .field("name", &self.name())
            .field("all", &self.all())
            .field("any", &self.any())
            .field("none", &self.none())
            .field("exact", &self.exact())
            .finish()
    }
}

impl FilterInfo {
    const fn new(
        all: Box<[ComponentKey]>,
        any: Box<[ComponentKey]>,
        none: Box<[ComponentKey]>,
        exact: Box<[ComponentKey]>,
        name: &'static str,
    ) -> Self {
        Self {
            all,
            any,
            none,
            exact,
            name,
        }
    }

    pub(crate) const fn all(&self) -> &[ComponentKey] {
        &self.all
    }

    pub(crate) const fn any(&self) -> &[ComponentKey] {
        &self.any
    }

    pub(crate) const fn none(&self) -> &[ComponentKey] {
        &self.none
    }

    pub(crate) const fn exact(&self) -> &[ComponentKey] {
        &self.exact
    }

    pub(crate) const fn name(&self) -> &'static str {
        self.name
    }

    pub(crate) fn filter<F>(&self, contains: F, num_columns: usize) -> bool
    where
        F: Fn(&ComponentKey) -> bool,
    {
        // empty iter.all() -> returns true.
        // empty iter.any() -> returns false.

        if !self.exact.is_empty() {
            self.exact.len() == num_columns && self.exact.iter().all(&contains)
        } else {
            self.all.iter().all(&contains)
                && !self.none.iter().any(&contains)
                && if self.any.is_empty() {
                    true
                } else {
                    self.any.iter().any(contains)
                }
        }
    }

    /// Determines that the given filter is disjoint with this filter.
    ///
    /// Disjoint filters mean that two filters don't overlap at all. Disjoint conditions are as
    /// follows.
    pub(crate) fn is_disjoint(&self, rhs: &Self) -> bool {
        let is_self_general = self.exact.is_empty();
        let is_rhs_general = rhs.exact.is_empty();
        match (is_self_general, is_rhs_general) {
            // Exact and Exact
            (false, false) => self.is_disjoint_exact_exact(rhs),
            // Exact and General
            (false, true) => rhs.is_disjoint_general_exact(self),
            // General and Exact
            (true, false) => self.is_disjoint_general_exact(rhs),
            // General and General
            (true, true) => self.is_disjoint_general_general(rhs),
        }
    }

    /// # General vs. General disjoint conditions
    /// - X's All intersects Y's None or vice versa.
    /// - X's Any is a subset of Y's None or vice versa.
    ///
    /// | Filter | All    | None      | Any    |
    /// | :---:  | :---:  | :---:     | :---:  |
    /// | FA     | A, B   | C, D      | E, F   |
    /// | FB     | ...    | A, ...    | ...    | 1. A.All intersects B.None
    /// | FB     | ...    | B, ...    | ...    | 1. A.All intersects B.None
    /// | FB     | C, ... | ...       | ...    | 2. A.None intersects B.All
    /// | FB     | D, ... | ...       | ...    | 2. A.None intersects B.All
    /// | FB     | ...    | ...       | C      | 3. B.Any is a subset of A.None
    /// | FB     | ...    | ...       | D      | 3. B.Any is a subset of A.None
    /// | FB     | ...    | ...       | C, D   | 3. B.Any is a subset of A.None
    /// | FB     | ...    | E, F, ... | ...    | 4. A.Any is a subset of B.None
    fn is_disjoint_general_general(&self, rhs: &Self) -> bool {
        let (a_all, a_any, a_none) = (&self.all, &self.any, &self.none);
        let (b_all, b_any, b_none) = (&rhs.all, &rhs.any, &rhs.none);

        // 1. FA::All intersects FB::None
        if a_all.iter().any(|a| b_none.contains(a)) {
            return true;
        }

        // 2. FA::None intersects FA::All
        if a_none.iter().any(|a| b_all.contains(a)) {
            return true;
        }

        // 3. FB::Any is a subset of FA::None
        if !b_any.is_empty() && b_any.iter().all(|b| a_none.contains(b)) {
            return true;
        }

        // 4. FA::Any is a subset of FB::None
        if !a_any.is_empty() && a_any.iter().all(|a| b_none.contains(a)) {
            return true;
        }

        false
    }

    /// # Exact vs. filter disjoint conditions
    ///
    /// - Not the same one
    fn is_disjoint_exact_exact(&self, rhs: &Self) -> bool {
        if self.exact.len() != rhs.exact.len() {
            return false;
        }

        self.exact.iter().any(|l| !rhs.exact.contains(l))
    }

    /// # General vs. filter disjoint conditions
    ///
    /// | Filter | All   | None  | Any   | Exact           |
    /// | :---:  | :---: | :---: | :---: | :--:            |
    /// | FA     | A, B  | C, D  | E, F  |                 |
    /// | FB     |       |       |       | not A, ...      | // Case 1
    /// | FB     |       |       |       | not B, ...      | // Case 1
    /// | FB     |       |       |       | C, ...          | // Case 2
    /// | FB     |       |       |       | D, ...          | // Case 2
    /// | FB     |       |       |       | ... except E, F | // Case 3
    fn is_disjoint_general_exact(&self, rhs: &Self) -> bool {
        let (a_all, a_any, a_none) = (&self.all, &self.any, &self.none);
        let b_exact = &rhs.exact;

        // Case 1. `B` includes one not belonging `A.All`.
        if b_exact.iter().any(|b| !a_all.contains(b)) {
            return true;
        }

        // Case 2. `B` includes one of `A.None`.
        if b_exact.iter().any(|b| a_none.contains(b)) {
            return true;
        }

        // Case 3. `B` doesn't include any of `A.Any`.
        if a_any.iter().all(|a| !b_exact.contains(a)) {
            return true;
        }

        false
    }
}

/// Shared references to [`Select::Target`] component arrays from multiple entities. You can get an
/// iterator traversing over each component array via [`iter`](Self::iter). A component array
/// belongs to a specific entity.
#[derive(Debug)]
pub struct Selected<'cont, Comp: 'cont> {
    /// A struct holding borrowed component arrays and their entity tags.
    raw: &'cont mut SelectedRaw,

    /// Holds component type.
    _marker: PhantomData<Comp>,
}

impl<'cont, Comp: 'cont> Selected<'cont, Comp> {
    /// Creates [`Selected`] from a mutable reference to a [`SelectedRaw`]. [`SelectedRaw`] is not a
    /// container, but it's borrowing container's data, and holding them inside [`Borrowed`]s. So we
    /// can think lifetime to the '&mut [`SelectedRaw`]' is as if container's.
    pub(crate) fn new(raw: &'cont mut SelectedRaw) -> Self {
        Self {
            raw,
            _marker: PhantomData,
        }
    }

    pub fn iter(&self) -> SelectedIter<'cont, Comp> {
        SelectedIter::new(self)
    }

    pub fn par_iter(&self) -> ParSelectedIter<'cont, Comp> {
        ParSelectedIter(self.iter())
    }

    pub(crate) fn as_raw(&self) -> &SelectedRaw {
        self.raw
    }
}

/// Mutable references to [`Select::Target`] component arrays from multiple entities. You can get an
/// iterator traversing over each component array via [`iter`](Self::iter) or
/// [`iter_mut`](Self::iter_mut). A component array belongs to a specific entity.
//
// `Selected` has mutable reference to a `SelectedRaw` in it. So we can make use of it and expose
// mutable methods to clients here.
#[derive(Debug)]
#[repr(transparent)]
pub struct SelectedMut<'cont, Comp>(Selected<'cont, Comp>);

impl<'cont, Comp: 'cont> SelectedMut<'cont, Comp> {
    pub(crate) fn new(filtered: &'cont mut SelectedRaw) -> Self {
        Self(Selected::new(filtered))
    }

    pub fn iter(&self) -> SelectedIter<'cont, Comp> {
        self.0.iter()
    }

    pub fn iter_mut(&mut self) -> SelectedIterMut<'cont, Comp> {
        SelectedIterMut(self.iter())
    }

    pub fn par_iter(&self) -> ParSelectedIter<'cont, Comp> {
        self.0.par_iter()
    }

    pub fn par_iter_mut(&mut self) -> ParSelectedIterMut<'cont, Comp> {
        ParSelectedIterMut(self.iter_mut())
    }
}

#[derive(Debug)]
pub struct FilteredMut<'stor, T: 'stor> {
    raw: &'stor mut FilteredRaw,
    _marker: PhantomData<T>,
}

impl<'stor, T: 'stor> FilteredMut<'stor, T> {
    pub(crate) fn new(raw: &'stor mut FilteredRaw) -> Self {
        Self {
            raw,
            _marker: PhantomData,
        }
    }

    pub fn iter_mut(&mut self) -> FilteredIterMut<'stor, T> {
        FilteredIterMut::new(self)
    }

    pub(crate) fn as_mut_raw(&mut self) -> &mut FilteredRaw {
        self.raw
    }
}

impl<'stor, T: Entity + 'stor> TakeRecur for FilteredMut<'stor, T> {
    type Inner = EntityContainerRef<'stor, T>;

    fn take_recur(mut self) -> Self::Inner {
        if let Some(cont) = self.iter_mut().next() {
            cont
        } else {
            panic!("have you registered `{}`?", any::type_name::<T>());
        }
    }
}

/// Selected component arrays by a [`Select`].
//
// This struct contains borrowed `Select::Target` arrays. But, this struct doesn't bring lifetime
// constraint into inside the struct, although it borrows component arrays. Instead, borrowed data
// are encapsulated by `Borrowed`, which is a run-time borrow checker. In other words, component
// arrays must be borrowed and released everytime.
//
// This struct is intended to be used as a cache without lifetime. Cache is a data storage which
// lives as long as system data. But system data will live indefinitely, so removing lifetime helps
// to keep things simple.
#[derive(Debug)]
pub struct SelectedRaw {
    /// [EntityTag] searched by the filter.
    //
    // Each system owns `SelectedRaw`, so `etags` and `col_idxs` will be duplicated between systems.
    etags: Vec<Arc<EntityTag>>,

    /// Column(Component) index searched by the filter.
    //
    // Each system owns `SelectedRaw`, so `etags` and `col_idxs` will be duplicated between systems.
    col_idxs: Vec<usize>,

    /// Temporary buffer for the query result.
    ///
    /// Content will be replaced for every query, but we can reuse the capacity. Notice that this
    /// doesn't actually own [Borrowed] because this is just a temporary buffer. Real user, system,
    /// owns it and will drop it after using it.
    //
    // See `request::BufferCleaner` for more details.
    query_res: Vec<Borrowed<RawGetter>>,
}

impl SelectedRaw {
    pub(crate) const fn new(etags: Vec<Arc<EntityTag>>, col_idxs: Vec<usize>) -> Self {
        Self {
            etags,
            col_idxs,
            query_res: Vec::new(),
        }
    }

    pub(crate) fn take(
        &mut self,
    ) -> (
        &Vec<Arc<EntityTag>>,
        &Vec<usize>,
        &mut Vec<Borrowed<RawGetter>>,
    ) {
        (&self.etags, &self.col_idxs, &mut self.query_res)
    }

    // `etags` and `col_idxs` always have the same length.
    pub(crate) fn add(&mut self, etag: Arc<EntityTag>, ci: usize) {
        self.etags.push(etag);
        self.col_idxs.push(ci);
    }

    // `etags` and `col_idxs` always have the same length.
    pub(crate) fn remove(&mut self, ei: EntityIndex, ci: usize) -> Option<Arc<EntityTag>> {
        let ei_iter = self.etags.iter().map(|etag| etag.index());
        let ei_ci_iter = ei_iter.zip(&self.col_idxs);

        if let Some((i, _)) = ei_ci_iter
            .enumerate()
            .find(|(_, (item_ei, item_ci))| *item_ei == ei && **item_ci == ci)
        {
            let old = self.etags.swap_remove(i);
            self.col_idxs.swap_remove(i);
            Some(old)
        } else {
            None
        }
    }

    /// Retrieve an iterator that traverses over entity and column index pair.
    pub(crate) fn iter_index_pair<'a>(
        etags: &'a [Arc<EntityTag>],
        col_idxs: &'a [usize],
    ) -> impl Iterator<Item = (EntityIndex, usize)> + 'a {
        // Self::add() guarantees that etags and col_idxs have the same length.
        etags
            .iter()
            .map(|etag| etag.index())
            .zip(col_idxs.iter().cloned())
    }

    pub(crate) fn clear(&mut self) {
        self.query_res.clear();
    }

    pub(crate) const fn query_res(&self) -> &Vec<Borrowed<RawGetter>> {
        &self.query_res
    }

    const fn entity_tags(&self) -> &Vec<Arc<EntityTag>> {
        &self.etags
    }
}

#[derive(Debug)]
pub struct FilteredRaw {
    pub(crate) etags: Vec<Arc<EntityTag>>,
    pub(crate) query_res: Vec<Borrowed<NonNull<dyn ContainEntity>>>,
}

impl FilteredRaw {
    pub(crate) const fn new(etags: Vec<Arc<EntityTag>>) -> Self {
        Self {
            etags,
            query_res: Vec::new(),
        }
    }

    #[allow(clippy::type_complexity)]
    pub(crate) fn take(
        &mut self,
    ) -> (
        &Vec<Arc<EntityTag>>,
        &mut Vec<Borrowed<NonNull<dyn ContainEntity>>>,
    ) {
        (&self.etags, &mut self.query_res)
    }

    pub(crate) fn add(&mut self, etag: Arc<EntityTag>) {
        self.etags.push(etag);
    }

    pub(crate) fn remove(&mut self, ei: &EntityIndex) -> Option<Arc<EntityTag>> {
        if let Some((i, _)) = self
            .etags
            .iter()
            .enumerate()
            .find(|(_, x)| &x.index() == ei)
        {
            let old = self.etags.swap_remove(i);
            Some(old)
        } else {
            None
        }
    }

    pub(crate) fn clear(&mut self) {
        self.query_res.clear();
    }
}

#[derive(Debug, Clone)]
pub struct SelectedIter<'cont, Comp: 'cont> {
    getter_left: SendSyncPtr<Borrowed<RawGetter>>,

    getter_right: SendSyncPtr<Borrowed<RawGetter>>,

    etag_left: SendSyncPtr<Arc<EntityTag>>,

    etag_right: SendSyncPtr<Arc<EntityTag>>,

    _marker: PhantomData<&'cont Comp>,
}

impl<'cont, Comp: 'cont> SelectedIter<'cont, Comp> {
    // Borrows `Selected`.
    fn new(raw: &Selected<'cont, Comp>) -> Self {
        // Safety: `Selected` guarantees we're good to access those vecs.
        unsafe {
            let getter_range = raw.as_raw().query_res().as_ptr_range();
            let getter_left = NonNull::new_unchecked(getter_range.start.cast_mut());
            let getter_right = NonNull::new_unchecked(getter_range.end.cast_mut());

            let etag_range = raw.as_raw().entity_tags().as_ptr_range();
            let etag_left = NonNull::new_unchecked(etag_range.start.cast_mut());
            let etag_right = NonNull::new_unchecked(etag_range.end.cast_mut());

            Self {
                getter_left: SendSyncPtr::new(getter_left),
                getter_right: SendSyncPtr::new(getter_right),
                etag_left: SendSyncPtr::new(etag_left),
                etag_right: SendSyncPtr::new(etag_right),
                _marker: PhantomData,
            }
        }
    }

    #[inline]
    pub const fn len(&self) -> usize {
        let left = self.getter_left.as_ptr();
        let right = self.getter_right.as_ptr();
        unsafe { right.offset_from(left) as usize }
    }

    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    #[inline]
    fn split_at(self, index: usize) -> (Self, Self) {
        let l_getter_left = self.getter_left;
        let l_getter_right = unsafe { self.getter_left.add(index) };
        let r_getter_left = l_getter_right;
        let r_getter_right = self.getter_right;

        let l_etag_left = self.etag_left;
        let l_etag_right = unsafe { self.etag_left.add(index) };
        let r_etag_left = l_etag_right;
        let r_etag_right = self.etag_right;

        let l = SelectedIter {
            getter_left: l_getter_left,
            getter_right: l_getter_right,
            etag_left: l_etag_left,
            etag_right: l_etag_right,
            _marker: PhantomData,
        };
        let r = SelectedIter {
            getter_left: r_getter_left,
            getter_right: r_getter_right,
            etag_left: r_etag_left,
            etag_right: r_etag_right,
            _marker: PhantomData,
        };
        (l, r)
    }

    unsafe fn create_item(
        getter: SendSyncPtr<Borrowed<RawGetter>>,
        etag: SendSyncPtr<Arc<EntityTag>>,
    ) -> TaggedGetter<'cont, Comp> {
        let getter = unsafe {
            let raw = **getter.as_ref();
            Getter::from_raw(raw)
        };

        let etag = unsafe {
            let etag = Arc::as_ptr(etag.as_ref()).cast_mut();
            let etag = NonNullExt::new(etag).unwrap_unchecked();
            ManagedConstPtr::new(etag)
        };

        TaggedGetter { getter, etag }
    }
}

impl<'cont, Comp: 'cont> Iterator for SelectedIter<'cont, Comp> {
    type Item = TaggedGetter<'cont, Comp>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.getter_left < self.getter_right {
            let getter = self.getter_left;
            let etag = self.etag_left;
            unsafe {
                self.getter_left = self.getter_left.add(1);
                self.etag_left = self.etag_left.add(1);
                Some(Self::create_item(getter, etag))
            }
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = Self::len(self);
        (len, Some(len))
    }
}

impl<'cont, Comp: 'cont> iter::FusedIterator for SelectedIter<'cont, Comp> {}

impl<'cont, Comp: 'cont> ExactSizeIterator for SelectedIter<'cont, Comp> {
    fn len(&self) -> usize {
        Self::len(self)
    }
}

impl<'cont, Comp: 'cont> DoubleEndedIterator for SelectedIter<'cont, Comp> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.getter_left < self.getter_right {
            unsafe {
                self.getter_right = self.getter_right.sub(1);
                self.etag_right = self.etag_right.sub(1);
                Some(Self::create_item(self.getter_right, self.etag_right))
            }
        } else {
            None
        }
    }
}

/// Parallel [`SelectedIter`].
//
// `Iterator` and `ParallelIterator` have the same signature methods, So clients have to write
// fully-qualified syntax to specify methods. This new type helps clients avoid it.
#[derive(Debug, Clone)]
#[repr(transparent)]
pub struct ParSelectedIter<'cont, Comp>(pub SelectedIter<'cont, Comp>);

impl<'cont, Comp: 'cont> ParSelectedIter<'cont, Comp> {
    #[inline]
    pub const fn into_seq(self) -> SelectedIter<'cont, Comp> {
        self.0
    }

    #[inline]
    pub const fn len(&self) -> usize {
        self.0.len()
    }

    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl<'cont, Comp: Send + Sync + 'cont> Producer for ParSelectedIter<'cont, Comp> {
    type Item = TaggedGetter<'cont, Comp>;
    type IntoIter = SelectedIter<'cont, Comp>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.into_seq()
    }

    #[inline]
    fn split_at(self, index: usize) -> (Self, Self) {
        let (l, r) = SelectedIter::split_at(self.0, index);
        (ParSelectedIter(l), ParSelectedIter(r))
    }
}

my_utils::impl_into_iterator_for_parallel!(
    "lifetimes" = 'cont; "bounds" = Comp: {'cont};
    "for" = ParSelectedIter; "to" = SelectedIter<'cont, Comp>;
    "item" = TaggedGetter<'cont, Comp>;
);
my_utils::impl_parallel_iterator!(
    "lifetimes" = 'cont; "bounds" = Comp: {Send + Sync + 'cont};
    "for" = ParSelectedIter; "item" = TaggedGetter<'cont, Comp>;
);
my_utils::impl_unindexed_producer!(
    "lifetimes" = 'cont; "bounds" = Comp: {Send + Sync + 'cont};
    "for" = ParSelectedIter; "item" = TaggedGetter<'cont, Comp>;
);

// Mutable iterator is not cloneable.
#[derive(Debug)]
#[repr(transparent)]
pub struct SelectedIterMut<'cont, Comp>(pub SelectedIter<'cont, Comp>);

impl<'cont, Comp: 'cont> SelectedIterMut<'cont, Comp> {
    #[inline]
    pub const fn into_seq(self) -> SelectedIter<'cont, Comp> {
        self.0
    }

    #[inline]
    pub const fn len(&self) -> usize {
        self.0.len()
    }

    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    #[inline]
    fn split_at(self, index: usize) -> (Self, Self) {
        let (l, r) = SelectedIter::split_at(self.0, index);
        (Self(l), Self(r))
    }
}

impl<'cont, Comp> Iterator for SelectedIterMut<'cont, Comp> {
    type Item = TaggedGetterMut<'cont, Comp>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|TaggedGetter { getter, etag }| {
            TaggedGetterMut {
                // Safety: `GetterMut` is made from `Getter`, which proves it's `RawGetter` and type
                // are valid.
                getter: unsafe { GetterMut::from_raw(getter.into_raw()) },
                etag,
            }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<'cont, Comp: 'cont> iter::FusedIterator for SelectedIterMut<'cont, Comp> {}

impl<'cont, Comp: 'cont> ExactSizeIterator for SelectedIterMut<'cont, Comp> {
    fn len(&self) -> usize {
        Self::len(self)
    }
}

impl<'cont, Comp: 'cont> DoubleEndedIterator for SelectedIterMut<'cont, Comp> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().map(|TaggedGetter { getter, etag }| {
            TaggedGetterMut {
                // Safety: `GetterMut` is made from `Getter`, which proves it's `RawGetter` and type
                // are valid.
                getter: unsafe { GetterMut::from_raw(getter.into_raw()) },
                etag,
            }
        })
    }
}

/// Parallel [`SelectedIterMut`].
//
// `Iterator` and `ParallelIterator` have the same signature methods, So clients have to write
// fully-qualified syntax to specify methods. This new type helps clients avoid it.
#[derive(Debug)]
#[repr(transparent)]
pub struct ParSelectedIterMut<'cont, Comp>(pub SelectedIterMut<'cont, Comp>);

impl<'cont, Comp: 'cont> ParSelectedIterMut<'cont, Comp> {
    #[inline]
    pub const fn into_seq(self) -> SelectedIterMut<'cont, Comp> {
        self.0
    }

    #[inline]
    pub const fn len(&self) -> usize {
        self.0.len()
    }

    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl<'cont, Comp: Send + Sync> Producer for ParSelectedIterMut<'cont, Comp> {
    type Item = TaggedGetterMut<'cont, Comp>;
    type IntoIter = SelectedIterMut<'cont, Comp>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.into_seq()
    }

    #[inline]
    fn split_at(self, index: usize) -> (Self, Self) {
        let (l, r) = SelectedIterMut::split_at(self.0, index);
        (ParSelectedIterMut(l), ParSelectedIterMut(r))
    }
}

my_utils::impl_into_iterator_for_parallel!(
    "lifetimes" = 'cont; "bounds" = Comp: {'cont};
    "for" = ParSelectedIterMut; "to" = SelectedIterMut<'cont, Comp>;
    "item" = TaggedGetterMut<'cont, Comp>;
);
my_utils::impl_parallel_iterator!(
    "lifetimes" = 'cont; "bounds" = Comp: {Send + Sync + 'cont};
    "for" = ParSelectedIterMut; "item" = TaggedGetterMut<'cont, Comp>;
);
my_utils::impl_unindexed_producer!(
    "lifetimes" = 'cont; "bounds" = Comp: {Send + Sync + 'cont};
    "for" = ParSelectedIterMut; "item" = TaggedGetterMut<'cont, Comp>;
);

#[derive(Debug)]
pub struct FilteredIterMut<'stor, T: 'stor> {
    /// Inclusive
    cont_left: NonNull<Borrowed<NonNull<dyn ContainEntity>>>,
    /// Exclusive
    cont_right: NonNull<Borrowed<NonNull<dyn ContainEntity>>>,
    /// Inclusive
    etag_left: NonNull<Arc<EntityTag>>,
    /// Exclusive
    etag_right: NonNull<Arc<EntityTag>>,
    _marker: PhantomData<&'stor mut T>,
}

impl<'stor, T: 'stor> FilteredIterMut<'stor, T> {
    fn new(raw: &mut FilteredMut<'stor, T>) -> Self {
        // Safety: `FilteredMut` guarantees we're good to access those vecs.
        unsafe {
            let cont_range = raw.as_mut_raw().query_res.as_mut_ptr_range();
            let cont_left = NonNull::new_unchecked(cont_range.start);
            let cont_right = NonNull::new_unchecked(cont_range.end);

            let etag_range = raw.as_mut_raw().etags.as_mut_ptr_range();
            let etag_left = NonNull::new_unchecked(etag_range.start);
            let etag_right = NonNull::new_unchecked(etag_range.end);

            Self {
                cont_left,
                cont_right,
                etag_left,
                etag_right,
                _marker: PhantomData,
            }
        }
    }

    #[inline]
    pub const fn len(&self) -> usize {
        let left = self.cont_left.as_ptr();
        let right = self.cont_right.as_ptr();
        unsafe { right.offset_from(left) as usize }
    }

    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    unsafe fn create_item(
        mut cont: NonNull<Borrowed<NonNull<dyn ContainEntity>>>,
        etag: NonNull<Arc<EntityTag>>,
    ) -> EntityContainerRef<'stor, T> {
        let etag = unsafe { etag.as_ref() };
        let etag = &**etag;
        let cont = unsafe { cont.as_mut().as_mut() };
        EntityContainerRef::new(etag, cont)
    }
}

impl<'stor, T: 'stor> Iterator for FilteredIterMut<'stor, T> {
    type Item = EntityContainerRef<'stor, T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.cont_left < self.cont_right {
            let getter = self.cont_left;
            let etag = self.etag_left;
            unsafe {
                let ptr = self.cont_left.as_ptr().add(1);
                self.cont_left = NonNull::new_unchecked(ptr);

                let ptr = self.etag_left.as_ptr().add(1);
                self.etag_left = NonNull::new_unchecked(ptr);

                Some(Self::create_item(getter, etag))
            }
        } else {
            None
        }
    }
}

impl<'stor, T: 'stor> iter::FusedIterator for FilteredIterMut<'stor, T> {}

impl<'stor, T: 'stor> ExactSizeIterator for FilteredIterMut<'stor, T> {
    fn len(&self) -> usize {
        Self::len(self)
    }
}

impl<'stor, T: 'stor> DoubleEndedIterator for FilteredIterMut<'stor, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.cont_left < self.cont_right {
            unsafe {
                let ptr = self.cont_right.as_ptr().sub(1);
                self.cont_right = NonNull::new_unchecked(ptr);

                let ptr = self.etag_right.as_ptr().sub(1);
                self.etag_right = NonNull::new_unchecked(ptr);

                Some(Self::create_item(self.cont_right, self.etag_right))
            }
        } else {
            None
        }
    }
}

/// Component getter with entity tag.
///
/// * Component getter
///   A component getter corresponds to a component array. You can get each component inside
///   component array via getter. See [`Getter`] for more details.
///
/// * Entity tag
///   Many entities may contain the same component type. So, it's needed to know what entity this
///   component belongs to. Entity tag has entity identification such as entity name.
#[derive(Debug)]
pub struct TaggedGetter<'cont, Comp: 'cont> {
    getter: Getter<'cont, Comp>,
    etag: ManagedConstPtr<EntityTag>,
}

impl<Comp> TaggedGetter<'_, Comp> {
    pub fn entity_index(&self) -> EntityIndex {
        self.etag.index()
    }

    pub fn entity_name(&self) -> Option<&EntityName> {
        self.etag.get_name()
    }

    pub fn component_names(&self) -> &[&'static str] {
        self.etag.get_component_names()
    }
}

impl<'cont, Comp> Deref for TaggedGetter<'cont, Comp> {
    type Target = Getter<'cont, Comp>;

    fn deref(&self) -> &Self::Target {
        &self.getter
    }
}

impl<'cont, Comp> IntoIterator for TaggedGetter<'cont, Comp> {
    type Item = &'cont Comp;
    type IntoIter = FlatIter<'cont, Comp>;

    fn into_iter(self) -> Self::IntoIter {
        self.getter.into_iter()
    }
}

impl<'cont, Comp: Send + Sync> IntoParallelIterator for TaggedGetter<'cont, Comp> {
    type Iter = ParFlatIter<'cont, Comp>;
    type Item = &'cont Comp;

    fn into_par_iter(self) -> Self::Iter {
        self.getter.into_par_iter()
    }
}

/// Component getter with entity tag.
///
/// * Component getter
///   A component getter corresponds to a component array. You can get each component inside
///   component array via getter. See [`GetterMut`] for more details.
///
/// * Entity tag
///   Many entities may contain the same component type. So, it's needed to know what entity this
///   component belongs to. Entity tag has entity identification such as entity name.
#[derive(Debug)]
pub struct TaggedGetterMut<'cont, Comp: 'cont> {
    getter: GetterMut<'cont, Comp>,
    etag: ManagedConstPtr<EntityTag>,
}

impl<Comp> TaggedGetterMut<'_, Comp> {
    pub fn entity_index(&self) -> EntityIndex {
        self.etag.index()
    }

    pub fn entity_name(&self) -> Option<&EntityName> {
        self.etag.get_name()
    }

    pub fn component_names(&self) -> &[&'static str] {
        self.etag.get_component_names()
    }
}

impl<'cont, Comp> Deref for TaggedGetterMut<'cont, Comp> {
    type Target = GetterMut<'cont, Comp>;

    fn deref(&self) -> &Self::Target {
        &self.getter
    }
}

impl<Comp> DerefMut for TaggedGetterMut<'_, Comp> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.getter
    }
}

impl<'cont, Comp> IntoIterator for TaggedGetterMut<'cont, Comp> {
    type Item = &'cont mut Comp;
    type IntoIter = FlatIterMut<'cont, Comp>;

    fn into_iter(self) -> Self::IntoIter {
        self.getter.into_iter()
    }
}

impl<'cont, Comp: Send + Sync> IntoParallelIterator for TaggedGetterMut<'cont, Comp> {
    type Iter = ParFlatIterMut<'cont, Comp>;
    type Item = &'cont mut Comp;

    fn into_par_iter(self) -> Self::Iter {
        self.getter.into_par_iter()
    }
}

#[cfg(test)]
mod tests {
    #[test]
    #[rustfmt::skip]
    fn test_my_ecs_macros_filter() {
        use crate as my_ecs;
        use crate::prelude::*;
        use crate::ecs::{
            sys::select::Select,
            ent::component::ComponentKey,
        };

        #[derive(Component)] struct Ca;
        #[derive(Component)] struct Cb;
        #[derive(Component)] struct Cc;
        #[derive(Component)] struct Cd;
        #[derive(Component)] struct Ce;
        #[derive(Component)] struct Cf;

        // Target only.
        filter!(F0, Target = Ca);
        let [all, any, none] = F0::all_any_none();
        assert_eq!(<F0 as Select>::Target::key(), Ca::key());
        assert!(all.is_empty());
        assert!(any.is_empty());
        assert!(none.is_empty());

        // All only.
        filter!(F1, All = Ca);
        let [all, any, none] = F1::all_any_none();
        validate_slice(&all, &[Ca::key()]);
        assert!(any.is_empty());
        assert!(none.is_empty());

        // Any only.
        filter!(F2, Any = Ca);
        let [all, any, none] = F2::all_any_none();
        assert!(all.is_empty());
        validate_slice(&any, &[Ca::key()]);
        assert!(none.is_empty());

        // None only.
        filter!(F3, None = Ca);
        let [all, any, none] = F3::all_any_none();
        assert!(all.is_empty());
        assert!(any.is_empty());
        validate_slice(&none, &[Ca::key()]);

        // All + Any + None.
        filter!(F4, All = (Ca, Cb), Any = (Cc, Cd), None = (Ce, Cf));
        let [all, any, none] = F4::all_any_none();
        validate_slice(&all, &[Ca::key(), Cb::key()]);
        validate_slice(&any, &[Cc::key(), Cd::key()]);
        validate_slice(&none, &[Ce::key(), Cf::key()]);

        // Target + All + Any + None.
        filter!(F5, Target = Ca, All = Cb, Any = Cc, None = Cd);
        let [all, any, none] = F5::all_any_none();
        assert_eq!(<F5 as Select>::Target::key(), Ca::key());
        validate_slice(&all, &[Cb::key()]);
        validate_slice(&any, &[Cc::key()]);
        validate_slice(&none, &[Cd::key()]);

        fn validate_slice(a: &[ComponentKey], b: &[ComponentKey]) {
            assert_eq!(a.len(), b.len());
            for (va, vb) in a.iter().zip(b) {
                assert_eq!(va, vb);
            }
        }
    }
}