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
use super::*;

impl<'a, T, N> GetIndex<'a, &'a [T]> for StaticRange<N>
where
    N: Unsigned + Array<T>,
    <N as Array<T>>::Array: 'a,
{
    type Output = &'a N::Array;
    #[inline]
    fn get(self, set: &&'a [T]) -> Option<Self::Output> {
        if self.end() <= set.len() {
            Some(unsafe { GetIndex::at_unchecked(self, set) })
        } else {
            None
        }
    }
    #[inline]
    unsafe fn at_unchecked(self, set: &&'a [T]) -> Self::Output {
        &*((*set).as_ptr().add(self.start()) as *const N::Array)
    }
}

impl<'a, T, N> IsolateIndex<&'a [T]> for StaticRange<N>
where
    N: Unsigned + Array<T>,
    <N as Array<T>>::Array: 'a,
{
    type Output = &'a N::Array;
    #[inline]
    unsafe fn isolate_unchecked(self, set: &'a [T]) -> Self::Output {
        &*(set.as_ptr().add(self.start()) as *const N::Array)
    }
    #[inline]
    fn try_isolate(self, set: &'a [T]) -> Option<Self::Output> {
        if self.end() <= set.len() {
            Some(unsafe { IsolateIndex::isolate_unchecked(self, set) })
        } else {
            None
        }
    }
}

impl<'a, T, N> IsolateIndex<&'a mut [T]> for StaticRange<N>
where
    N: Unsigned + Array<T>,
    <N as Array<T>>::Array: 'a,
{
    type Output = &'a mut N::Array;
    #[inline]
    unsafe fn isolate_unchecked(self, set: &'a mut [T]) -> Self::Output {
        &mut *(set.as_mut_ptr().add(self.start()) as *mut N::Array)
    }
    #[inline]
    fn try_isolate(self, set: &'a mut [T]) -> Option<Self::Output> {
        if self.end() <= set.len() {
            Some(unsafe { IsolateIndex::isolate_unchecked(self, set) })
        } else {
            None
        }
    }
}

impl<'a, T, I> GetIndex<'a, &'a [T]> for I
where
    I: std::slice::SliceIndex<[T]>,
    <[T] as std::ops::Index<I>>::Output: 'a,
{
    type Output = &'a <[T] as std::ops::Index<I>>::Output;
    #[inline]
    fn get(self, set: &&'a [T]) -> Option<Self::Output> {
        Some(std::ops::Index::<I>::index(*set, self))
    }
    #[inline]
    unsafe fn at_unchecked(self, set: &&'a [T]) -> Self::Output {
        <[T]>::get_unchecked(*set, self)
    }
}

impl<'a, T, I> IsolateIndex<&'a [T]> for I
where
    I: std::slice::SliceIndex<[T]>,
    <I as std::slice::SliceIndex<[T]>>::Output: 'a,
{
    type Output = &'a <[T] as std::ops::Index<I>>::Output;
    #[inline]
    unsafe fn isolate_unchecked(self, set: &'a [T]) -> &'a <[T] as std::ops::Index<I>>::Output {
        set.get_unchecked(self)
    }
    #[inline]
    fn try_isolate(self, set: &'a [T]) -> Option<&'a <[T] as std::ops::Index<I>>::Output> {
        Some(std::ops::Index::<I>::index(set, self))
    }
}

impl<'a, T, I> IsolateIndex<&'a mut [T]> for I
where
    I: std::slice::SliceIndex<[T]>,
    <I as std::slice::SliceIndex<[T]>>::Output: 'a,
{
    type Output = &'a mut <[T] as std::ops::Index<I>>::Output;
    #[inline]
    unsafe fn isolate_unchecked(
        self,
        set: &'a mut [T],
    ) -> &'a mut <[T] as std::ops::Index<I>>::Output {
        set.get_unchecked_mut(self)
    }
    #[inline]
    fn try_isolate(self, set: &'a mut [T]) -> Option<&'a mut <[T] as std::ops::Index<I>>::Output> {
        Some(std::ops::IndexMut::<I>::index_mut(set, self))
    }
}

impl<T> Set for [T] {
    type Elem = T;
    type Atom = T;
    #[inline]
    fn len(&self) -> usize {
        <[T]>::len(self)
    }
}

impl<'a, T: 'a> View<'a> for [T] {
    type Type = &'a [T];

    #[inline]
    fn view(&'a self) -> Self::Type {
        self
    }
}

impl<'a, T: 'a> ViewMut<'a> for [T] {
    type Type = &'a mut [T];

    #[inline]
    fn view_mut(&'a mut self) -> Self::Type {
        self
    }
}

impl<'a, T: 'a> ViewIterator<'a> for [T] {
    type Item = &'a T;
    type Iter = std::slice::Iter<'a, T>;

    #[inline]
    fn view_iter(&'a self) -> Self::Iter {
        self.iter()
    }
}
impl<'a, T: 'a> ViewMutIterator<'a> for [T] {
    type Item = &'a mut T;
    type Iter = std::slice::IterMut<'a, T>;

    #[inline]
    fn view_mut_iter(&'a mut self) -> Self::Iter {
        self.iter_mut()
    }
}

impl<'a, T: 'a> AtomIterator<'a> for [T] {
    type Item = &'a T;
    type Iter = std::slice::Iter<'a, T>;
    #[inline]
    fn atom_iter(&'a self) -> Self::Iter {
        self.iter()
    }
}

impl<'a, T: 'a> AtomMutIterator<'a> for [T] {
    type Item = &'a mut T;
    type Iter = std::slice::IterMut<'a, T>;
    #[inline]
    fn atom_mut_iter(&'a mut self) -> Self::Iter {
        self.iter_mut()
    }
}

impl<'a, T, N> SplitPrefix<N> for &'a [T]
where
    N: Unsigned + Array<T>,
    <N as Array<T>>::Array: 'a,
{
    type Prefix = &'a N::Array;

    #[inline]
    fn split_prefix(self) -> Option<(Self::Prefix, Self)> {
        if self.len() < N::to_usize() {
            None
        } else {
            Some(unsafe {
                let (l, r) = self.split_at(N::to_usize());
                (&*(l.as_ptr() as *const N::Array), r)
            })
        }
    }
}

impl<'a, T, N> SplitPrefix<N> for &'a mut [T]
where
    N: Unsigned + Array<T>,
    <N as Array<T>>::Array: 'a,
{
    type Prefix = &'a mut N::Array;

    #[inline]
    fn split_prefix(self) -> Option<(Self::Prefix, Self)> {
        if self.len() < N::to_usize() {
            None
        } else {
            Some(unsafe {
                let (l, r) = self.split_at_mut(N::to_usize());
                (&mut *(l.as_mut_ptr() as *mut N::Array), r)
            })
        }
    }
}

impl<T, N: Array<T>> UniChunkable<N> for [T] {
    type Chunk = N::Array;
}

impl<'a, T, N: Array<T>> UniChunkable<N> for &'a [T]
where
    <N as Array<T>>::Array: 'a,
{
    type Chunk = &'a N::Array;
}

impl<'a, T, N: Array<T>> UniChunkable<N> for &'a mut [T]
where
    <N as Array<T>>::Array: 'a,
{
    type Chunk = &'a mut N::Array;
}

impl<'a, T, N> IntoStaticChunkIterator<N> for &'a [T]
where
    Self: SplitPrefix<N>,
    N: Unsigned,
{
    type Item = <Self as SplitPrefix<N>>::Prefix;
    type IterType = UniChunkedIter<Self, N>;
    #[inline]
    fn into_static_chunk_iter(self) -> Self::IterType {
        self.into_generic_static_chunk_iter()
    }
}

impl<'a, T, N> IntoStaticChunkIterator<N> for &'a mut [T]
where
    Self: SplitPrefix<N>,
    N: Unsigned,
{
    type Item = <Self as SplitPrefix<N>>::Prefix;
    type IterType = UniChunkedIter<Self, N>;
    #[inline]
    fn into_static_chunk_iter(self) -> Self::IterType {
        self.into_generic_static_chunk_iter()
    }
}

#[cfg(feature = "rayon")]
impl<'a, T: Send + Sync> IntoParChunkIterator for &'a [T] {
    type Item = &'a [T];
    type IterType = rayon::slice::Chunks<'a, T>;

    #[inline]
    fn into_par_chunk_iter(self, chunk_size: usize) -> Self::IterType {
        use rayon::slice::ParallelSlice;
        assert_eq!(self.len() % chunk_size, 0);
        self.par_chunks(chunk_size)
    }
}

#[cfg(feature = "rayon")]
impl<'a, T: Send + Sync> IntoParChunkIterator for &'a mut [T] {
    type Item = &'a mut [T];
    type IterType = rayon::slice::ChunksMut<'a, T>;

    #[inline]
    fn into_par_chunk_iter(self, chunk_size: usize) -> Self::IterType {
        use rayon::slice::ParallelSliceMut;
        assert_eq!(self.len() % chunk_size, 0);
        self.par_chunks_mut(chunk_size)
    }
}

impl<'a, T> SplitFirst for &'a [T] {
    type First = &'a T;

    #[inline]
    fn split_first(self) -> Option<(Self::First, Self)> {
        self.split_first()
    }
    #[inline]
    unsafe fn split_first_unchecked(self) -> (Self::First, Self) {
        (self.get_unchecked(0), &self[1..])
    }
}

impl<'a, T> SplitFirst for &'a mut [T] {
    type First = &'a mut T;

    #[inline]
    fn split_first(self) -> Option<(Self::First, Self)> {
        self.split_first_mut()
    }
    #[inline]
    unsafe fn split_first_unchecked(self) -> (Self::First, Self) {
        let len = self.len();
        let ptr = self.as_mut_ptr();

        // SAFETY: Caller has to check that `0 <= mid <= self.len()`.
        //
        // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference
        // is fine.
        (
            &mut *ptr,
            std::slice::from_raw_parts_mut(ptr.add(1), len - 1),
        )
    }
}

impl<'a, T> IntoStorage for &'a [T] {
    type StorageType = &'a [T];
    #[inline]
    fn into_storage(self) -> Self::StorageType {
        self
    }
}

impl<'a, T> IntoStorage for &'a mut [T] {
    type StorageType = &'a mut [T];
    #[inline]
    fn into_storage(self) -> Self::StorageType {
        self
    }
}

impl<'a, T> StorageView<'a> for &'a [T] {
    type StorageView = &'a [T];
    #[inline]
    fn storage_view(&'a self) -> Self::StorageView {
        self
    }
}

impl<'a, T> Storage for [T] {
    type Storage = [T];
    #[inline]
    fn storage(&self) -> &Self::Storage {
        self
    }
}

impl<'a, T> StorageMut for [T] {
    /// A slice is a type of storage, simply return a mutable reference to self.
    #[inline]
    fn storage_mut(&mut self) -> &mut Self::Storage {
        self
    }
}

impl<'a, T: 'a> CloneWithStorage<Vec<T>> for &'a [T] {
    type CloneType = Vec<T>;
    /// This function simply ignores self and returns storage since self is already
    /// a storage type.
    #[inline]
    fn clone_with_storage(&self, storage: Vec<T>) -> Self::CloneType {
        assert_eq!(self.len(), storage.len());
        storage
    }
}

impl<'a, T: 'a> CloneWithStorage<&'a [T]> for &'a [T] {
    type CloneType = &'a [T];
    /// This function simply ignores self and returns storage since self is already
    /// a storage type.
    #[inline]
    fn clone_with_storage(&self, storage: &'a [T]) -> Self::CloneType {
        assert_eq!(self.len(), storage.len());
        storage
    }
}

impl<'a, T: 'a> CloneWithStorage<&'a mut [T]> for &'a mut [T] {
    type CloneType = &'a mut [T];
    /// This function simply ignores self and returns storage since self is already
    /// a storage type.
    #[inline]
    fn clone_with_storage(&self, storage: &'a mut [T]) -> Self::CloneType {
        assert_eq!(self.len(), storage.len());
        storage
    }
}

impl<'a, T> SplitAt for &mut [T] {
    #[inline]
    fn split_at(self, mid: usize) -> (Self, Self) {
        self.split_at_mut(mid)
    }
}

impl<'a, T> SplitAt for &[T] {
    #[inline]
    fn split_at(self, mid: usize) -> (Self, Self) {
        self.split_at(mid)
    }
}

impl<T> Dummy for &[T] {
    #[inline]
    unsafe fn dummy() -> Self {
        &[]
    }
}

impl<T> Dummy for &mut [T] {
    #[inline]
    unsafe fn dummy() -> Self {
        &mut []
    }
}

impl<T> RemovePrefix for &[T] {
    #[inline]
    fn remove_prefix(&mut self, n: usize) {
        *self = &self[n..];
    }
}

impl<T> RemovePrefix for &mut [T] {
    /// Remove a prefix of size `n` from this mutable slice.
    ///
    /// # Example
    ///
    /// ```rust
    /// use flatk::*;
    /// let mut v = vec![1,2,3,4,5];
    /// let mut s = v.as_mut_slice();
    /// s.remove_prefix(2);
    /// assert_eq!(&[3,4,5], s);
    /// ```
    #[inline]
    fn remove_prefix(&mut self, n: usize) {
        let data = std::mem::take(self);
        *self = &mut data[n..];
    }
}

impl<'a, T, N> ReinterpretAsGrouped<N> for &'a [T]
where
    T: bytemuck::Pod,
    N: Array<T>,
    <N as Array<T>>::Array: 'a,
{
    type Output = &'a [N::Array];
    #[inline]
    fn reinterpret_as_grouped(self) -> Self::Output {
        //unsafe { reinterpret::reinterpret_slice(self) }
        bytemuck::cast_slice(self)
    }
}

impl<'a, T, N> ReinterpretAsGrouped<N> for &'a mut [T]
where
    T: bytemuck::Pod,
    N: Array<T>,
    <N as Array<T>>::Array: 'a,
{
    type Output = &'a mut [N::Array];
    #[inline]
    fn reinterpret_as_grouped(self) -> Self::Output {
        //unsafe { reinterpret::reinterpret_mut_slice(self) }
        bytemuck::cast_slice_mut(self)
    }
}

impl<T> Viewed for [T] {}

impl<T> Truncate for &[T] {
    #[inline]
    fn truncate(&mut self, new_len: usize) {
        // Simply forget about the elements past new_len.
        *self = self.split_at(new_len).0;
    }
}

impl<T> Truncate for &mut [T] {
    #[inline]
    fn truncate(&mut self, new_len: usize) {
        let data = std::mem::take(self);
        // Simply forget about the elements past new_len.
        *self = data.split_at_mut(new_len).0;
    }
}

/*
 * These are base cases for `ConvertStorage`. We apply the conversion at this point since slices
 * are storage types. The following are some common conversion behaviours.
 */

/// Convert a slice into an owned `Vec` type.
impl<'a, T: Clone> StorageInto<Vec<T>> for &'a [T] {
    type Output = Vec<T>;
    #[inline]
    fn storage_into(self) -> Self::Output {
        self.to_vec()
    }
}

impl<T, Out> MapStorage<Out> for &[T] {
    type Input = Self;
    type Output = Out;
    #[inline]
    fn map_storage<F: FnOnce(Self::Input) -> Out>(self, f: F) -> Self::Output {
        f(self)
    }
}

impl<T, Out> MapStorage<Out> for &mut [T] {
    type Input = Self;
    type Output = Out;
    #[inline]
    fn map_storage<F: FnOnce(Self::Input) -> Out>(self, f: F) -> Self::Output {
        f(self)
    }
}

/// Convert a mutable slice into an owned `Vec` type.
impl<'a, T: Clone> StorageInto<Vec<T>> for &'a mut [T] {
    type Output = Vec<T>;
    #[inline]
    fn storage_into(self) -> Self::Output {
        self.to_vec()
    }
}

/// Convert a mutable slice into an immutable borrow.
impl<'a, T: 'a> StorageInto<&'a [T]> for &'a mut [T] {
    type Output = &'a [T];
    #[inline]
    fn storage_into(self) -> Self::Output {
        &*self
    }
}

/*
 * End of ConvertStorage impls
 */

impl<T> SwapChunks for &mut [T] {
    /// Swap non-overlapping chunks beginning at the given indices.
    #[inline]
    fn swap_chunks(&mut self, i: usize, j: usize, chunk_size: usize) {
        assert!(i + chunk_size <= j || j + chunk_size <= i);

        let (lower, upper) = if i < j { (i, j) } else { (j, i) };
        let (l, r) = self.split_at_mut(upper);
        l[lower..lower + chunk_size].swap_with_slice(&mut r[..chunk_size]);
    }
}

impl<T: PartialOrd + Clone> Sort for [T] {
    /// Sort the given indices into this collection with respect to values provided by this collection.
    /// Invalid values like `NaN` in floats will be pushed to the end.
    #[inline]
    fn sort_indices(&self, indices: &mut [usize]) {
        indices.sort_by(|&a, &b| {
            self[a]
                .partial_cmp(&self[b])
                .unwrap_or(std::cmp::Ordering::Less)
        });
    }
}

impl<T> PermuteInPlace for &mut [T] {
    /// Permute this slice according to the given permutation.
    /// The given permutation must have length equal to this slice.
    /// The slice `seen` is provided to keep track of which elements have already been seen.
    /// `seen` is assumed to be initialized to `false` and have length equal or
    /// larger than this slice.
    #[inline]
    fn permute_in_place(&mut self, permutation: &[usize], seen: &mut [bool]) {
        let data = std::mem::take(self);
        UniChunked {
            chunk_size: 1,
            data,
        }
        .permute_in_place(permutation, seen);
    }
}

impl<T: Clone> CloneIntoOther<Vec<T>> for [T] {
    #[inline]
    fn clone_into_other(&self, other: &mut Vec<T>) {
        other.clear();
        other.extend_from_slice(self);
    }
}

impl<T: Clone> CloneIntoOther for [T] {
    #[inline]
    fn clone_into_other(&self, other: &mut [T]) {
        assert_eq!(self.len(), other.len());
        other.clone_from_slice(self);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn clone_into_other() {
        let a = vec![1, 2, 3, 4];

        // slice -> mut slice
        let mut b = vec![5, 6, 7, 8];
        a.as_slice().clone_into_other(b.as_mut_slice());
        assert_eq!(b, a);
    }

    /// Test below verify that isolating a slice will correctly panic when the underlying collection has the wrong size.
    /// This used to cause an invalid memory reference, and these tests ensure it doesn't happen again.

    #[test]
    #[should_panic]
    fn slice_mut_isolate_panic() {
        let mut b: Vec<i32> = vec![];
        dbg!(b.view_mut().isolate(0));
    }
    #[test]
    #[should_panic]
    fn slice_isolate_panic() {
        let b: Vec<i32> = vec![];
        dbg!(b.view().isolate(0));
    }
}