soa-rs 1.0.0

A Vec-like structure-of-arrays container
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
use crate::{
    AsMutSlice, AsSlice, Iter, IterMut, SliceMut, SliceRef, SoaClone, SoaDeref, SoaRaw, Soars, Vec,
    chunks_exact::ChunksExact, index::SoaIndex, iter_raw::IterRaw,
};
use core::{
    cmp::Ordering,
    fmt::{self, Debug, Formatter},
    hash::{Hash, Hasher},
    marker::PhantomData,
    ops::{ControlFlow, Deref, DerefMut},
};

/// A dynamically-sized view into the contents of a [`Soa`].
///
/// [`Slice`] and [`Soa`] have the same relationship as `[T]` and `Vec`. The
/// related types [`SliceRef`] and [`SliceMut`] are equivalent to `&[T]` and
/// `&mut [T]`.
///
/// This struct provides most of the implementation for [`Soa`], [`SliceRef`],
/// and [`SliceMut`] via [`Deref`] impls. It is not usually constructed directly
/// but instead used through one of these other types. The [`SliceRef`] and
/// [`SliceMut`] wrappers attach lifetimes and ensure the same borrowing rules
/// as `&` and `&mut`.
///
/// While [`Vec`] can return `&[T]` for all its slice methods, returning
/// `&Slice` is not always possible. That is why [`SliceRef`] and [`SliceMut`]
/// are necessary. While fat pointers allow packing length information as slice
/// metadata, this is insufficient for SoA slices, which require multiple
/// pointers alongside the length. Therefore, SoA slice references cannot be
/// created on the stack and returned like normal slices can.
///
/// [`Soa`]: crate::Soa
/// [`SliceRef`]: crate::SliceRef
/// [`SliceMut`]: crate::SliceMut
pub struct Slice<T: Soars, D: ?Sized = [()]> {
    pub(crate) raw: T::Raw,
    pub(crate) dst: D,
}

unsafe impl<T: Soars, D: ?Sized> Sync for Slice<T, D> where T: Sync {}
unsafe impl<T: Soars, D: ?Sized> Send for Slice<T, D> where T: Send {}

/// ```compile_fail,E0277
/// use core::marker::PhantomData;
/// use soa_rs::{soa, Soars};
///
/// fn assert_send<T: Send>(_t: T) {}
///
/// #[derive(Soars)]
/// struct NoSendSync(PhantomData<*mut ()>);
///
/// assert_send(soa![NoSendSync(PhantomData)]);
/// ```
///
/// ```compile_fail,E0277
/// use core::marker::PhantomData;
/// use soa_rs::{soa, Soars};
///
/// fn assert_sync<T: Sync>(_t: T) {}
///
/// #[derive(Soars)]
/// struct NoSendSync(PhantomData<*mut ()>);
///
/// assert_sync(soa![NoSendSync(PhantomData)]);
/// ```
mod send_sync_fail {}

impl<T> Slice<T, ()>
where
    T: Soars,
{
    /// Constructs a new, empty `Slice<T>`.
    pub(crate) fn empty() -> Self {
        Self::with_raw(<T::Raw as SoaRaw>::dangling())
    }

    /// Creates a new slice with the given [`SoaRaw`]. This is intended for use
    /// in proc macro code, not user code.
    #[doc(hidden)]
    pub const fn with_raw(raw: T::Raw) -> Self {
        Self { raw, dst: () }
    }

    /// Converts to an mutable unsized variant.
    ///
    /// # Safety
    ///
    /// - `length` must be valid for the underlying type `T`.
    /// - The lifetime of the returned reference is unconstrained. Ensure that
    ///   the right lifetimes are applied.
    pub(crate) const unsafe fn as_unsized_mut<'a>(&mut self, len: usize) -> &'a mut Slice<T> {
        let ptr = core::ptr::slice_from_raw_parts_mut(self, len) as *mut Slice<T>;
        unsafe { &mut *ptr }
    }

    /// Converts to an unsized variant.
    ///
    /// # Safety
    ///
    /// - `length` must be valid for the underlying type `T`.
    /// - The lifetime of the returned reference is unconstrained. Ensure that
    ///   the right lifetimes are applied.
    pub(crate) const unsafe fn as_unsized<'a>(&self, len: usize) -> &'a Slice<T> {
        let ptr = core::ptr::slice_from_raw_parts(self, len) as *const Slice<T>;
        unsafe { &*ptr }
    }
}

impl<T, D> Slice<T, D>
where
    T: Soars,
    D: ?Sized,
{
    /// Gets the [`SoaRaw`] the slice uses.
    ///
    /// Used by the [`Soars`] derive macro, but generally not intended for use
    /// by end users.
    #[doc(hidden)]
    #[inline]
    pub const fn raw(&self) -> T::Raw {
        self.raw
    }
}

impl<T> Slice<T>
where
    T: Soars,
{
    /// Returns the number of elements in the slice, also referred to as its
    /// length.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let soa = soa![Foo(1), Foo(2), Foo(3)];
    /// assert_eq!(soa.len(), 3);
    /// ```
    pub const fn len(&self) -> usize {
        self.dst.len()
    }

    /// Returns true if the slice contains no elements.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars};
    /// # #[derive(Soars)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let mut soa = Soa::<Foo>::new();
    /// assert!(soa.is_empty());
    /// soa.push(Foo(1));
    /// assert!(!soa.is_empty());
    /// ```
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns an iterator over the elements.
    ///
    /// The iterator yields all items from start to end.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # use core::fmt;
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let soa = soa![Foo(1), Foo(2), Foo(4)];
    /// let mut iter = soa.iter();
    /// assert_eq!(iter.next(), Some(FooRef(&1)));
    /// assert_eq!(iter.next(), Some(FooRef(&2)));
    /// assert_eq!(iter.next(), Some(FooRef(&4)));
    /// assert_eq!(iter.next(), None);
    /// ```
    pub const fn iter(&self) -> Iter<'_, T> {
        Iter {
            iter_raw: IterRaw {
                // SAFETY: The Iter lifetime is bound to &self,
                // which ensures the aliasing rules are respected.
                slice: unsafe { self.as_sized() },
                len: self.len(),
                adapter: PhantomData,
            },
            _marker: PhantomData,
        }
    }

    /// Returns an iterator over the elements that allows modifying each value.
    ///
    /// The iterator yields all items from start to end.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # use core::fmt;
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let mut soa = soa![Foo(1), Foo(2), Foo(4)];
    /// for mut elem in soa.iter_mut() {
    ///     *elem.0 *= 2;
    /// }
    /// assert_eq!(soa, soa![Foo(2), Foo(4), Foo(8)]);
    /// ```
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        IterMut {
            iter_raw: IterRaw {
                // SAFETY: The Iter lifetime is bound to &self,
                // which ensures the aliasing rules are respected.
                slice: unsafe { self.as_sized() },
                len: self.len(),
                adapter: PhantomData,
            },
            _marker: PhantomData,
        }
    }

    /// Returns a reference to an element or subslice depending on the type of
    /// index.
    ///
    /// - If given a position, returns a reference to the element at that
    ///   position or None if out of bounds.
    ///
    /// - If given a range, returns the subslice corresponding to that range, or
    ///   None if out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// # use core::fmt;
    /// # use soa_rs::{Soa, Soars, soa, Slice, AsSlice};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(PartialEq, Debug)]
    /// # struct Foo(usize);
    /// let soa = soa![Foo(10), Foo(40), Foo(30), Foo(20)];
    /// assert_eq!(soa.get(1), Some(FooRef(&40)));
    /// assert!(soa.get(4).is_none());
    /// assert_eq!(soa.get(..), Some(soa![Foo(10), Foo(40), Foo(30), Foo(20)].as_slice()));
    /// assert_eq!(soa.get(..2), Some(soa![Foo(10), Foo(40)].as_slice()));
    /// assert_eq!(soa.get(..=2), Some(soa![Foo(10), Foo(40), Foo(30)].as_slice()));
    /// assert_eq!(soa.get(2..), Some(soa![Foo(30), Foo(20)].as_slice()));
    /// assert_eq!(soa.get(1..3), Some(soa![Foo(40), Foo(30)].as_slice()));
    /// assert_eq!(soa.get(1..=3), Some(soa![Foo(40), Foo(30), Foo(20)].as_slice()));
    /// assert!(soa.get(2..5).is_none());
    /// ```
    #[inline]
    pub fn get<I>(&self, index: I) -> Option<I::Output<'_>>
    where
        I: SoaIndex<T>,
    {
        index.get(self)
    }

    /// Returns a mutable reference to an element or subslice depending on the
    /// type of index (see [`get`]) or `None` if the index is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let mut soa = soa![Foo(1), Foo(2), Foo(3)];
    /// if let Some(mut elem) = soa.get_mut(1) {
    ///     *elem.0 = 42;
    /// }
    /// assert_eq!(soa, soa![Foo(1), Foo(42), Foo(3)]);
    /// ```
    ///
    /// [`get`]: Slice::get
    pub fn get_mut<I>(&mut self, index: I) -> Option<I::OutputMut<'_>>
    where
        I: SoaIndex<T>,
    {
        index.get_mut(self)
    }

    /// Returns a reference to the element at the given index.
    ///
    /// This is similar to [`Index`], which is not implementable for this type.
    /// See [`get`] for a non-panicking version.
    ///
    /// # Panics
    ///
    /// Panics if the index is out-of-bounds, which is whenever
    /// [`SoaIndex::get`] returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use core::fmt;
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let soa = soa![Foo(10), Foo(40), Foo(30), Foo(90)];
    /// assert_eq!(soa.idx(3), FooRef(&90));
    /// assert_eq!(soa.idx(1..3), soa![Foo(40), Foo(30)]);
    /// ```
    ///
    /// [`Index`]: core::ops::Index
    /// [`get`]: Slice::get
    pub fn idx<I>(&self, index: I) -> I::Output<'_>
    where
        I: SoaIndex<T>,
    {
        self.get(index).expect("index out of bounds")
    }

    /// Returns a mutable reference to the element at the given index.
    ///
    /// This is similar to [`IndexMut`], which is not implementable for this
    /// type. See [`get_mut`] for a non-panicking version.
    ///
    /// # Panics
    ///
    /// Panics if the index is out-of-bounds, which is whenever
    /// [`SoaIndex::get_mut`] returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use core::fmt;
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let mut soa = soa![Foo(10), Foo(20), Foo(30)];
    /// *soa.idx_mut(1).0 = 42;
    /// assert_eq!(soa, soa![Foo(10), Foo(42), Foo(30)]);
    /// ```
    ///
    /// [`IndexMut`]: core::ops::Index
    /// [`get_mut`]: Slice::get_mut
    pub fn idx_mut<I>(&mut self, index: I) -> I::OutputMut<'_>
    where
        I: SoaIndex<T>,
    {
        self.get_mut(index).expect("index out of bounds")
    }

    /// Divides one slice into two at an index.
    ///
    /// The first will contain all indices from `[0, mid)` (excluding
    /// the index `mid` itself) and the second will contain all
    /// indices from `[mid, len)` (excluding the index `len` itself).
    ///
    /// # Panics
    ///
    /// Panics if `mid > len`.  For a non-panicking alternative see
    /// [`split_at_checked`](Slice::split_at_checked).
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let soa = soa![Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)];
    /// let (l, r) = soa.split_at(3);
    /// assert_eq!(l, soa![Foo(1), Foo(2), Foo(3)]);
    /// assert_eq!(r, soa![Foo(4), Foo(5)]);
    /// ```
    #[must_use]
    pub fn split_at(&self, mid: usize) -> (SliceRef<'_, T>, SliceRef<'_, T>) {
        match self.split_at_checked(mid) {
            Some(pair) => pair,
            None => panic!("mid > len"),
        }
    }

    /// Divides one mutable slice into two at an index.
    ///
    /// The first will contain all indices from `[0, mid)` (excluding
    /// the index `mid` itself) and the second will contain all
    /// indices from `[mid, len)` (excluding the index `len` itself).
    ///
    /// # Panics
    ///
    /// Panics if `mid > len`.  For a non-panicking alternative see
    /// [`split_at_mut_checked`](Slice::split_at_mut_checked).
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let mut soa = soa![Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)];
    /// let (l, r) = soa.split_at_mut(3);
    /// assert_eq!(l, soa![Foo(1), Foo(2), Foo(3)]);
    /// assert_eq!(r, soa![Foo(4), Foo(5)]);
    /// ```
    #[must_use]
    pub fn split_at_mut(&mut self, mid: usize) -> (SliceMut<'_, T>, SliceMut<'_, T>) {
        match self.split_at_mut_checked(mid) {
            Some(pair) => pair,
            None => panic!("mid > len"),
        }
    }

    /// Divides one slice into two at an index,
    /// returning `None` if the slice is too short.
    ///
    /// If `mid ≤ len` returns a pair of slices where the first will contain all
    /// indices from `[0, mid)` (excluding the index `mid` itself) and the
    /// second will contain all indices from `[mid, len)` (excluding the index
    /// `len` itself).
    ///
    /// Otherwise, if `mid > len`, returns `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let soa = soa![Foo(1), Foo(2), Foo(3), Foo(4)];
    ///
    /// {
    ///     let (l, r) = soa.split_at_checked(0).unwrap();
    ///     assert_eq!(l, soa![]);
    ///     assert_eq!(r, soa);
    /// }
    ///
    /// {
    ///     let (l, r) = soa.split_at_checked(2).unwrap();
    ///     assert_eq!(l, soa![Foo(1), Foo(2)]);
    ///     assert_eq!(r, soa![Foo(3), Foo(4)]);
    /// }
    ///
    /// {
    ///     let (l, r) = soa.split_at_checked(4).unwrap();
    ///     assert_eq!(l, soa);
    ///     assert_eq!(r, soa![]);
    /// }
    ///
    /// assert_eq!(None, soa.split_at_checked(5));
    #[must_use]
    pub fn split_at_checked(&self, mid: usize) -> Option<(SliceRef<'_, T>, SliceRef<'_, T>)> {
        // SAFETY:
        // Don't use `bool::then_some` here because constructing an invalid reference is unsound,
        // even if it is not accessed
        (mid <= self.len()).then(|| unsafe { self.split_at_unchecked(mid) })
    }

    /// Divides one mutable slice into two at an index,
    /// returning `None` if the slice is too short.
    ///
    /// If `mid ≤ len` returns a pair of slices where the first will contain all
    /// indices from `[0, mid)` (excluding the index `mid` itself) and the
    /// second will contain all indices from `[mid, len)` (excluding the index
    /// `len` itself).
    ///
    /// Otherwise, if `mid > len`, returns `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let mut soa = soa![Foo(1), Foo(2), Foo(3), Foo(4)];
    ///
    /// {
    ///     let (l, r) = soa.split_at_mut_checked(0).unwrap();
    ///     assert_eq!(l, soa![]);
    ///     assert_eq!(r, soa![Foo(1), Foo(2), Foo(3), Foo(4)]);
    /// }
    ///
    /// {
    ///     let (l, r) = soa.split_at_mut_checked(2).unwrap();
    ///     assert_eq!(l, soa![Foo(1), Foo(2)]);
    ///     assert_eq!(r, soa![Foo(3), Foo(4)]);
    /// }
    ///
    /// {
    ///     let (l, r) = soa.split_at_mut_checked(4).unwrap();
    ///     assert_eq!(l, soa![Foo(1), Foo(2), Foo(3), Foo(4)]);
    ///     assert_eq!(r, soa![]);
    /// }
    ///
    /// assert_eq!(None, soa.split_at_mut_checked(5));
    #[must_use]
    pub fn split_at_mut_checked(
        &mut self,
        mid: usize,
    ) -> Option<(SliceMut<'_, T>, SliceMut<'_, T>)> {
        // SAFETY:
        // Don't use `bool::then_some` here because constructing an invalid reference is unsound,
        // even if it is not accessed
        (mid <= self.len()).then(|| unsafe { self.split_at_mut_unchecked(mid) })
    }

    /// Divides one slice into two at an index without doing bounds checking.
    ///
    /// The first will contain all indices from `[0, mid)` (excluding
    /// the index `mid` itself) and the second will contain all
    /// indices from `[mid, len)` (excluding the index `len` itself).
    ///
    /// For a safe alternative, see [`split_at`].
    ///
    /// # Safety
    ///
    /// Calling this method with an out-of-bounds index is undefined behavior,
    /// even if the resulting reference is not used.
    ///
    /// [`split_at`]: Slice::split_at
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let soa = soa![Foo(1), Foo(2), Foo(3)];
    /// let (l, r) = unsafe { soa.split_at_unchecked(2) };
    /// assert_eq!(l, soa![Foo(1), Foo(2)]);
    /// assert_eq!(r, soa![Foo(3)]);
    /// ```
    #[must_use]
    pub unsafe fn split_at_unchecked(&self, mid: usize) -> (SliceRef<'_, T>, SliceRef<'_, T>) {
        let (l, r, r_len) = self.split_at_parts(mid);
        // SAFETY: Lifetime matches that of self
        let l = unsafe { SliceRef::from_slice(l, mid) };
        let r = unsafe { SliceRef::from_slice(r, r_len) };
        (l, r)
    }

    /// Divides one mutable slice into two at an index without doing bounds checking.
    ///
    /// The first will contain all indices from `[0, mid)` (excluding
    /// the index `mid` itself) and the second will contain all
    /// indices from `[mid, len)` (excluding the index `len` itself).
    ///
    /// For a safe alternative, see [`split_at_mut`].
    ///
    /// # Safety
    ///
    /// Calling this method with an out-of-bounds index is undefined behavior,
    /// even if the resulting reference is not used.
    ///
    /// [`split_at_mut`]: Slice::split_at_mut
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let mut soa = soa![Foo(1), Foo(2), Foo(3)];
    /// let (l, r) = unsafe { soa.split_at_mut_unchecked(1) };
    /// assert_eq!(l, soa![Foo(1)]);
    /// assert_eq!(r, soa![Foo(2), Foo(3)]);
    /// ```
    #[must_use]
    pub unsafe fn split_at_mut_unchecked(
        &mut self,
        mid: usize,
    ) -> (SliceMut<'_, T>, SliceMut<'_, T>) {
        let (l, r, r_len) = self.split_at_parts(mid);
        // SAFETY: Lifetime matches that of self
        let l = unsafe { SliceMut::from_slice(l, mid) };
        let r = unsafe { SliceMut::from_slice(r, r_len) };
        (l, r)
    }

    fn split_at_parts(&self, mid: usize) -> (Slice<T, ()>, Slice<T, ()>, usize) {
        (
            unsafe { self.as_sized() },
            Slice::with_raw(unsafe { self.raw.offset(mid) }),
            self.len() - mid,
        )
    }

    /// Swaps the position of two elements.
    ///
    /// # Arguments
    ///
    /// - `a`: The index of the first element
    /// - `b`: The index of the second element
    ///
    /// # Panics
    ///
    /// Panics if `a` or `b` is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let mut soa = soa![Foo(0), Foo(1), Foo(2), Foo(3), Foo(4)];
    /// soa.swap(2, 4);
    /// assert_eq!(soa, soa![Foo(0), Foo(1), Foo(4), Foo(3), Foo(2)]);
    /// ```
    pub fn swap(&mut self, a: usize, b: usize) {
        if a >= self.len() || b >= self.len() {
            panic!("index out of bounds");
        }

        // SAFETY: We bounds checked a and b
        unsafe {
            let a = self.raw().offset(a);
            let b = self.raw().offset(b);
            let tmp = a.get();
            b.copy_to(a, 1);
            b.set(tmp);
        }
    }

    /// Returns the first element of the slice, or None if empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let soa = soa![Foo(10), Foo(40), Foo(30)];
    /// assert_eq!(soa.first(), Some(FooRef(&10)));
    ///
    /// let soa = Soa::<Foo>::new();
    /// assert_eq!(soa.first(), None);
    /// ```
    pub fn first(&self) -> Option<T::Ref<'_>> {
        self.get(0)
    }

    /// Returns a mutable reference to the first element of the slice, or None if empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let mut soa = soa![Foo(0), Foo(1), Foo(2)];
    /// if let Some(mut first) = soa.first_mut() {
    ///     *first.0 = 5;
    /// }
    /// assert_eq!(soa, soa![Foo(5), Foo(1), Foo(2)]);
    /// ```
    pub fn first_mut(&mut self) -> Option<T::RefMut<'_>> {
        self.get_mut(0)
    }

    /// Returns the last element of the slice, or None if empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let soa = soa![Foo(10), Foo(40), Foo(30)];
    /// assert_eq!(soa.last(), Some(FooRef(&30)));
    ///
    /// let soa = Soa::<Foo>::new();
    /// assert_eq!(soa.last(), None);
    /// ```
    pub fn last(&self) -> Option<T::Ref<'_>> {
        self.get(self.len().saturating_sub(1))
    }

    /// Returns a mutable reference to the last element of the slice, or None if empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(usize);
    /// let mut soa = soa![Foo(0), Foo(1), Foo(2)];
    /// if let Some(mut last) = soa.last_mut() {
    ///     *last.0 = 5;
    /// }
    /// assert_eq!(soa, soa![Foo(0), Foo(1), Foo(5)]);
    /// ```
    pub fn last_mut(&mut self) -> Option<T::RefMut<'_>> {
        self.get_mut(self.len().saturating_sub(1))
    }

    /// Returns an iterator over `chunk_size` elements of the slice at a time,
    /// starting at the beginning of the slice.
    ///
    /// The chunks are slices and do not overlap. If `chunk_size` does not divide
    /// the length of the slice, then the last up to `chunk_size-1` elements will
    /// be omitted and can be retrieved from the [`remainder`] function of the
    /// iterator.
    ///
    /// Due to each chunk having exactly `chunk_size` elements, the compiler can
    /// often optimize the resulting code better than in the case of chunks.
    ///
    /// [`remainder`]: ChunksExact::remainder
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa, AsSlice};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo(char);
    /// let soa = soa![Foo('l'), Foo('o'), Foo('r'), Foo('e'), Foo('m')];
    /// let mut iter = soa.chunks_exact(2);
    /// assert_eq!(iter.next(), Some(soa![Foo('l'), Foo('o')].as_slice()));
    /// assert_eq!(iter.next(), Some(soa![Foo('r'), Foo('e')].as_slice()));
    /// assert!(iter.next().is_none());
    /// assert_eq!(iter.remainder(), &soa![Foo('m')]);
    /// ```
    pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
        if chunk_size == 0 {
            panic!("chunk size must be nonzero")
        }

        ChunksExact::new(self, chunk_size)
    }

    /// Returns a collection of slices for each field of the slice.
    ///
    /// For convenience, slices can also be aquired using the getter methods for
    /// individual fields.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo {
    /// #     foo: u8,
    /// #     bar: u8,
    /// # }
    /// let soa = soa![Foo { foo: 1, bar: 2 }, Foo { foo: 3, bar: 4 }];
    /// let slices = soa.slices();
    /// assert_eq!(slices.foo, soa.foo());
    /// assert_eq!(slices.bar, soa.bar());
    /// ```
    pub fn slices(&self) -> T::Slices<'_> {
        // SAFETY:
        // - The returned lifetime is bound to self
        // - len elements are allocated and initialized
        unsafe { self.raw.slices(self.len()) }
    }

    /// Returns a collection of mutable slices for each field of the slice.
    ///
    /// For convenience, individual mutable slices can also be aquired using the
    /// getter methods for individual fields. This method is necessary to be
    /// able to mutably borrow multiple SoA fields simultaneously.
    ///
    /// # Examples
    ///
    /// ```
    /// # use soa_rs::{Soa, Soars, soa};
    /// # #[derive(Soars, Debug, PartialEq)]
    /// # #[soa_derive(Debug, PartialEq)]
    /// # struct Foo {
    /// #     foo: u8,
    /// #     bar: u8,
    /// # }
    /// let mut soa = soa![Foo { foo: 1, bar: 0 }, Foo { foo: 2, bar: 0 }];
    /// let slices = soa.slices_mut();
    /// for (foo, bar) in slices.foo.iter().zip(slices.bar) {
    ///     *bar = foo * 2;
    /// }
    /// assert_eq!(soa.bar(), [2, 4]);
    /// ```
    pub fn slices_mut(&mut self) -> T::SlicesMut<'_> {
        // SAFETY:
        // - The returned lifetime is bound to self
        // - len elements are allocated and initialized
        unsafe { self.raw.slices_mut(self.len()) }
    }

    /// Converts from an unsized variant to sized variant
    ///
    /// # Safety
    ///
    /// Since this returns an owned value, it implicitly extends the lifetime &
    /// in an unbounded way. The caller must ensure proper lifetimes with, for
    /// example, [`PhantomData`].
    ///
    /// [`PhantomData`]: core::marker::PhantomData
    pub(crate) const unsafe fn as_sized(&self) -> Slice<T, ()> {
        let ptr = core::ptr::from_ref(self).cast();
        unsafe { *ptr }
    }
}

impl<T> Clone for Slice<T, ()>
where
    T: Soars,
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for Slice<T, ()> where T: Soars {}

impl<'a, T> IntoIterator for &'a Slice<T>
where
    T: Soars,
{
    type Item = T::Ref<'a>;
    type IntoIter = Iter<'a, T>;

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

impl<'a, T> IntoIterator for &'a mut Slice<T>
where
    T: Soars,
{
    type Item = T::RefMut<'a>;
    type IntoIter = IterMut<'a, T>;

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

impl<T, R> PartialEq<R> for Slice<T>
where
    T: Soars,
    R: AsSlice<Item = T> + ?Sized,
    for<'a> T::Ref<'a>: PartialEq,
{
    fn eq(&self, other: &R) -> bool {
        let other = other.as_slice();
        self.len() == other.len() && self.iter().zip(other.iter()).all(|(me, them)| me == them)
    }
}

impl<T> Eq for Slice<T>
where
    T: Soars,
    for<'a> T::Ref<'a>: Eq,
{
}

impl<T> Debug for Slice<T>
where
    T: Soars,
    for<'a> T::Ref<'a>: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let mut list = f.debug_list();
        self.iter().for_each(|item| {
            list.entry(&item);
        });
        list.finish()
    }
}

impl<T> PartialOrd for Slice<T>
where
    T: Soars,
    for<'a> T::Ref<'a>: PartialOrd,
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match self
            .iter()
            .zip(other.iter())
            .try_fold(Ordering::Equal, |_, (a, b)| match a.partial_cmp(&b) {
                ord @ (None | Some(Ordering::Less | Ordering::Greater)) => ControlFlow::Break(ord),
                Some(Ordering::Equal) => ControlFlow::Continue(self.len().cmp(&other.len())),
            }) {
            ControlFlow::Continue(ord) => Some(ord),
            ControlFlow::Break(ord) => ord,
        }
    }
}

impl<T> Ord for Slice<T>
where
    T: Soars,
    for<'a> T::Ref<'a>: Ord,
{
    fn cmp(&self, other: &Self) -> Ordering {
        match self
            .iter()
            .zip(other.iter())
            .try_fold(Ordering::Equal, |_, (a, b)| match a.cmp(&b) {
                ord @ (Ordering::Greater | Ordering::Less) => ControlFlow::Break(ord),
                Ordering::Equal => ControlFlow::Continue(self.len().cmp(&other.len())),
            }) {
            ControlFlow::Continue(ord) | ControlFlow::Break(ord) => ord,
        }
    }
}

impl<T> Hash for Slice<T>
where
    T: Soars,
    for<'a> T::Ref<'a>: Hash,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.len().hash(state);
        for item in self {
            item.hash(state);
        }
    }
}

impl<T> Deref for Slice<T>
where
    T: Soars,
{
    type Target = T::Deref;

    fn deref(&self) -> &Self::Target {
        <T::Deref as SoaDeref>::from_slice(self)
    }
}

impl<T> DerefMut for Slice<T>
where
    T: Soars,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        <T::Deref as SoaDeref>::from_slice_mut(self)
    }
}

impl<T> AsRef<Slice<T>> for Slice<T>
where
    T: Soars,
{
    fn as_ref(&self) -> &Self {
        self
    }
}

impl<T> AsMut<Slice<T>> for Slice<T>
where
    T: Soars,
{
    fn as_mut(&mut self) -> &mut Self {
        self
    }
}

impl<T> From<&Slice<T>> for Vec<T>
where
    T: SoaClone,
{
    /// Allocate a `Vec<T>` and fill it by cloning `value`'s items.
    fn from(value: &Slice<T>) -> Self {
        value.iter().map(SoaClone::soa_clone).collect()
    }
}

impl<T> From<&mut Slice<T>> for Vec<T>
where
    T: SoaClone,
{
    /// Allocate a `Vec<T>` and fill it by cloning `value`'s items.
    fn from(value: &mut Slice<T>) -> Self {
        value.as_ref().into()
    }
}

impl<T> AsSlice for Slice<T>
where
    T: Soars,
{
    type Item = T;

    fn as_slice(&self) -> SliceRef<'_, Self::Item> {
        // SAFETY: The returned lifetime is bound to self
        unsafe { SliceRef::from_slice(self.as_sized(), self.len()) }
    }
}

impl<T> AsMutSlice for Slice<T>
where
    T: Soars,
{
    fn as_mut_slice(&mut self) -> SliceMut<'_, Self::Item> {
        // SAFETY: The returned lifetime is bound to self
        unsafe { SliceMut::from_slice(self.as_sized(), self.len()) }
    }
}