bevy_ecs 0.19.0

Bevy Engine's entity component system
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
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
use crate::{
    change_detection::{traits::*, ComponentTickCells, MaybeLocation, Tick},
    component::Mutable,
    ptr::PtrMut,
    resource::Resource,
};
use bevy_ptr::{Ptr, ThinSlicePtr, UnsafeCellDeref};
use core::{
    cell::UnsafeCell,
    ops::{Deref, DerefMut},
    panic::Location,
};

/// Used by immutable query parameters (such as [`Ref`] and [`Res`])
/// to store immutable access to the [`Tick`]s of a single component or resource.
#[derive(Clone, Copy)]
pub(crate) struct ComponentTicksRef<'w> {
    pub(crate) added: &'w Tick,
    pub(crate) changed: &'w Tick,
    pub(crate) changed_by: MaybeLocation<&'w &'static Location<'static>>,
    pub(crate) last_run: Tick,
    pub(crate) this_run: Tick,
}

impl<'w> ComponentTicksRef<'w> {
    /// # Safety
    /// This should never alias the underlying ticks with a mutable one such as `ComponentTicksMut`.
    #[inline]
    pub(crate) unsafe fn from_tick_cells(
        cells: ComponentTickCells<'w>,
        last_run: Tick,
        this_run: Tick,
    ) -> Self {
        Self {
            // SAFETY: Caller ensures there is no mutable access to the cell.
            added: unsafe { cells.added.deref() },
            // SAFETY: Caller ensures there is no mutable access to the cell.
            changed: unsafe { cells.changed.deref() },
            // SAFETY: Caller ensures there is no mutable access to the cell.
            changed_by: unsafe { cells.changed_by.map(|changed_by| changed_by.deref()) },
            last_run,
            this_run,
        }
    }
}

/// Data type storing contiguously lying ticks.
///
/// Retrievable via [`ContiguousRef::split`] and probably only useful if you want to use the following
/// methods:
/// - [`ContiguousComponentTicksRef::is_changed_iter`],
/// - [`ContiguousComponentTicksRef::is_added_iter`]
#[derive(Clone)]
pub struct ContiguousComponentTicksRef<'w> {
    pub(crate) added: &'w [Tick],
    pub(crate) changed: &'w [Tick],
    pub(crate) changed_by: MaybeLocation<&'w [&'static Location<'static>]>,
    pub(crate) last_run: Tick,
    pub(crate) this_run: Tick,
}

impl<'w> ContiguousComponentTicksRef<'w> {
    /// # Safety
    /// - The caller must have permission for all given ticks to be read.
    /// - `len` must be the length of `added`, `changed` and `changed_by` (unless none) slices.
    pub(crate) unsafe fn from_slice_ptrs(
        added: ThinSlicePtr<'w, UnsafeCell<Tick>>,
        changed: ThinSlicePtr<'w, UnsafeCell<Tick>>,
        changed_by: MaybeLocation<ThinSlicePtr<'w, UnsafeCell<&'static Location<'static>>>>,
        len: usize,
        this_run: Tick,
        last_run: Tick,
    ) -> Self {
        Self {
            // SAFETY:
            // - The caller ensures that `len` is the length of the slice.
            // - The caller ensures we have permission to read the data.
            added: unsafe { added.cast().as_slice_unchecked(len) },
            // SAFETY: see above.
            changed: unsafe { changed.cast().as_slice_unchecked(len) },
            // SAFETY: see above.
            changed_by: changed_by.map(|v| unsafe { v.cast().as_slice_unchecked(len) }),
            last_run,
            this_run,
        }
    }

    /// Creates a new `ContiguousComponentTicksRef` using provided values or returns [`None`] if lengths of
    /// `added`, `changed` and `changed_by` do not match    
    ///
    /// This is an advanced feature, `ContiguousComponentTicksRef`s are designed to be _created_ by
    /// engine-internal code and _consumed_ by end-user code.
    ///
    /// - `added` - [`Tick`]s that store the tick when the wrapped value was created.
    /// - `changed` - [`Tick`]s that store the last time the wrapped value was changed.
    /// - `last_run` - A [`Tick`], occurring before `this_run`, which is used
    ///   as a reference to determine whether the wrapped value is newly added or changed.
    /// - `this_run` - A [`Tick`] corresponding to the current point in time -- "now".
    /// - `caller` - [`Location`]s that store the location when the wrapper value was changed.
    pub fn new(
        added: &'w [Tick],
        changed: &'w [Tick],
        last_run: Tick,
        this_run: Tick,
        caller: MaybeLocation<&'w [&'static Location<'static>]>,
    ) -> Option<Self> {
        let eq = added.len() == changed.len()
            && caller
                .map(|v| v.len() == added.len())
                .into_option()
                .unwrap_or(true);
        eq.then_some(Self {
            added,
            changed,
            changed_by: caller,
            last_run,
            this_run,
        })
    }

    /// Returns added ticks' slice.
    pub fn added(&self) -> &'w [Tick] {
        self.added
    }

    /// Returns changed ticks' slice.
    pub fn changed(&self) -> &'w [Tick] {
        self.changed
    }

    /// Returns changed by locations' slice.
    pub fn changed_by(&self) -> MaybeLocation<&[&'static Location<'static>]> {
        self.changed_by.as_deref()
    }

    /// Returns the tick the system last ran.
    pub fn last_run(&self) -> Tick {
        self.last_run
    }

    /// Returns the tick of the current system's run.
    pub fn this_run(&self) -> Tick {
        self.this_run
    }

    /// Returns an iterator where the i-th item corresponds to whether the i-th component was
    /// marked as changed. If the value equals [`prim@true`], then the component was changed.
    ///
    /// # Example
    /// ```
    /// # use bevy_ecs::prelude::*;
    /// #
    /// # #[derive(Component)]
    /// # struct A(pub i32);
    ///
    /// fn some_system(mut query: Query<Ref<A>>) {
    ///     for a in query.contiguous_iter().unwrap() {
    ///         let (a_values, a_ticks) = ContiguousRef::split(a);
    ///         for (value, is_changed) in a_values.iter().zip(a_ticks.is_changed_iter()) {
    ///             if is_changed {
    ///                 // do something
    ///             }
    ///         }
    ///     }
    /// }
    /// ```
    pub fn is_changed_iter(&self) -> impl Iterator<Item = bool> {
        self.changed
            .iter()
            .map(|v| v.is_newer_than(self.last_run, self.this_run))
    }

    /// Returns an iterator where the i-th item corresponds to whether the i-th component was
    /// marked as added. If the value equals [`prim@true`], then the component was added.
    ///
    /// # Example
    /// ```
    /// # use bevy_ecs::prelude::*;
    /// #
    /// # #[derive(Component)]
    /// # struct A(pub i32);
    ///
    /// fn some_system(mut query: Query<Ref<A>>) {
    ///     for a in query.contiguous_iter().unwrap() {
    ///         let (a_values, a_ticks) = ContiguousRef::split(a);
    ///         for (value, is_added) in a_values.iter().zip(a_ticks.is_added_iter()) {
    ///             if is_added {
    ///                 // do something
    ///             }
    ///         }
    ///     }
    /// }
    /// ```
    pub fn is_added_iter(&self) -> impl Iterator<Item = bool> {
        self.added
            .iter()
            .map(|v| v.is_newer_than(self.last_run, self.this_run))
    }
}

/// Used by mutable query parameters (such as [`Mut`] and [`ResMut`])
/// to store mutable access to the [`Tick`]s of a single component or resource.
pub(crate) struct ComponentTicksMut<'w> {
    pub(crate) added: &'w mut Tick,
    pub(crate) changed: &'w mut Tick,
    pub(crate) changed_by: MaybeLocation<&'w mut &'static Location<'static>>,
    pub(crate) last_run: Tick,
    pub(crate) this_run: Tick,
}

impl<'w> ComponentTicksMut<'w> {
    /// # Safety
    /// This should never alias the underlying ticks. All access must be unique.
    #[inline]
    pub(crate) unsafe fn from_tick_cells(
        cells: ComponentTickCells<'w>,
        last_run: Tick,
        this_run: Tick,
    ) -> Self {
        Self {
            // SAFETY: Caller ensures there is no alias to the cell.
            added: unsafe { cells.added.deref_mut() },
            // SAFETY: Caller ensures there is no alias to the cell.
            changed: unsafe { cells.changed.deref_mut() },
            // SAFETY: Caller ensures there is no alias to the cell.
            changed_by: unsafe { cells.changed_by.map(|changed_by| changed_by.deref_mut()) },
            last_run,
            this_run,
        }
    }
}

impl<'w> From<ComponentTicksMut<'w>> for ComponentTicksRef<'w> {
    fn from(ticks: ComponentTicksMut<'w>) -> Self {
        ComponentTicksRef {
            added: ticks.added,
            changed: ticks.changed,
            changed_by: ticks.changed_by.map(|changed_by| &*changed_by),
            last_run: ticks.last_run,
            this_run: ticks.this_run,
        }
    }
}

/// Data type storing contiguously lying ticks, which may be accessed to mutate.
///
/// Retrievable via [`ContiguousMut::split`] and probably only useful if you want to use the following
/// methods:
/// - [`ContiguousComponentTicksMut::is_changed_iter`],
/// - [`ContiguousComponentTicksMut::is_added_iter`]
pub struct ContiguousComponentTicksMut<'w> {
    pub(crate) added: &'w mut [Tick],
    pub(crate) changed: &'w mut [Tick],
    pub(crate) changed_by: MaybeLocation<&'w mut [&'static Location<'static>]>,
    pub(crate) last_run: Tick,
    pub(crate) this_run: Tick,
}

impl<'w> ContiguousComponentTicksMut<'w> {
    /// # Safety
    /// - The caller must have permission to use all given ticks to be mutated.
    /// - `len` must be the length of `added`, `changed` and `changed_by` (unless none) slices.
    pub(crate) unsafe fn from_slice_ptrs(
        added: ThinSlicePtr<'w, UnsafeCell<Tick>>,
        changed: ThinSlicePtr<'w, UnsafeCell<Tick>>,
        changed_by: MaybeLocation<ThinSlicePtr<'w, UnsafeCell<&'static Location<'static>>>>,
        len: usize,
        this_run: Tick,
        last_run: Tick,
    ) -> Self {
        Self {
            // SAFETY:
            // - The caller ensures that `len` is the length of the slice.
            // - The caller ensures we have permission to mutate the data.
            added: unsafe { added.as_mut_slice_unchecked(len) },
            // SAFETY: see above.
            changed: unsafe { changed.as_mut_slice_unchecked(len) },
            // SAFETY: see above.
            changed_by: changed_by.map(|v| unsafe { v.as_mut_slice_unchecked(len) }),
            last_run,
            this_run,
        }
    }

    /// Creates a new `ContiguousComponentTicksMut` using provided values or returns [`None`] if lengths of
    /// `added`, `changed` and `changed_by` do not match    
    ///
    /// This is an advanced feature, `ContiguousComponentTicksMut`s are designed to be _created_ by
    /// engine-internal code and _consumed_ by end-user code.
    ///
    /// - `added` - [`Tick`]s that store the tick when the wrapped value was created.
    /// - `changed` - [`Tick`]s that store the last time the wrapped value was changed.
    /// - `last_run` - A [`Tick`], occurring before `this_run`, which is used
    ///   as a reference to determine whether the wrapped value is newly added or changed.
    /// - `this_run` - A [`Tick`] corresponding to the current point in time -- "now".
    /// - `caller` - [`Location`]s that store the location when the wrapper value was changed.
    pub fn new(
        added: &'w mut [Tick],
        changed: &'w mut [Tick],
        last_run: Tick,
        this_run: Tick,
        caller: MaybeLocation<&'w mut [&'static Location<'static>]>,
    ) -> Option<Self> {
        let eq = added.len() == changed.len()
            && caller
                .as_ref()
                .map(|v| v.len() == added.len())
                .into_option()
                .unwrap_or(true);
        eq.then_some(Self {
            added,
            changed,
            changed_by: caller,
            last_run,
            this_run,
        })
    }

    /// Returns added ticks' slice.
    pub fn added(&self) -> &[Tick] {
        self.added
    }

    /// Returns changed ticks' slice.
    pub fn changed(&self) -> &[Tick] {
        self.changed
    }

    /// Returns changed by locations' slice.
    pub fn changed_by(&self) -> MaybeLocation<&[&'static Location<'static>]> {
        self.changed_by.as_deref()
    }

    /// Returns mutable added ticks' slice.
    pub fn added_mut(&mut self) -> &mut [Tick] {
        self.added
    }

    /// Returns mutable changed ticks' slice.
    pub fn changed_mut(&mut self) -> &mut [Tick] {
        self.changed
    }

    /// Returns mutable changed by locations' slice.
    pub fn changed_by_mut(&mut self) -> MaybeLocation<&mut [&'static Location<'static>]> {
        self.changed_by.as_deref_mut()
    }

    /// Returns the tick the system last ran.
    pub fn last_run(&self) -> Tick {
        self.last_run
    }

    /// Returns the tick of the current system's run.
    pub fn this_run(&self) -> Tick {
        self.this_run
    }

    /// Returns an iterator where the i-th item corresponds to whether the i-th component was
    /// marked as changed. If the value equals [`prim@true`], then the component was changed.
    ///
    /// # Example
    /// ```
    /// # use bevy_ecs::prelude::*;
    /// #
    /// # #[derive(Component)]
    /// # struct A(pub i32);
    ///
    /// fn some_system(mut query: Query<&mut A>) {
    ///     for a in query.contiguous_iter_mut().unwrap() {
    ///         let (a_values, a_ticks) = ContiguousMut::split(a);
    ///         for (value, is_changed) in a_values.iter_mut().zip(a_ticks.is_changed_iter()) {
    ///             if is_changed {
    ///                 value.0 *= 10;
    ///             }
    ///         }
    ///     }
    /// }
    /// ```
    pub fn is_changed_iter(&self) -> impl Iterator<Item = bool> {
        self.changed
            .iter()
            .map(|v| v.is_newer_than(self.last_run, self.this_run))
    }

    /// Returns an iterator where the i-th item corresponds to whether the i-th component was
    /// marked as added. If the value equals [`prim@true`], then the component was added.
    ///
    /// # Example
    /// ```
    /// # use bevy_ecs::prelude::*;
    /// #
    /// # #[derive(Component)]
    /// # struct A(pub i32);
    ///
    /// fn some_system(mut query: Query<&mut A>) {
    ///     for a in query.contiguous_iter_mut().unwrap() {
    ///         let (a_values, a_ticks) = ContiguousMut::split(a);
    ///         for (value, is_added) in a_values.iter_mut().zip(a_ticks.is_added_iter()) {
    ///             if is_added {
    ///                 value.0 = 10;
    ///             }
    ///         }
    ///     }
    /// }
    /// ```
    pub fn is_added_iter(&self) -> impl Iterator<Item = bool> {
        self.added
            .iter()
            .map(|v| v.is_newer_than(self.last_run, self.this_run))
    }

    /// Marks every tick as changed.
    pub fn mark_all_as_changed(&mut self) {
        let this_run = self.this_run;

        self.changed_by.as_mut().map(|v| {
            for v in v.iter_mut() {
                *v = Location::caller();
            }
        });

        for t in self.changed.iter_mut() {
            *t = this_run;
        }
    }

    /// Returns a `ContiguousComponentTicksMut` with a smaller lifetime.
    pub fn reborrow(&mut self) -> ContiguousComponentTicksMut<'_> {
        ContiguousComponentTicksMut {
            added: self.added,
            changed: self.changed,
            changed_by: self.changed_by.as_deref_mut(),
            last_run: self.last_run,
            this_run: self.this_run,
        }
    }
}

impl<'w> From<ContiguousComponentTicksMut<'w>> for ContiguousComponentTicksRef<'w> {
    fn from(value: ContiguousComponentTicksMut<'w>) -> Self {
        Self {
            added: value.added,
            changed: value.changed,
            changed_by: value.changed_by.map(|v| &*v),
            last_run: value.last_run,
            this_run: value.this_run,
        }
    }
}

/// Shared borrow of a [`Resource`].
///
/// See the [`Resource`] documentation for usage.
///
/// If you need a unique mutable borrow, use [`ResMut`] instead.
///
/// This [`SystemParam`](crate::system::SystemParam) fails validation if resource doesn't exist.
/// This will cause a panic, but can be configured to do nothing or warn once.
///
/// Use [`Option<Res<T>>`] instead if the resource might not always exist.
pub struct Res<'w, T: ?Sized + Resource> {
    pub(crate) value: &'w T,
    pub(crate) ticks: ComponentTicksRef<'w>,
}

impl<'w, T: Resource> Res<'w, T> {
    /// Copies a reference to a resource.
    ///
    /// Note that unless you actually need an instance of `Res<T>`, you should
    /// prefer to just convert it to `&T` which can be freely copied.
    #[expect(
        clippy::should_implement_trait,
        reason = "As this struct derefs to the inner resource, a `Clone` trait implementation would interfere with the common case of cloning the inner content."
    )]
    pub fn clone(this: &Self) -> Self {
        Self {
            value: this.value,
            ticks: this.ticks,
        }
    }

    /// Due to lifetime limitations of the `Deref` trait, this method can be used to obtain a
    /// reference of the [`Resource`] with a lifetime bound to `'w` instead of the lifetime of the
    /// struct itself.
    pub fn into_inner(self) -> &'w T {
        self.value
    }
}

impl<'w, T: Resource<Mutability = Mutable>> From<ResMut<'w, T>> for Res<'w, T> {
    fn from(res: ResMut<'w, T>) -> Self {
        Self {
            value: res.value,
            ticks: res.ticks.into(),
        }
    }
}

impl<'w, T: Resource> From<Res<'w, T>> for Ref<'w, T> {
    /// Convert a `Res` into a `Ref`. This allows keeping the change-detection feature of `Ref`
    /// while losing the specificity of `Res` for resources.
    fn from(res: Res<'w, T>) -> Self {
        Self {
            value: res.value,
            ticks: res.ticks,
        }
    }
}

impl<'w, 'a, T: Resource> IntoIterator for &'a Res<'w, T>
where
    &'a T: IntoIterator,
{
    type Item = <&'a T as IntoIterator>::Item;
    type IntoIter = <&'a T as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.value.into_iter()
    }
}
change_detection_impl!(Res<'w, T>, T, Resource);
impl_debug!(Res<'w, T>, Resource);

/// Unique mutable borrow of a [`Resource`].
///
/// See the [`Resource`] documentation for usage.
///
/// If you need a shared borrow, use [`Res`] instead.
///
/// This [`SystemParam`](crate::system::SystemParam) fails validation if resource doesn't exist.
/// This will cause a panic, but can be configured to do nothing or warn once.
///
/// Use [`Option<ResMut<T>>`] instead if the resource might not always exist.
pub struct ResMut<'w, T: ?Sized + Resource<Mutability = Mutable>> {
    pub(crate) value: &'w mut T,
    pub(crate) ticks: ComponentTicksMut<'w>,
}

impl<'w, 'a, T: Resource<Mutability = Mutable>> IntoIterator for &'a ResMut<'w, T>
where
    &'a T: IntoIterator,
{
    type Item = <&'a T as IntoIterator>::Item;
    type IntoIter = <&'a T as IntoIterator>::IntoIter;

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

impl<'w, 'a, T: Resource<Mutability = Mutable>> IntoIterator for &'a mut ResMut<'w, T>
where
    &'a mut T: IntoIterator,
{
    type Item = <&'a mut T as IntoIterator>::Item;
    type IntoIter = <&'a mut T as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.set_changed();
        self.value.into_iter()
    }
}

change_detection_impl!(ResMut<'w, T>, T, Resource<Mutability = Mutable>);
change_detection_mut_impl!(ResMut<'w, T>, T, Resource<Mutability = Mutable>);
impl_methods!(ResMut<'w, T>, T, Resource<Mutability = Mutable>);
impl_debug!(ResMut<'w, T>, Resource<Mutability = Mutable>);

impl<'w, T: Resource<Mutability = Mutable>> From<ResMut<'w, T>> for Mut<'w, T> {
    /// Convert this `ResMut` into a `Mut`. This allows keeping the change-detection feature of `Mut`
    /// while losing the specificity of `ResMut` for resources.
    fn from(other: ResMut<'w, T>) -> Mut<'w, T> {
        Mut {
            value: other.value,
            ticks: other.ticks,
        }
    }
}

/// Shared borrow of a non-[`Send`] resource.
///
/// Only [`Send`] resources may be accessed with the [`Res`] [`SystemParam`](crate::system::SystemParam). In case that the
/// resource does not implement `Send`, this `SystemParam` wrapper can be used. This will instruct
/// the scheduler to instead run the system on the main thread so that it doesn't send the resource
/// over to another thread.
///
/// This [`SystemParam`](crate::system::SystemParam) fails validation if the non-send resource doesn't exist.
/// This will cause a panic, but can be configured to do nothing or warn once.
///
/// Use [`Option<NonSend<T>>`] instead if the resource might not always exist.
pub struct NonSend<'w, T: ?Sized + 'static> {
    pub(crate) value: &'w T,
    pub(crate) ticks: ComponentTicksRef<'w>,
}

change_detection_impl!(NonSend<'w, T>, T,);
impl_debug!(NonSend<'w, T>,);

impl<'w, T> From<NonSendMut<'w, T>> for NonSend<'w, T> {
    fn from(other: NonSendMut<'w, T>) -> Self {
        Self {
            value: other.value,
            ticks: other.ticks.into(),
        }
    }
}

/// Unique borrow of a non-[`Send`] resource.
///
/// Only [`Send`] resources may be accessed with the [`ResMut`] [`SystemParam`](crate::system::SystemParam). In case that the
/// resource does not implement `Send`, this `SystemParam` wrapper can be used. This will instruct
/// the scheduler to instead run the system on the main thread so that it doesn't send the resource
/// over to another thread.
///
/// This [`SystemParam`](crate::system::SystemParam) fails validation if non-send resource doesn't exist.
/// This will cause a panic, but can be configured to do nothing or warn once.
///
/// Use [`Option<NonSendMut<T>>`] instead if the resource might not always exist.
pub struct NonSendMut<'w, T: ?Sized + 'static> {
    pub(crate) value: &'w mut T,
    pub(crate) ticks: ComponentTicksMut<'w>,
}

change_detection_impl!(NonSendMut<'w, T>, T,);
change_detection_mut_impl!(NonSendMut<'w, T>, T,);
impl_methods!(NonSendMut<'w, T>, T,);
impl_debug!(NonSendMut<'w, T>,);

impl<'w, T: 'static> From<NonSendMut<'w, T>> for Mut<'w, T> {
    /// Convert this `NonSendMut` into a `Mut`. This allows keeping the change-detection feature of `Mut`
    /// while losing the specificity of `NonSendMut`.
    fn from(other: NonSendMut<'w, T>) -> Mut<'w, T> {
        Mut {
            value: other.value,
            ticks: other.ticks,
        }
    }
}

/// Shared borrow of an entity's component with access to change detection.
/// Similar to [`Mut`] but is immutable and so doesn't require unique access.
///
/// # Examples
///
/// These two systems produce the same output.
///
/// ```
/// # use bevy_ecs::change_detection::DetectChanges;
/// # use bevy_ecs::query::{Changed, With};
/// # use bevy_ecs::system::Query;
/// # use bevy_ecs::world::Ref;
/// # use bevy_ecs_macros::Component;
/// # #[derive(Component)]
/// # struct MyComponent;
///
/// fn how_many_changed_1(query: Query<(), Changed<MyComponent>>) {
///     println!("{} changed", query.iter().count());
/// }
///
/// fn how_many_changed_2(query: Query<Ref<MyComponent>>) {
///     println!("{} changed", query.iter().filter(|c| c.is_changed()).count());
/// }
/// ```
pub struct Ref<'w, T: ?Sized> {
    pub(crate) value: &'w T,
    pub(crate) ticks: ComponentTicksRef<'w>,
}

impl<'w, T: ?Sized> Ref<'w, T> {
    /// Returns the reference wrapped by this type. The reference is allowed to outlive `self`, which makes this method more flexible than simply borrowing `self`.
    pub fn into_inner(self) -> &'w T {
        self.value
    }

    /// Map `Ref` to a different type using `f`.
    ///
    /// This doesn't do anything else than call `f` on the wrapped value.
    /// This is equivalent to [`Mut::map_unchanged`].
    pub fn map<U: ?Sized>(self, f: impl FnOnce(&T) -> &U) -> Ref<'w, U> {
        Ref {
            value: f(self.value),
            ticks: self.ticks,
        }
    }

    /// Create a new `Ref` using provided values.
    ///
    /// This is an advanced feature, `Ref`s are designed to be _created_ by
    /// engine-internal code and _consumed_ by end-user code.
    ///
    /// - `value` - The value wrapped by `Ref`.
    /// - `added` - A [`Tick`] that stores the tick when the wrapped value was created.
    /// - `changed` - A [`Tick`] that stores the last time the wrapped value was changed.
    /// - `last_run` - A [`Tick`], occurring before `this_run`, which is used
    ///   as a reference to determine whether the wrapped value is newly added or changed.
    /// - `this_run` - A [`Tick`] corresponding to the current point in time -- "now".
    pub fn new(
        value: &'w T,
        added: &'w Tick,
        changed: &'w Tick,
        last_run: Tick,
        this_run: Tick,
        caller: MaybeLocation<&'w &'static Location<'static>>,
    ) -> Ref<'w, T> {
        Ref {
            value,
            ticks: ComponentTicksRef {
                added,
                changed,
                changed_by: caller,
                last_run,
                this_run,
            },
        }
    }

    /// Overwrite the `last_run` and `this_run` tick that are used for change detection.
    ///
    /// This is an advanced feature. `Ref`s are usually _created_ by engine-internal code and
    /// _consumed_ by end-user code.
    pub fn set_ticks(&mut self, last_run: Tick, this_run: Tick) {
        self.ticks.last_run = last_run;
        self.ticks.this_run = this_run;
    }
}

// `Ref` is `Copy` to facilitate creation of split borrows. Compared to `Res`
// (which isn't `Copy`), `Ref` is not as widely used so can afford to require
// `ref.as_ref().clone()` or `ref.deref().clone()` in order to clone the inner `T`.
impl<'w, T: ?Sized> Copy for Ref<'w, T> {}

impl<'w, T: ?Sized> Clone for Ref<'w, T> {
    fn clone(&self) -> Self {
        *self
    }
}

/// Contiguous equivalent of [`Ref<T>`].
///
/// Data type returned by [`ContiguousQueryData::fetch_contiguous`](crate::query::ContiguousQueryData::fetch_contiguous) for [`Ref<T>`].
#[derive(Clone)]
pub struct ContiguousRef<'w, T> {
    pub(crate) value: &'w [T],
    pub(crate) ticks: ContiguousComponentTicksRef<'w>,
}

impl<'w, T> ContiguousRef<'w, T> {
    /// Returns the reference wrapped by this type. The reference is allowed to outlive `self`, which makes this method more flexible than simply borrowing `self`.
    pub fn into_inner(self) -> &'w [T] {
        self.value
    }

    /// Returns the added ticks.
    #[inline]
    pub fn added_ticks_slice(&self) -> &'w [Tick] {
        self.ticks.added
    }

    /// Returns the changed ticks.
    #[inline]
    pub fn changed_ticks_slice(&self) -> &'w [Tick] {
        self.ticks.changed
    }

    /// Returns the changed by ticks.
    #[inline]
    pub fn changed_by_ticks_slice(&self) -> MaybeLocation<&[&'static Location<'static>]> {
        self.ticks.changed_by.as_deref()
    }

    /// Returns the tick when the system last ran.
    #[inline]
    pub fn last_run_tick(&self) -> Tick {
        self.ticks.last_run
    }

    /// Returns the tick of the system's current run.
    #[inline]
    pub fn this_run_tick(&self) -> Tick {
        self.ticks.this_run
    }

    /// Creates a new `ContiguousRef` using provided values or returns [`None`] if lengths of
    /// `value`, `added`, `changed` and `changed_by` do not match    
    ///
    /// This is an advanced feature, `ContiguousRef`s are designed to be _created_ by
    /// engine-internal code and _consumed_ by end-user code.
    ///
    /// - `value` - The values wrapped by `ContiguousRef`.
    /// - `added` - [`Tick`]s that store the tick when the wrapped value was created.
    /// - `changed` - [`Tick`]s that store the last time the wrapped value was changed.
    /// - `last_run` - A [`Tick`], occurring before `this_run`, which is used
    ///   as a reference to determine whether the wrapped value is newly added or changed.
    /// - `this_run` - A [`Tick`] corresponding to the current point in time -- "now".
    /// - `caller` - [`Location`]s that store the location when the wrapper value was changed.
    pub fn new(
        value: &'w [T],
        added: &'w [Tick],
        changed: &'w [Tick],
        last_run: Tick,
        this_run: Tick,
        caller: MaybeLocation<&'w [&'static Location<'static>]>,
    ) -> Option<Self> {
        (value.len() == added.len())
            .then(|| ContiguousComponentTicksRef::new(added, changed, last_run, this_run, caller))
            .flatten()
            .map(|ticks| Self { value, ticks })
    }

    /// Splits [`ContiguousRef`] into it's inner data types.
    pub fn split(this: Self) -> (&'w [T], ContiguousComponentTicksRef<'w>) {
        (this.value, this.ticks)
    }

    /// Reverse of [`ContiguousRef::split`], constructing a [`ContiguousRef`] using components'
    /// values and ticks.
    ///
    /// Returns [`None`] if lengths of `value` and `ticks` do not match, which doesn't happen if
    /// `ticks` and `value` come from the same [`Self::split`] call.
    pub fn from_parts(value: &'w [T], ticks: ContiguousComponentTicksRef<'w>) -> Option<Self> {
        (value.len() == ticks.changed.len()).then_some(Self { value, ticks })
    }
}

impl<'w, T> Deref for ContiguousRef<'w, T> {
    type Target = [T];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.value
    }
}

impl<'w, T> AsRef<[T]> for ContiguousRef<'w, T> {
    #[inline]
    fn as_ref(&self) -> &[T] {
        self.deref()
    }
}

impl<'w, T> IntoIterator for ContiguousRef<'w, T> {
    type Item = &'w T;

    type IntoIter = core::slice::Iter<'w, T>;

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

impl<'w, T: core::fmt::Debug> core::fmt::Debug for ContiguousRef<'w, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("ContiguousRef").field(&self.value).finish()
    }
}

impl<'w, 'a, T> IntoIterator for &'a Ref<'w, T>
where
    &'a T: IntoIterator,
{
    type Item = <&'a T as IntoIterator>::Item;
    type IntoIter = <&'a T as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.value.into_iter()
    }
}
change_detection_impl!(Ref<'w, T>, T,);
impl_debug!(Ref<'w, T>,);

/// Unique mutable borrow of an entity's component or of a resource.
///
/// This can be used in queries to access change detection from immutable query methods, as opposed
/// to `&mut T` which only provides access to change detection from mutable query methods.
///
/// ```rust
/// # use bevy_ecs::prelude::*;
/// # use bevy_ecs::query::QueryData;
/// #
/// #[derive(Component, Clone, Debug)]
/// struct Name(String);
///
/// #[derive(Component, Clone, Copy, Debug)]
/// struct Health(f32);
///
/// fn my_system(mut query: Query<(Mut<Name>, &mut Health)>) {
///     // Mutable access provides change detection information for both parameters:
///     // - `name` has type `Mut<Name>`
///     // - `health` has type `Mut<Health>`
///     for (name, health) in query.iter_mut() {
///         println!("Name: {:?} (last changed {:?})", name, name.last_changed());
///         println!("Health: {:?} (last changed: {:?})", health, health.last_changed());
/// #        println!("{}{}", name.0, health.0); // Silence dead_code warning
///     }
///
///     // Immutable access only provides change detection for `Name`:
///     // - `name` has type `Ref<Name>`
///     // - `health` has type `&Health`
///     for (name, health) in query.iter() {
///         println!("Name: {:?} (last changed {:?})", name, name.last_changed());
///         println!("Health: {:?}", health);
///     }
/// }
///
/// # bevy_ecs::system::assert_is_system(my_system);
/// ```
pub struct Mut<'w, T: ?Sized> {
    pub(crate) value: &'w mut T,
    pub(crate) ticks: ComponentTicksMut<'w>,
}

impl<'w, T: ?Sized> Mut<'w, T> {
    /// Creates a new change-detection enabled smart pointer.
    /// In almost all cases you do not need to call this method manually,
    /// as instances of `Mut` will be created by engine-internal code.
    ///
    /// Many use-cases of this method would be better served by [`Mut::map_unchanged`]
    /// or [`Mut::reborrow`].
    ///
    /// - `value` - The value wrapped by this smart pointer.
    /// - `added` - A [`Tick`] that stores the tick when the wrapped value was created.
    /// - `last_changed` - A [`Tick`] that stores the last time the wrapped value was changed.
    ///   This will be updated to the value of `change_tick` if the returned smart pointer
    ///   is modified.
    /// - `last_run` - A [`Tick`], occurring before `this_run`, which is used
    ///   as a reference to determine whether the wrapped value is newly added or changed.
    /// - `this_run` - A [`Tick`] corresponding to the current point in time -- "now".
    pub fn new(
        value: &'w mut T,
        added: &'w mut Tick,
        last_changed: &'w mut Tick,
        last_run: Tick,
        this_run: Tick,
        caller: MaybeLocation<&'w mut &'static Location<'static>>,
    ) -> Self {
        Self {
            value,
            ticks: ComponentTicksMut {
                added,
                changed: last_changed,
                changed_by: caller,
                last_run,
                this_run,
            },
        }
    }

    /// Overwrite the `last_run` and `this_run` tick that are used for change detection.
    ///
    /// This is an advanced feature. `Mut`s are usually _created_ by engine-internal code and
    /// _consumed_ by end-user code.
    pub fn set_ticks(&mut self, last_run: Tick, this_run: Tick) {
        self.ticks.last_run = last_run;
        self.ticks.this_run = this_run;
    }
}

/// Data type returned by [`ContiguousQueryData::fetch_contiguous`](crate::query::ContiguousQueryData::fetch_contiguous)
/// for [`Mut<T>`] and `&mut T`
///
/// # Warning
/// Implementations of [`DerefMut`], [`AsMut`] and [`IntoIterator`] update change ticks, which may effect performance.
pub struct ContiguousMut<'w, T> {
    pub(crate) value: &'w mut [T],
    pub(crate) ticks: ContiguousComponentTicksMut<'w>,
}

impl<'w, T> ContiguousMut<'w, T> {
    /// Manually bypasses change detection, allowing you to mutate the underlying values without updating the change tick,
    /// which may be useful to reduce amount of work to be done.
    ///
    /// # Warning
    /// This is a risky operation, that can have unexpected consequences on any system relying on this code.
    /// However, it can be an essential escape hatch when, for example,
    /// you are trying to synchronize representations using change detection and need to avoid infinite recursion.
    #[inline]
    pub fn bypass_change_detection(&mut self) -> &mut [T] {
        self.value
    }

    /// Returns the immutable added ticks' slice.
    #[inline]
    pub fn added_ticks_slice(&self) -> &[Tick] {
        self.ticks.added
    }

    /// Returns the immutable changed ticks' slice.
    #[inline]
    pub fn changed_ticks_slice(&self) -> &[Tick] {
        self.ticks.changed
    }

    /// Returns the mutable changed by ticks' slice
    #[inline]
    pub fn changed_by_ticks_mut(&self) -> MaybeLocation<&[&'static Location<'static>]> {
        self.ticks.changed_by.as_deref()
    }

    /// Returns the tick when the system last ran.
    #[inline]
    pub fn last_run_tick(&self) -> Tick {
        self.ticks.last_run
    }

    /// Returns the tick of the system's current run.
    #[inline]
    pub fn this_run_tick(&self) -> Tick {
        self.ticks.this_run
    }

    /// Returns the mutable added ticks' slice.
    #[inline]
    pub fn added_ticks_slice_mut(&mut self) -> &mut [Tick] {
        self.ticks.added
    }

    /// Returns the mutable changed ticks' slice.
    #[inline]
    pub fn changed_ticks_slice_mut(&mut self) -> &mut [Tick] {
        self.ticks.changed
    }

    /// Returns the mutable changed by ticks' slice
    #[inline]
    pub fn changed_by_ticks_slice_mut(
        &mut self,
    ) -> MaybeLocation<&mut [&'static Location<'static>]> {
        self.ticks.changed_by.as_deref_mut()
    }

    /// Marks all components as changed.
    ///
    /// **Runs in O(n), where n is the amount of rows**
    #[inline]
    pub fn mark_all_as_changed(&mut self) {
        self.ticks.mark_all_as_changed();
    }

    /// Creates a new `ContiguousMut` using provided values or returns [`None`] if lengths of
    /// `value`, `added`, `changed` and `changed_by` do not match    
    ///
    /// This is an advanced feature, `ContiguousMut`s are designed to be _created_ by
    /// engine-internal code and _consumed_ by end-user code.
    ///
    /// - `value` - The values wrapped by `ContiguousMut`.
    /// - `added` - [`Tick`]s that store the tick when the wrapped value was created.
    /// - `changed` - [`Tick`]s that store the last time the wrapped value was changed.
    /// - `last_run` - A [`Tick`], occurring before `this_run`, which is used
    ///   as a reference to determine whether the wrapped value is newly added or changed.
    /// - `this_run` - A [`Tick`] corresponding to the current point in time -- "now".
    /// - `caller` - [`Location`]s that store the location when the wrapper value was changed.
    pub fn new(
        value: &'w mut [T],
        added: &'w mut [Tick],
        changed: &'w mut [Tick],
        last_run: Tick,
        this_run: Tick,
        caller: MaybeLocation<&'w mut [&'static Location<'static>]>,
    ) -> Option<Self> {
        (value.len() == added.len())
            .then(|| ContiguousComponentTicksMut::new(added, changed, last_run, this_run, caller))
            .flatten()
            .map(|ticks| Self { value, ticks })
    }

    /// Returns a `ContiguousMut<T>` with a smaller lifetime.
    pub fn reborrow(&mut self) -> ContiguousMut<'_, T> {
        ContiguousMut {
            value: self.value,
            ticks: self.ticks.reborrow(),
        }
    }

    /// Splits [`ContiguousMut`] into it's inner data types. It may be useful, when you want to
    /// have an iterator over component values and check ticks simultaneously (using
    /// [`ContiguousComponentTicksMut::is_changed_iter`] and
    /// [`ContiguousComponentTicksMut::is_added_iter`]).
    ///
    /// Variant of [`Self::split`] which bypasses change detection: [`Self::bypass_change_detection_split`].
    ///
    /// Reverse of [`Self::split`] is [`Self::from_parts`].
    ///
    /// # Warning
    /// This version updates changed ticks **before** returning, hence
    /// [`ContiguousComponentTicksMut::is_changed_iter`] will be useless (the iterator will be filled with
    /// [`prim@true`]s).
    // NOTE: `ticks_since_insert` will be 0 (because `this.mark_all_as_changed` makes all changed ticks `this_run`),
    // `ticks_since_system` won't be 0, `tick` is newer if
    // `ticks_since_system` > `ticks_since_insert`, hence it will always be true.
    pub fn split(mut this: Self) -> (&'w mut [T], ContiguousComponentTicksMut<'w>) {
        this.mark_all_as_changed();
        (this.value, this.ticks)
    }

    /// Splits [`ContiguousMut`] into it's inner data types. It may be useful, when you want to
    /// have an iterator over component values and check ticks simultaneously (using
    /// [`ContiguousComponentTicksMut::is_changed_iter`] and
    /// [`ContiguousComponentTicksMut::is_added_iter`]).
    ///
    /// Variant of [`Self::bypass_change_detection_split`] which **does not** bypass change detection: [`Self::split`].
    ///
    /// Reverse of [`Self::bypass_change_detection_split`] is [`Self::from_parts`].
    ///
    /// # Warning
    /// **Bypasses change detection**, call [`Self::split`] if you don't want to bypass it.
    ///
    /// See [`Self::bypass_change_detection`] for further explanations.
    pub fn bypass_change_detection_split(
        this: Self,
    ) -> (&'w mut [T], ContiguousComponentTicksMut<'w>) {
        (this.value, this.ticks)
    }

    /// Reverse of [`ContiguousMut::split`] and [`ContiguousMut::bypass_change_detection_split`],
    /// constructing a [`ContiguousMut`] using components' values and ticks.
    ///
    /// Returns [`None`] if lengths of `value` and `ticks` do not match, which doesn't happen if
    /// `ticks` and `value` come from the same [`Self::split`] or [`Self::bypass_change_detection_split`] call.
    pub fn from_parts(value: &'w mut [T], ticks: ContiguousComponentTicksMut<'w>) -> Option<Self> {
        (value.len() == ticks.changed.len()).then_some(Self { value, ticks })
    }
}

impl<'w, T> Deref for ContiguousMut<'w, T> {
    type Target = [T];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.value
    }
}

impl<'w, T> DerefMut for ContiguousMut<'w, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.mark_all_as_changed();
        self.value
    }
}

impl<'w, T> AsRef<[T]> for ContiguousMut<'w, T> {
    #[inline]
    fn as_ref(&self) -> &[T] {
        self.deref()
    }
}

impl<'w, T> AsMut<[T]> for ContiguousMut<'w, T> {
    #[inline]
    fn as_mut(&mut self) -> &mut [T] {
        self.deref_mut()
    }
}

impl<'w, T> IntoIterator for ContiguousMut<'w, T> {
    type Item = &'w mut T;

    type IntoIter = core::slice::IterMut<'w, T>;

    fn into_iter(mut self) -> Self::IntoIter {
        self.mark_all_as_changed();
        self.value.iter_mut()
    }
}

impl<'w, T: core::fmt::Debug> core::fmt::Debug for ContiguousMut<'w, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("ContiguousMut").field(&self.value).finish()
    }
}

impl<'w, T> From<ContiguousMut<'w, T>> for ContiguousRef<'w, T> {
    fn from(value: ContiguousMut<'w, T>) -> Self {
        Self {
            value: value.value,
            ticks: value.ticks.into(),
        }
    }
}

impl<'w, T: ?Sized> From<Mut<'w, T>> for Ref<'w, T> {
    fn from(mut_ref: Mut<'w, T>) -> Self {
        Self {
            value: mut_ref.value,
            ticks: mut_ref.ticks.into(),
        }
    }
}

impl<'w, 'a, T> IntoIterator for &'a Mut<'w, T>
where
    &'a T: IntoIterator,
{
    type Item = <&'a T as IntoIterator>::Item;
    type IntoIter = <&'a T as IntoIterator>::IntoIter;

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

impl<'w, 'a, T> IntoIterator for &'a mut Mut<'w, T>
where
    &'a mut T: IntoIterator,
{
    type Item = <&'a mut T as IntoIterator>::Item;
    type IntoIter = <&'a mut T as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.set_changed();
        self.value.into_iter()
    }
}

change_detection_impl!(Mut<'w, T>, T,);
change_detection_mut_impl!(Mut<'w, T>, T,);
impl_methods!(Mut<'w, T>, T,);
impl_debug!(Mut<'w, T>,);

/// Unique mutable borrow of resources or an entity's component.
///
/// Similar to [`Mut`], but not generic over the component type, instead
/// exposing the raw pointer as a `*mut ()`.
///
/// Usually you don't need to use this and can instead use the APIs returning a
/// [`Mut`], but in situations where the types are not known at compile time
/// or are defined outside of rust this can be used.
pub struct MutUntyped<'w> {
    pub(crate) value: PtrMut<'w>,
    pub(crate) ticks: ComponentTicksMut<'w>,
}

impl<'w> MutUntyped<'w> {
    /// Returns the pointer to the value, marking it as changed.
    ///
    /// In order to avoid marking the value as changed, you need to call [`bypass_change_detection`](DetectChangesMut::bypass_change_detection).
    #[inline]
    pub fn into_inner(mut self) -> PtrMut<'w> {
        self.set_changed();
        self.value
    }

    /// Returns a [`MutUntyped`] with a smaller lifetime.
    /// This is useful if you have `&mut MutUntyped`, but you need a `MutUntyped`.
    #[inline]
    pub fn reborrow(&mut self) -> MutUntyped<'_> {
        MutUntyped {
            value: self.value.reborrow(),
            ticks: ComponentTicksMut {
                added: self.ticks.added,
                changed: self.ticks.changed,
                changed_by: self.ticks.changed_by.as_deref_mut(),
                last_run: self.ticks.last_run,
                this_run: self.ticks.this_run,
            },
        }
    }

    /// Returns `true` if this value was changed or mutably dereferenced
    /// either since a specific change tick.
    pub fn has_changed_since(&self, tick: Tick) -> bool {
        self.ticks.changed.is_newer_than(tick, self.ticks.this_run)
    }

    /// Returns a pointer to the value without taking ownership of this smart pointer, marking it as changed.
    ///
    /// In order to avoid marking the value as changed, you need to call [`bypass_change_detection`](DetectChangesMut::bypass_change_detection).
    #[inline]
    pub fn as_mut(&mut self) -> PtrMut<'_> {
        self.set_changed();
        self.value.reborrow()
    }

    /// Returns an immutable pointer to the value without taking ownership.
    #[inline]
    pub fn as_ref(&self) -> Ptr<'_> {
        self.value.as_ref()
    }

    /// Turn this [`MutUntyped`] into a [`Mut`] by mapping the inner [`PtrMut`] to another value,
    /// without flagging a change.
    /// This function is the untyped equivalent of [`Mut::map_unchanged`].
    ///
    /// You should never modify the argument passed to the closure – if you want to modify the data without flagging a change, consider using [`bypass_change_detection`](DetectChangesMut::bypass_change_detection) to make your intent explicit.
    ///
    /// If you know the type of the value you can do
    /// ```no_run
    /// # use bevy_ecs::change_detection::{Mut, MutUntyped};
    /// # let mut_untyped: MutUntyped = unimplemented!();
    /// // SAFETY: ptr is of type `u8`
    /// mut_untyped.map_unchanged(|ptr| unsafe { ptr.deref_mut::<u8>() });
    /// ```
    /// If you have a [`ReflectFromPtr`](bevy_reflect::ReflectFromPtr) that you know belongs to this [`MutUntyped`],
    /// you can do
    /// ```no_run
    /// # use bevy_ecs::change_detection::{Mut, MutUntyped};
    /// # let mut_untyped: MutUntyped = unimplemented!();
    /// # let reflect_from_ptr: bevy_reflect::ReflectFromPtr = unimplemented!();
    /// // SAFETY: from the context it is known that `ReflectFromPtr` was made for the type of the `MutUntyped`
    /// mut_untyped.map_unchanged(|ptr| unsafe { reflect_from_ptr.as_reflect_mut(ptr) });
    /// ```
    pub fn map_unchanged<T: ?Sized>(self, f: impl FnOnce(PtrMut<'w>) -> &'w mut T) -> Mut<'w, T> {
        Mut {
            value: f(self.value),
            ticks: self.ticks,
        }
    }

    /// Transforms this [`MutUntyped`] into a [`Mut<T>`] with the same lifetime.
    ///
    /// # Safety
    /// - `T` must be the erased pointee type for this [`MutUntyped`].
    pub unsafe fn with_type<T>(self) -> Mut<'w, T> {
        Mut {
            // SAFETY: `value` is `Aligned` and caller ensures the pointee type is `T`.
            value: unsafe { self.value.deref_mut() },
            ticks: self.ticks,
        }
    }
}

impl<'w> DetectChanges for MutUntyped<'w> {
    #[inline]
    fn is_added(&self) -> bool {
        self.is_added_after(self.ticks.last_run)
    }

    #[inline]
    fn is_changed(&self) -> bool {
        self.is_changed_after(self.ticks.last_run)
    }

    #[inline]
    fn is_added_after(&self, other: Tick) -> bool {
        self.ticks.added.is_newer_than(other, self.ticks.this_run)
    }

    #[inline]
    fn is_changed_after(&self, other: Tick) -> bool {
        self.ticks.changed.is_newer_than(other, self.ticks.this_run)
    }

    #[inline]
    fn last_changed(&self) -> Tick {
        *self.ticks.changed
    }

    #[inline]
    fn changed_by(&self) -> MaybeLocation {
        self.ticks.changed_by.copied()
    }

    #[inline]
    fn added(&self) -> Tick {
        *self.ticks.added
    }
}

impl<'w> DetectChangesMut for MutUntyped<'w> {
    type Inner = PtrMut<'w>;

    #[inline]
    #[track_caller]
    fn set_changed(&mut self) {
        *self.ticks.changed = self.ticks.this_run;
        self.ticks.changed_by.assign(MaybeLocation::caller());
    }

    #[inline]
    #[track_caller]
    fn set_added(&mut self) {
        *self.ticks.changed = self.ticks.this_run;
        *self.ticks.added = self.ticks.this_run;
        self.ticks.changed_by.assign(MaybeLocation::caller());
    }

    #[inline]
    #[track_caller]
    fn set_last_changed(&mut self, last_changed: Tick) {
        *self.ticks.changed = last_changed;
        self.ticks.changed_by.assign(MaybeLocation::caller());
    }

    #[inline]
    #[track_caller]
    fn set_last_added(&mut self, last_added: Tick) {
        *self.ticks.added = last_added;
        *self.ticks.changed = last_added;
        self.ticks.changed_by.assign(MaybeLocation::caller());
    }

    #[inline]
    #[track_caller]
    fn bypass_change_detection(&mut self) -> &mut Self::Inner {
        &mut self.value
    }
}

impl core::fmt::Debug for MutUntyped<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("MutUntyped")
            .field(&self.value.as_ptr())
            .finish()
    }
}

impl<'w, T> From<Mut<'w, T>> for MutUntyped<'w> {
    fn from(value: Mut<'w, T>) -> Self {
        MutUntyped {
            value: value.value.into(),
            ticks: value.ticks,
        }
    }
}