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
use core::marker::PhantomData;

/// Trait that says that T can be safely transmuted into F
pub unsafe trait TransmutableFrom<T: Sized>: Sized {
    fn transmute_from(val: T) -> Self;

    fn transmute_slice_from(val: &[T]) -> &[Self] {
        let len = val.len();
        let ptr = val.as_ptr() as *const Self;

        unsafe { core::slice::from_raw_parts(ptr, len) }
    }

    fn transmute_slice_from_mut(val: &mut [T]) -> &mut [Self] {
        let len = val.len();
        let ptr = val.as_mut_ptr() as *mut Self;

        unsafe { core::slice::from_raw_parts_mut(ptr, len) }
    }
}

pub unsafe trait TransmutableInto<T: Sized>: Sized {
    fn transmute_into(val: Self) -> T;

    fn transmute_slice_into(val: &[Self]) -> &[T] {
        let len = val.len();
        let ptr = val.as_ptr() as *const T;

        unsafe { core::slice::from_raw_parts(ptr, len) }
    }

    fn transmute_slice_into_mut(val: &mut [Self]) -> &mut [T] {
        let len = val.len();
        let ptr = val.as_mut_ptr() as *mut T;

        unsafe { core::slice::from_raw_parts_mut(ptr, len) }
    }
}

unsafe impl<T: TransmutableFrom<F>, F: Sized> TransmutableInto<T> for F {
    fn transmute_into(val: Self) -> T {
        T::transmute_from(val)
    }
}

unsafe impl<T: Sized> TransmutableFrom<T> for T {
    fn transmute_from(val: T) -> Self {
        val
    }
}

pub trait SliceExt {
    type Item;

    /// Returns an iterator over `N` elements of the slice at a time, starting at the
    /// beginning of the slice.
    ///
    /// The chunks are array references and do not overlap. If `N` does not divide the
    /// length of the slice, then the last up to `N-1` elements will be omitted and can be
    /// retrieved from the [`remainder`](ArrayChunks::remainder) function of the iterator.
    ///
    /// Note: this function is designed to be equivalent to the currently unstable core::slice::array_chunks.
    fn uarray_chunks<const SIZE: usize>(&self) -> ArrayChunks<Self::Item, SIZE>;

    /// Returns an iterator over `N` elements of the slice at a time, starting at the
    /// beginning of the slice.
    ///
    /// The chunks are mutable array references and do not overlap. If `N` does not divide
    /// the length of the slice, then the last up to `N-1` elements will be omitted and
    /// can be retrieved from the [`into_remainder`](ArrayChunksMut::into_remainder) function of the iterator.
    ///
    /// Note: this function is designed to be equivalent to the currently unstable core::slice::array_chunks_mut.
    fn uarray_chunks_mut<const SIZE: usize>(&mut self) -> ArrayChunksMut<Self::Item, SIZE>;
}

impl<T> SliceExt for [T] {
    type Item = T;

    fn uarray_chunks<const SIZE: usize>(&self) -> ArrayChunks<Self::Item, SIZE> {
        ArrayChunks { inner: &self }
    }

    fn uarray_chunks_mut<const SIZE: usize>(&mut self) -> ArrayChunksMut<Self::Item, SIZE> {
        let len = self.len();
        let start = self.as_mut_ptr();

        ArrayChunksMut {
            start,
            len,
            phantomdata: PhantomData,
        }
    }
}

pub struct ArrayChunks<'a, T: 'a, const SIZE: usize> {
    inner: &'a [T],
}

impl<'a, T: 'a, const SIZE: usize> ArrayChunks<'a, T, SIZE> {
    pub fn remainder(&self) -> &'a [T] {
        self.inner
    }
}

impl<'a, T: 'a, const SIZE: usize> Iterator for ArrayChunks<'a, T, SIZE> {
    type Item = &'a [T; SIZE];

    fn next(&mut self) -> Option<Self::Item> {
        if self.inner.len() < SIZE {
            return None;
        }

        let (arr, rem) = self.inner.split_at(SIZE);
        self.inner = rem;

        let item = unsafe { <&'a [T; SIZE]>::try_from(arr).unwrap_unchecked() };

        Some(item)
    }
}

// I had to implement this using raw pointers because the compiler was giving weird lifetime errors
pub struct ArrayChunksMut<'a, T: 'a, const SIZE: usize> {
    start: *mut T,
    len: usize,

    phantomdata: PhantomData<&'a mut ()>,
}

impl<'a, T: 'a, const SIZE: usize> ArrayChunksMut<'a, T, SIZE> {
    pub fn into_remainder(self) -> &'a mut [T] {
        unsafe { core::slice::from_raw_parts_mut(self.start, self.len) }
    }
}

impl<'a, T: 'a, const SIZE: usize> Iterator for ArrayChunksMut<'a, T, SIZE> {
    type Item = &'a mut [T; SIZE];

    fn next(&mut self) -> Option<Self::Item> {
        if self.len < SIZE {
            return None;
        }

        unsafe {
            let arr: *mut [T; SIZE] = self.start.cast();

            self.len -= SIZE;
            self.start = self.start.offset(SIZE as isize);

            Some(&mut *arr)
        }
    }
}

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

    #[test]
    fn array_chunks() {
        let arr = [1, 2, 3, 5, 7, 11];
        let mut chunks = arr.uarray_chunks();

        assert_eq!(chunks.next(), Some(&[1, 2]));
        assert_eq!(chunks.next(), Some(&[3, 5]));
        assert_eq!(chunks.next(), Some(&[7, 11]));
        assert_eq!(chunks.next(), None);

        let arr = [1, 2, 3, 5, 7, 11, 13];
        let mut chunks = arr.uarray_chunks();

        assert_eq!(chunks.next(), Some(&[1, 2]));
        assert_eq!(chunks.next(), Some(&[3, 5]));
        assert_eq!(chunks.next(), Some(&[7, 11]));
        assert_eq!(chunks.next(), None);
    }

    #[test]
    fn array_chunks_mut() {
        let mut arr = [1, 2, 3, 5, 7, 11];
        let mut chunks = arr.uarray_chunks_mut();

        assert_eq!(chunks.next(), Some(&mut [1, 2]));
        assert_eq!(chunks.next(), Some(&mut [3, 5]));
        assert_eq!(chunks.next(), Some(&mut [7, 11]));
        assert_eq!(chunks.next(), None);

        let mut arr = [1, 2, 3, 5, 7, 11, 13];
        let mut chunks = arr.uarray_chunks_mut();

        assert_eq!(chunks.next(), Some(&mut [1, 2]));
        assert_eq!(chunks.next(), Some(&mut [3, 5]));
        assert_eq!(chunks.next(), Some(&mut [7, 11]));
        assert_eq!(chunks.next(), None);
    }
}