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
use {Stride, MutStride};
use std::ops::{Deref, DerefMut};

/// Things that can be viewed as a series of equally spaced `T`s in
/// memory.
pub trait Strided {
    type Elem;
    fn as_stride(&self) -> Stride<Self::Elem>;

    fn stride(&self) -> usize {
        self.as_stride().stride()
    }
}

/// Things that can be viewed as a series of mutable equally spaced
/// `T`s in memory.
pub trait MutStrided : Strided {
    fn as_stride_mut(&mut self) -> MutStride<<Self as Strided>::Elem>;
}

// this isn't as general as it could be.
impl<T, X: Deref<Target=[T]>> Strided for X {
    type Elem = T;
    fn as_stride(&self) -> Stride<T> {
        Stride::new(&**self)
    }

    #[inline(always)]
    fn stride(&self) -> usize {
        1
    }
}
impl<T, X: DerefMut + Deref<Target=[T]>> MutStrided for X {
    fn as_stride_mut(&mut self) -> MutStride<T> {
        MutStride::new(&mut **self)
    }
}

impl<T> Strided for [T] {
    type Elem = T;
    fn as_stride(&self) -> Stride<T> { Stride::new(self) }
    #[inline(always)]
    fn stride(&self) -> usize { 1 }
}
impl<T> MutStrided for [T] {
    fn as_stride_mut(&mut self) -> MutStride<T> { MutStride::new(self) }
}

impl<'a,T> Strided for Stride<'a,T> {
    type Elem = T;
    fn as_stride(&self) -> Stride<T> { *self }
    fn stride(&self) -> usize { Stride::stride(self) }
}
impl<'a,T> Strided for MutStride<'a,T> {
    type Elem = T;
    fn as_stride(&self) -> Stride<T> { **self }
    fn stride(&self) -> usize { MutStride::stride(self) }
}
impl<'a,T> MutStrided for MutStride<'a,T> {
    fn as_stride_mut(&mut self) -> MutStride<T> { self.reborrow() }
}

impl<'a,T, X: AsRef<[T]> + ?Sized> From<&'a X> for Stride<'a,T> {
    fn from(value: &X) -> Stride<T> { Stride::new(value.as_ref()) }
}
impl<'a,T, X: AsMut<[T]> + ?Sized> From<&'a mut X> for MutStride<'a,T> {
    fn from(value: &mut X) -> MutStride<T> { MutStride::new(value.as_mut()) }
}