layout 0.0.1

Optimized memory layout using struct of array, Data-oriented design in Rust, DOD SOA
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
#![cfg_attr(not(feature = "std"), no_std)]
//! This crate provides a custom derive (`#[derive(SOA)]`) to
//! automatically generate code from a given struct `T` that allow to replace
//! `Vec<T>` with a struct of arrays. For example, the following code
//!
//! ```
//! # #[macro_use] extern crate layout;
//! # mod cheese {
//! #[derive(SOA)]
//! pub struct Cheese {
//!     pub smell: f64,
//!     pub color: (f64, f64, f64),
//!     pub with_mushrooms: bool,
//!     pub name: String,
//! }
//! # }
//! ```
//!
//! will generate a `CheeseVec` struct that looks like this:
//!
//! ```
//! pub struct CheeseVec {
//!     pub smell: Vec<f64>,
//!     pub color: Vec<(f64, f64, f64)>,
//!     pub with_mushrooms: Vec<bool>,
//!     pub name: Vec<String>,
//! }
//! ```
//!
//! It will also generate the same functions that a `Vec<Chees>` would have, and
//! a few helper structs: `CheeseSlice`, `CheeseSliceMut`, `CheeseRef` and
//! `CheeseRefMut` corresponding respectivly to `&[Cheese]`, `&mut [Cheese]`,
//! `&Cheese` and `&mut Cheese`.
//!
//! # How to use it
//!
//! Add `#[derive(SOA)]` to each struct you want to derive a struct of
//! array version. If you need the helper structs to derive additional traits
//! (such as `Debug` or `PartialEq`), you can add an attribute `#[layout =
//! "Debug, PartialEq"]` to the struct declaration.
//!
//! ```
//! # #[macro_use] extern crate layout;
//! # mod cheese {
//! #[derive(Debug, PartialEq, SOA)]
//! #[layout(Debug, PartialEq)]
//! pub struct Cheese {
//!     pub smell: f64,
//!     pub color: (f64, f64, f64),
//!     pub with_mushrooms: bool,
//!     pub name: String,
//! }
//! # }
//! ```
//!
//! If you want to add attribute to a specific generated struct(such as
//! `#[cfg_attr(test, derive(PartialEq))]` on `CheeseVec`), you can add an
//! attribute `#[soa_attr(Vec, cfg_attr(test, derive(PartialEq)))]` to the
//! struct declaration.
//!
//! ```
//! # #[macro_use] extern crate layout;
//! # mod cheese {
//! #[derive(Debug, PartialEq, SOA)]
//! #[soa_attr(Vec, cfg_attr(test, derive(PartialEq)))]
//! pub struct Cheese {
//!     pub smell: f64,
//!     pub color: (f64, f64, f64),
//!     pub with_mushrooms: bool,
//!     pub name: String,
//! }
//! # }
//! ```
//!
//! Mappings for first argument of ``soa_attr`` to the generated struct for ``Cheese``:
//! * `Vec` => `CheeseVec`
//! * `Slice` => `CheeseSlice`
//! * `SliceMut` => `CheeseSliceMut`
//! * `Ref` => `CheeseRef`
//! * `RefMut` => `CheeseRefMut`
//! * `Ptr` => `CheesePtr`
//! * `PtrMut` => `CheesePtrMut`
//!
//! # Usage and API
//!
//! All the generated code have some generated documentation with it, so you
//! should be able to use `cargo doc` on your crate and see the documentation
//! for all the generated structs and functions.
//!
//! Most of the time, you should be able to replace `Vec<Cheese>` by
//! `CheeseVec`, with exception of code using direct indexing in the vector and
//! a few other caveats listed below.
//!
//! ## Caveats and limitations
//!
//! `Vec<T>` functionalities rely a lot on references and automatic *deref*
//! feature, for getting function from `[T]` and indexing. But the SoA vector
//! (let's call it `CheeseVec`, generated from the `Cheese` struct) generated by
//! this crate can not implement `Deref<Target=CheeseSlice>`, because `Deref` is
//! required to return a reference, and `CheeseSlice` is not a reference. The
//! same applies to `Index` and `IndexMut` trait, that can not return
//! `CheeseRef/CheeseRefMut`.
//!
//! This means that the we can not index into a `CheeseVec`, and that a few
//! functions are duplicated, or require a call to `as_ref()/as_mut()` to change
//! the type used.
//!
//! # Iteration
//!
//! It is possible to iterate over the values in a `CheeseVec`
//!
//! ```no_run
//! # #[macro_use] extern crate layout;
//! # mod cheese {
//! # #[derive(Debug, PartialEq, SOA)]
//! # pub struct Cheese {
//! #     pub smell: f64,
//! #     pub color: (f64, f64, f64),
//! #     pub with_mushrooms: bool,
//! #     pub name: String,
//! # }
//! # impl Cheese { fn new(name: &str) -> Cheese { unimplemented!() } }
//! # fn main() {
//! let mut vec = CheeseVec::new();
//! vec.push(Cheese::new("stilton"));
//! vec.push(Cheese::new("brie"));
//!
//! for cheese in vec.iter() {
//!     // when iterating over a CheeseVec, we load all members from memory
//!     // in a CheeseRef
//!     let typeof_cheese: CheeseRef = cheese;
//!     println!("this is {}, with a smell power of {}", cheese.name, cheese.smell);
//! }
//! # }
//! # }
//! ```
//!
//! One of the main advantage of the SoA layout is to be able to only load some
//! fields from memory when iterating over the vector. In order to do so, one
//! can manually pick the needed fields:
//!
//! ```no_run
//! # #[macro_use] extern crate layout;
//! # mod cheese {
//! # #[derive(Debug, PartialEq, SOA)]
//! # pub struct Cheese {
//! #     pub smell: f64,
//! #     pub color: (f64, f64, f64),
//! #     pub with_mushrooms: bool,
//! #     pub name: String,
//! # }
//! # impl Cheese { fn new(name: &str) -> Cheese { unimplemented!() } }
//! # fn main() {
//! # let mut vec = CheeseVec::new();
//! # vec.push(Cheese::new("stilton"));
//! # vec.push(Cheese::new("brie"));
//! for name in &vec.name {
//!     // We get referenes to the names
//!     let typeof_name: &String = name;
//!     println!("got cheese {}", name);
//! }
//! # }
//! # }
//! ```
//!
//! In order to iterate over multiple fields at the same time, one can use the
//! [soa_zip!](macro.soa_zip.html) macro.
//!
//! ```no_run
//! # #[macro_use] extern crate layout;
//! # mod cheese {
//! # #[derive(Debug, PartialEq, SOA)]
//! # pub struct Cheese {
//! #     pub smell: f64,
//! #     pub color: (f64, f64, f64),
//! #     pub with_mushrooms: bool,
//! #     pub name: String,
//! # }
//! # impl Cheese { fn new(name: &str) -> Cheese { unimplemented!() } }
//! # fn main() {
//! # let mut vec = CheeseVec::new();
//! # vec.push(Cheese::new("stilton"));
//! # vec.push(Cheese::new("brie"));
//! for (name, smell, color) in soa_zip!(&mut vec, [name, mut smell, color]) {
//!     println!("this is {}, with color {:#?}", name, color);
//!     // smell is a mutable reference
//!     *smell += 1.0;
//! }
//! # }
//! # }
//! ```
//!
//! ## Nested Struct of Arrays
//!
//! In order to nest a struct of arrays inside another struct of arrays, one can use the `#[nested_soa]` attribute.
//!
//! For example, the following code
//!
//! ```
//! # mod cheese {
//! # use layout::SOA;
//! #[derive(SOA)]
//! pub struct Point {
//!     x: f32,
//!     y: f32,
//! }
//! #[derive(SOA)]
//! pub struct Particle {
//!     #[nested_soa]
//!     point: Point,
//!     mass: f32,
//! }
//! # }
//! ```
//!
//! will generate structs that looks like this:
//!
//! ```
//! pub struct PointVec {
//!     x: Vec<f32>,
//!     y: Vec<f32>,
//! }
//! pub struct ParticleVec {
//!     point: PointVec, // rather than Vec<Point>
//!     mass: Vec<f32>
//! }
//! ```
//!
//! All helper structs will be also nested, for example `PointSlice` will be nested in `ParticleSlice`.
//!
//! # Use in a generic context
//!
//! `SOA` does not provide a set of common operations by default. Thus if you wanted to use a `SOA`
//! type in a generic context, there is no way to guarantee to the type system that any methods are available.
//!
//! This will also generate implementations of [`SoAVec`], [`SoASlice`], and [`SoASliceMut`] for the respective
//! `Vec`, `Slice` and `SliceMut` types. These rely on GATs, and so require Rust 1.65 or newer.
//!
//! ```ignore
//! # mod cheese {
//! # use layout::{SOA, prelude::*};
//! #[derive(SOA)]
//! pub struct Point {
//!     x: f32,
//!     y: f32,
//! }
//!
//! fn get_num_items<T: SOA, V: SoAVec<T>>(values: &V) -> usize {
//!     values.len()
//! }
//! # }
//! ```

extern crate alloc;
#[allow(unused_imports)]
use alloc::{vec::Vec,string::String};


// The proc macro is implemented in layout_internal, and re-exported by this
// crate. This is because a single crate can not define both a proc macro and a
// macro_rules macro.
pub use layout_internal::SOA;

// External dependency necessary for implementing the sorting methods.
// It is basically used by the macro-generated code.
#[doc(hidden)]
pub use permutation::permutation::*;

/// Any struct derived by SOA will auto impl this trait You can use
/// `<Cheese as SOA>::Type` instead of explicit named type
/// `CheeseVec`; This will helpful in generics programing that generate struct
/// can be expressed as `<T as SOA>::Type`
pub trait SOA {
    type Type;
}

/// Any struct derived by SOA will auto impl this trait.
///
/// Useful for generic programming and implementation of attribute `nested_soa`.
///
/// `CheeseVec::iter(&'a self)` returns an iterator which has a type `<Cheese as SoAIter<'a>>::Iter`
///
/// `CheeseVec::iter_mut(&mut 'a self)` returns an iterator which has a type `<Cheese as SoAIter<'a>>::IterMut`
pub trait SoAIter<'a> {
    type Ref;
    type RefMut;
    type Iter: 'a + Iterator<Item=Self::Ref>;
    type IterMut: 'a + Iterator<Item=Self::RefMut>;
}

mod private_soa_indexes {
    // From [`core::slice::SliceIndex`](https://doc.rust-lang.org/std/slice/trait.SliceIndex.html) code.
    // Limits the types that may implement the SoA index traits.
    // It's also helpful to have the exaustive list of all accepted types.

    use ::core::ops;

    pub trait Sealed {}

    impl Sealed for usize {}                        // [a]
    impl Sealed for ops::Range<usize> {}            // [a..b]
    impl Sealed for ops::RangeTo<usize> {}          // [..b]
    impl Sealed for ops::RangeFrom<usize> {}        // [a..]
    impl Sealed for ops::RangeFull {}               // [..]
    impl Sealed for ops::RangeInclusive<usize> {}   // [a..=b]
    impl Sealed for ops::RangeToInclusive<usize> {} // [..=b]
}

/// Helper trait used for indexing operations.
/// Inspired by [`core::slice::SliceIndex`](https://doc.rust-lang.org/std/slice/trait.SliceIndex.html).
pub trait SoAIndex<T>: private_soa_indexes::Sealed {
    /// The output for the non-mutable functions
    type RefOutput;

    /// Returns the reference output in this location if in bounds, `None`
    /// otherwise.
    fn get(self, soa: T) -> Option<Self::RefOutput>;
    /// Returns the reference output in this location without performing any
    /// bounds check.
    ///
    /// # Safety
    /// The index must be in bounds.
    unsafe fn get_unchecked(self, soa: T) -> Self::RefOutput;
    /// Returns the reference output in this location. Panics if it is not in
    /// bounds.
    fn index(self, soa: T) -> Self::RefOutput;
}

/// Helper trait used for indexing operations returning mutable references.
/// Inspired by [`core::slice::SliceIndex`](https://doc.rust-lang.org/std/slice/trait.SliceIndex.html).
pub trait SoAIndexMut<T>: private_soa_indexes::Sealed {
    /// The output for the mutable functions
    type MutOutput;

    /// Returns the mutable reference output in this location if in bounds,
    /// `None` otherwise.
    fn get_mut(self, soa: T) -> Option<Self::MutOutput>;
    /// Returns the mutable reference output in this location without performing
    /// any bounds check.
    ///
    /// # Safety
    /// The index must be in bounds.
    unsafe fn get_unchecked_mut(self, soa: T) -> Self::MutOutput;
    /// Returns the mutable reference output in this location. Panics if it is
    /// not in bounds.
    fn index_mut(self, soa: T) -> Self::MutOutput;
}

/// Create an iterator over multiple fields in a Struct of array style vector.
///
/// This macro takes two main arguments: the array/slice container, and a list
/// of fields to use, inside square brackets. The iterator will give references
/// to the fields, which can be mutable references if the field name is prefixed
/// with `mut`.
///
/// ```
/// # #[macro_use] extern crate layout;
/// # mod cheese {
/// #[derive(SOA)]
/// struct Cheese {
///     size: f64,
///     mass: f64,
///     smell: f64,
///     name: String,
/// }
///
/// # fn main() {
/// let mut vec = CheeseVec::new();
/// // fill the vector
///
/// // Iterate over immutable references
/// for (mass, size, name) in soa_zip!(&vec, [mass, size, name]) {
///     println!("got {} kg and {} cm of {}", mass, size, name);
/// }
///
/// // Iterate over mutable references
/// for (mass, name) in soa_zip!(&mut vec, [mut mass, name]) {
///     println!("got {} kg of {}, eating 1 kg", mass, name);
///     *mass -= 1.0;
/// }
/// # }
/// # }
/// ```
///
/// The iterator can also work with external iterators. In this case, the
/// iterator will yields elements until any of the fields or one external
/// iterator returns None.
///
/// ```
/// # #[macro_use] extern crate layout;
/// # mod cheese {
/// # #[derive(SOA)]
/// # struct Cheese {
/// #     size: f64,
/// #     mass: f64,
/// #     smell: f64,
/// #     name: String,
/// # }
/// # #[derive(Debug)] struct Cellar;
/// # fn main() {
/// let mut vec = CheeseVec::new();
/// let mut cellars = Vec::<Cellar>::new();
///
/// for (name, mass, cellar) in soa_zip!(&vec, [name, mass], &cellars) {
///     println!("we have {} kg of {} in {:#?}", mass, name, cellar);
/// }
/// # }
/// # }
/// ```
#[macro_export]
macro_rules! soa_zip {
    ($self: expr, [$($fields: tt)*] $(, $external: expr)* $(,)*) => {{
        let this = $self;
        $crate::soa_zip_impl!(@munch this, {$($fields)*} -> [] $($external ,)*)
    }};
}


/// This trait is automatically implemented by the relevant generated by [`SOA`].
///
/// Links a [`SOA`] type to its raw pointer types, which is useful for generic
/// programming.
pub trait SoAPointers {
    /// The immutable pointer type for an SoA type
    type Ptr;
    /// The mutable pointer type for an SoA type
    type MutPtr;
}


mod generics {
    use super::*;

    /**
    The interface for the `Slice` immutable slice struct-of-arrays type.
    */
    pub trait SoASlice<T: SOA> {
        /// The type that elements will be proxied with as
        type Ref<'t> where Self: 't;

        /// The type representing immutable slices of elements
        type Slice<'t>: SoASlice<T> + IntoSoAIter<'t, T, Ref<'t> = Self::Ref<'t>> where Self: 't;

        /// The type used for iteration over [`Self::Ref`]
        type Iter<'t>: Iterator<Item=Self::Ref<'t>> where Self: 't;

        /// The raw pointer type interface
        type Ptr;

        /// Returns the number of elements in the arrays
        fn len(&self) -> usize;

        /// Returns true if the arrays has a length of 0.
        fn is_empty(&self) -> bool;

        /// Create an immutable slice of the arrays
        fn as_slice(&self) -> Self::Slice<'_>;

        /// Create a slice of this vector matching the given `range`. This
        /// is analogous to `Index<Range<usize>>`.
        fn slice<'c, 'a: 'c>(&'c self, index: impl core::ops::RangeBounds<usize>) -> Self::Slice<'c> where Self: 'a;

        /// Analogous to [`slice::get()`](https://doc.rust-lang.org/std/primitive.slice.html#method.get)
        fn get(&self, index: usize) -> Option<Self::Ref<'_>>;

        /// Analogous to [`core::ops::Index::index()`] for `usize`
        fn index(&self, index: usize) -> Self::Ref<'_>;

        /// Create an immutable iterator
        fn iter(&self) -> Self::Iter<'_>;

        /// Analogous to [`slice::first()`](https://doc.rust-lang.org/std/primitive.slice.html#method.first)
        fn first(&self) -> Option<Self::Ref<'_>> {
            self.get(0)
        }

        /// Analogous to [`slice::last()`](https://doc.rust-lang.org/std/primitive.slice.html#method.last)
        fn last(&self) -> Option<Self::Ref<'_>> {
            self.get(self.len().saturating_sub(1))
        }

        /// Obtain a `const` pointer type for this data
        fn as_ptr(&self) -> Self::Ptr;
    }

    /**
    The interface for the `SliceMut` mutable slice struct-of-arrays type. A generalization of [`SoASlice`]
    whose methods can modify elements of the arrays
    */
    pub trait SoASliceMut<T: SOA> {
        /// The type that elements will be proxied with as
        type Ref<'t> where Self: 't;

        /// The type representing immutable slices of elements
        type Slice<'t>: SoASlice<T> + IntoSoAIter<'t, T, Ref<'t> = Self::Ref<'t>> where Self: 't;

        /// The type used for iteration over [`Self::Ref`]
        type Iter<'t>: Iterator<Item=Self::Ref<'t>> where Self: 't;

        /// The const pointer type interface
        type Ptr;

        /// The type that elements will be proxied with as when mutable
        type RefMut<'t> where Self: 't;

        /// The type representing mutable slices of elements
        type SliceMut<'t>: SoASliceMut<T> where Self: 't;

        /// The type used for iteration over [`Self::RefMut`]
        type IterMut<'t>: Iterator<Item=Self::RefMut<'t>> where Self: 't;

        /// The mut pointer type interface
        type PtrMut;

        /// Returns the number of elements in the arrays
        fn len(&self) -> usize;

        /// Returns true if the arrays has a length of 0.
        fn is_empty(&self) -> bool;

        /// Create an immutable slice of the arrays
        fn as_slice(&self) -> Self::Slice<'_>;

        /// Create a slice of this vector matching the given `range`. This
        /// is analogous to `Index<Range<usize>>`.
        fn slice<'c, 'a: 'c>(&'c self, index: impl core::ops::RangeBounds<usize>) -> Self::Slice<'c> where Self: 'a;

        /// Analogous to [`slice::get()`](https://doc.rust-lang.org/std/primitive.slice.html#method.get)
        fn get(&self, index: usize) -> Option<Self::Ref<'_>>;

        /// Analogous to [`core::ops::Index::index()`] for `usize`
        fn index(&self, index: usize) -> Self::Ref<'_>;

        /// Create an immutable iterator
        fn iter(&self) -> Self::Iter<'_>;

        /// Analogous to [`slice::first()`](https://doc.rust-lang.org/std/primitive.slice.html#method.first)
        fn first(&self) -> Option<Self::Ref<'_>> {
            self.get(0)
        }

        /// Analogous to [`slice::last()`](https://doc.rust-lang.org/std/primitive.slice.html#method.last)
        fn last(&self) -> Option<Self::Ref<'_>> {
            self.get(self.len().saturating_sub(1))
        }

        /// Obtain a `const` pointer type for this data
        fn as_ptr(&self) -> Self::Ptr;

        /// Analogous to [`Vec::as_mut_slice()`]
        fn as_mut_slice<'c: 'b, 'b>(&'c mut self) -> Self::SliceMut<'c> where Self: 'b;

        /// Create a mutable slice of this vector matching the given
        /// `range`. This is analogous to `IndexMut<Range<usize>>`.
        fn slice_mut(&mut self, index: impl core::ops::RangeBounds<usize>) -> Self::SliceMut<'_>;

        /// Analogous to [`slice::get_mut()`](https://doc.rust-lang.org/std/primitive.slice.html#method.get_mut)
        fn get_mut(&mut self, index: usize) -> Option<Self::RefMut<'_>>;

        /// Analogous to [`core::ops::IndexMut::index_mut()`] for `usize`
        fn index_mut(&mut self, index: usize) -> Self::RefMut<'_>;

        /// Creates a mutable iterator
        fn iter_mut(&mut self) -> Self::IterMut<'_>;

        /** Re-order the arrays using the provided indices. This is provided so that generic sorting methods
         can be implemented because closure-passing trait methods encounter difficulties with lifetimes.
        */
        fn apply_index(&mut self, indices: &[usize]);

        /// `[slice::sort_by()`](<https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by>).
        fn sort_by<F>(&mut self, mut f: F) where F: FnMut(Self::Ref<'_>, Self::Ref<'_>) -> core::cmp::Ordering {
            let mut permutation: Vec<usize> = (0..self.len()).collect();
            permutation.sort_by(|j, k| f(self.index(*j), self.index(*k)));

            self.apply_index(&permutation);
        }

        /// `[slice::sort_by()`](<https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by_key>).
        fn sort_by_key<F, K>(&mut self, mut f: F) where
            F: FnMut(Self::Ref<'_>) -> K,
            K: Ord,
        {
            let mut permutation: Vec<usize> = (0..self.len()).collect();
            permutation.sort_by_key(|j| f(self.index(*j)));

            self.apply_index(&permutation);
        }

        /// Analogous to [`slice::first_mut()`](<https://doc.rust-lang.org/std/primitive.slice.html#method.first_mut>).
        fn first_mut(&mut self) -> Option<Self::RefMut<'_>> {
            self.get_mut(0)
        }

        /// Analogous to [`slice::last_mut()`](<https://doc.rust-lang.org/std/primitive.slice.html#method.last_mut>).
        fn last_mut(&mut self) -> Option<Self::RefMut<'_>> {
            self.get_mut(self.len().saturating_sub(1))
        }

        /// Obtain a `mut` pointer type for this data
        fn as_mut_ptr(&mut self) -> Self::PtrMut;
    }

    /**
    The interface for the `Vec`-like struct-of-arrays type. A generalization of [`SoASliceMut`] whose methods can
    also re-size the underlying arrays.

    **NOTE**: This interface is incomplete and additional methods may be added as needed.
    */
    pub trait SoAVec<T: SOA> {
        /// The type that elements will be proxied with as
        type Ref<'t> where Self: 't;

        /// The type representing immutable slices of elements
        type Slice<'t>: SoASlice<T> + IntoSoAIter<'t, T> where Self: 't;

        /// The type used for iteration over [`Self::Ref`]
        type Iter<'t>: Iterator<Item=Self::Ref<'t>> where Self: 't;

        /// The const pointer type interface
        type Ptr;

        /// The type that elements will be proxied with as when mutable
        type RefMut<'t> where Self: 't;

        /// The type representing mutable slices of elements
        type SliceMut<'t>: SoASliceMut<T> where Self: 't;

        /// The type used for iteration over [`Self::RefMut`]
        type IterMut<'t>: Iterator<Item=Self::RefMut<'t>> where Self: 't;

        /// The mut pointer type interface
        type PtrMut;

        /// Returns the number of elements in the arrays
        fn len(&self) -> usize;

        /// Returns true if the arrays has a length of 0.
        fn is_empty(&self) -> bool;

        /// Create an immutable slice of the arrays
        fn as_slice<'c, 'a: 'c>(&'c self) -> Self::Slice<'c> where Self: 'a;

        /// Create a slice of this vector matching the given `range`. This
        /// is analogous to `Index<Range<usize>>`.
        fn slice<'c, 'a: 'c>(&'c self, index: impl core::ops::RangeBounds<usize>) -> Self::Slice<'c> where Self: 'a;

        /// Analogous to [`slice::get()`](https://doc.rust-lang.org/std/primitive.slice.html#method.get)
        fn get(&self, index: usize) -> Option<Self::Ref<'_>>;

        /// Analogous to [`core::ops::Index::index()`] for `usize`
        fn index(&self, index: usize) -> Self::Ref<'_>;

        /// Create an immutable iterator
        fn iter(&self) -> Self::Iter<'_>;

        /// Analogous to [`slice::first()`](https://doc.rust-lang.org/std/primitive.slice.html#method.first)
        fn first(&self) -> Option<Self::Ref<'_>> {
            self.get(0)
        }

        /// Analogous to [`slice::last()`](https://doc.rust-lang.org/std/primitive.slice.html#method.last)
        fn last(&self) -> Option<Self::Ref<'_>> {
            self.get(self.len().saturating_sub(1))
        }

        /// Obtain a `const` pointer type for this data
        fn as_ptr(&self) -> Self::Ptr;

        /// Analogous to [`Vec::as_mut_slice()`]
        fn as_mut_slice<'c, 'a: 'c>(&'c mut self) -> Self::SliceMut<'c> where Self: 'a;

        /// Create a mutable slice of this vector matching the given
        /// `range`. This is analogous to `IndexMut<Range<usize>>`.
        fn slice_mut(&mut self, index: impl core::ops::RangeBounds<usize>) -> Self::SliceMut<'_>;

        /// Analogous to [`slice::get_mut()`](https://doc.rust-lang.org/std/primitive.slice.html#method.get_mut)
        fn get_mut(&mut self, index: usize) -> Option<Self::RefMut<'_>>;

        /// Analogous to [`core::ops::IndexMut::index_mut()`] for `usize`
        fn index_mut(&mut self, index: usize) -> Self::RefMut<'_>;

        /// Creates a mutable iterator
        fn iter_mut(&mut self) -> Self::IterMut<'_>;

        /** Re-order the arrays using the provided indices. This is provided so that generic sorting methods
         can be implemented because closure-passing trait methods encounter difficulties with lifetimes.
        */
        fn apply_index(&mut self, indices: &[usize]);

        /// `[slice::sort_by()`](<https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by>).
        fn sort_by<F>(&mut self, mut f: F) where F: FnMut(Self::Ref<'_>, Self::Ref<'_>) -> core::cmp::Ordering {
            let mut permutation: Vec<usize> = (0..self.len()).collect();
            permutation.sort_by(|j, k| f(self.index(*j), self.index(*k)));

            self.apply_index(&permutation);
        }

        /// `[slice::sort_by()`](<https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by_key>).
        fn sort_by_key<F, K>(&mut self, mut f: F) where
            F: FnMut(Self::Ref<'_>) -> K,
            K: Ord,
        {
            let mut permutation: Vec<usize> = (0..self.len()).collect();
            permutation.sort_by_key(|j| f(self.index(*j)));

            self.apply_index(&permutation);
        }

        /// Analogous to [`slice::first_mut()`](<https://doc.rust-lang.org/std/primitive.slice.html#method.first_mut>)
        fn first_mut(&mut self) -> Option<Self::RefMut<'_>> {
            self.get_mut(0)
        }

        /// Analogous to [`slice::last_mut()`](<https://doc.rust-lang.org/std/primitive.slice.html#method.last_mut>)
        fn last_mut(&mut self) -> Option<Self::RefMut<'_>> {
            self.get_mut(self.len().saturating_sub(1))
        }

        /// Obtain a `mut` pointer type for this data
        fn as_mut_ptr(&mut self) -> Self::PtrMut;

        /// Create a new, empty struct of arrays
        fn new() -> Self;

        /// Create a new, empty struct of arrays with the specified capacity
        fn with_capacity(capacity: usize) -> Self;

        /// Analogous to [`Vec::capacity`]
        fn capacity(&self) -> usize;

        /// Analogous to [`Vec::reserve`]
        fn reserve(&mut self, additional: usize);

        /// Analogous to [`Vec::reserve_exact`]
        fn reserve_exact(&mut self, additional: usize);

        /// Analogous to [`Vec::shrink_to_fit`]
        fn shrink_to_fit(&mut self);

        /// Analogous to [`Vec::truncate`]
        fn truncate(&mut self, len: usize);

        /// Add a singular value of `T` to the arrays. Analogous to [`Vec::push`]
        fn push(&mut self, value: T);

        /// Analogous to [`Vec::swap_remove`]
        fn swap_remove(&mut self, index: usize) -> T;

        /// Analogous to [`Vec::insert`]
        fn insert(&mut self, index: usize, element: T);

        /// Similar to [`core::mem::replace()`](https://doc.rust-lang.org/std/mem/fn.replace.html).
        fn replace(&mut self, index: usize, element: T) -> T;

        /// Analogous to [`Vec::remove`]
        fn remove(&mut self, index: usize) -> T;

        /// Analogous to [`Vec::pop`]
        fn pop(&mut self) -> Option<T>;

        /// Analogous to [`Vec::append`]
        fn append(&mut self, other: &mut Self);

        /// Analogous to [`Vec::clear`]
        fn clear(&mut self);

        /// Analogous to [`Vec::split_off`]
        fn split_off(&mut self, at: usize) -> Self;
    }

    /// A trait to implement `Clone`-dependent behavior to convert a non-owning SoA type into an
    /// owning [`SoAVec`].
    pub trait ToSoAVec<T: SOA> {
        type SoAVecType: SoAVec<T>;

        /// Similar to [`slice::to_vec()`](https://doc.rust-lang.org/std/primitive.slice.html#method.to_vec)
        fn to_vec(&self) -> Self::SoAVecType;
    }

    /// A trait to implement `Clone`-dependent behavior to extend an [`SoAVec`] with data copied
    /// from its associated `Slice` type.
    pub trait SoAAppendVec<T: SOA>: SoAVec<T> {

        /// Analogous to [`Vec::extend_from_slice`]
        fn extend_from_slice(&mut self, other: Self::Slice<'_>);
    }

    /// A trait to express the [`IntoIterator`] guarantee of [`SoASlice`] types in the type system.
    pub trait IntoSoAIter<'a, T: SOA>: SoASlice<T> + IntoIterator<Item=Self::Ref<'a>> + 'a {}
}
pub use generics::*;


#[macro_export]
#[doc(hidden)]
macro_rules! soa_zip_impl {
    // @flatten creates a tuple-flattening closure for .map() call
    // Finish recursion
    (@flatten $p:pat => $tup:expr ) => {
        |$p| $tup
    };
    // Eat an element ($_iter) and add it to the current closure. Then recurse
    (@flatten $p:pat => ( $($tup:tt)* ) , $_iter:expr $( , $tail:expr )* ) => {
        $crate::soa_zip_impl!(@flatten ($p, a) => ( $($tup)*, a ) $( , $tail )*)
    };

    // The main code is emmited here: we create an iterator, zip it and then
    // map the zipped iterator to flatten it
    (@last , $first: expr, $($tail: expr,)*) => {
        ::core::iter::IntoIterator::into_iter($first)
            $(
                .zip($tail)
            )*
            .map(
                $crate::soa_zip_impl!(@flatten a => (a) $( , $tail )*)
            )
    };

    // Eat the last `mut $field` and then emit code
    (@munch $self: expr, {mut $field: ident} -> [$($output: tt)*] $($ext: expr ,)*) => {
        $crate::soa_zip_impl!(@last $($output)*, $self.$field.iter_mut(), $($ext, )*)
    };
    // Eat the last `$field` and then emit code
    (@munch $self: expr, {$field: ident} -> [$($output: tt)*] $($ext: expr ,)*) => {
        $crate::soa_zip_impl!(@last $($output)*, $self.$field.iter(), $($ext, )*)
    };

    // Eat the next `mut $field` and then recurse
    (@munch $self: expr, {mut $field: ident, $($tail: tt)*} -> [$($output: tt)*] $($ext: expr ,)*) => {
        $crate::soa_zip_impl!(@munch $self, {$($tail)*} -> [$($output)*, $self.$field.iter_mut()] $($ext, )*)
    };
    // Eat the next `$field` and then recurse
    (@munch $self: expr, {$field: ident, $($tail: tt)*} -> [$($output: tt)*] $($ext: expr ,)*) => {
        $crate::soa_zip_impl!(@munch $self, {$($tail)*} -> [$($output)*, $self.$field.iter()] $($ext, )*)
    };
}