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
use std::ops::Deref;

use super::Indices;

/// This type ensures statically that the indices are sorted and unique.
///
/// This ensures only a single comparison is needed to check if the indices
/// are in bounds of a slice.
///
/// # Example codegen
///
/// ```rust
/// use index_many::generic::PresortedIndices;
/// pub fn example(slice: &mut [usize], indices: PresortedIndices<3>) -> [&mut usize; 3] {
///     index_many::generic::index_many_mut(slice, indices)
/// }
/// ```
///
/// ```nasm
/// example:
///  sub     rsp, 56
///  mov     r11, qword, ptr, [r9]
///  mov     r10, qword, ptr, [r9, +, 8]
///  mov     rax, qword, ptr, [r9, +, 16]
///  cmp     rax, r8
///  jae     .LBB2_1
///  lea     r8, [rdx, +, 8*r11]
///  lea     r9, [rdx, +, 8*r10]
///  lea     rax, [rdx, +, 8*rax]
///  mov     qword, ptr, [rcx], r8
///  mov     qword, ptr, [rcx, +, 8], r9
///  mov     qword, ptr, [rcx, +, 16], rax
///  mov     rax, rcx
///  add     rsp, 56
///  ret
/// .LBB2_1:
///  mov     qword, ptr, [rsp, +, 32], r11
///  mov     qword, ptr, [rsp, +, 40], r10
///  mov     qword, ptr, [rsp, +, 48], rax
///  lea     rcx, [rsp, +, 32]
///  mov     edx, 3
///  call    index_many::bound_check_failed
///  ud2
/// ```
#[derive(Copy, Clone)]
pub struct PresortedIndices<const N: usize> {
    indices: [usize; N],
}

impl<const N: usize> Deref for PresortedIndices<N> {
    type Target = [usize; N];

    fn deref(&self) -> &Self::Target {
        &self.indices
    }
}

#[derive(Debug)]
pub struct PresortedIndicesError {
    _private: (),
}

impl<const N: usize> PresortedIndices<N> {
    pub fn new(indices: [usize; N]) -> Result<Self, PresortedIndicesError> {
        let mut valid = true;
        for &[a, b] in indices.array_windows() {
            valid &= a < b;
        }
        if valid {
            Ok(Self { indices })
        } else {
            Err(PresortedIndicesError { _private: () })
        }
    }
}

unsafe impl<const N: usize> Indices<N> for PresortedIndices<N> {
    #[inline]
    fn to_raw_indices(&self) -> [usize; N] {
        self.indices
    }

    #[inline]
    fn is_valid(&self, len: usize) -> bool {
        let mut valid = true;

        if let Some(&idx) = self.indices.last() {
            valid &= idx < len;
        }

        valid
    }

    #[inline(always)]
    fn cause_invalid_panic(&self, len: usize) -> ! {
        crate::bound_check_failed(&self.indices, len)
    }
}

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

    fn index_many<'a, T, const N: usize>(slice: &[T], indices: [usize; N]) -> [&T; N] {
        let indices = PresortedIndices::new(indices).unwrap();
        assert!(indices.indices.is_sorted());
        super::super::index_many(slice, indices)
    }

    fn index_many_mut<'a, T, const N: usize>(slice: &mut [T], indices: [usize; N]) -> [&mut T; N] {
        let indices = PresortedIndices::new(indices).unwrap();
        assert!(indices.indices.is_sorted());
        super::super::index_many_mut(slice, indices)
    }

    #[test]
    fn test_mut_normal() {
        let mut v = vec![1, 2, 3, 4, 5];
        let [a, b, c] = index_many_mut(&mut v, [0, 2, 4]);
        *a += 10;
        *b += 100;
        *c += 1000;
        assert_eq!(v, vec![11, 2, 103, 4, 1005]);
    }

    #[test]
    fn test_ref_normal() {
        let v = vec![1, 2, 3, 4, 5];
        let [a, b, c] = index_many(&v, [0, 2, 4]);
        assert_eq!(a, &1);
        assert_eq!(b, &3);
        assert_eq!(c, &5);
        assert_eq!(v, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_mut_empty() {
        let mut v = vec![1, 2, 3, 4, 5];
        let [] = index_many_mut(&mut v, []);
        assert_eq!(v, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_ref_empty() {
        let v = vec![1, 2, 3, 4, 5];
        let [] = index_many(&v, []);
        assert_eq!(v, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_mut_single_first() {
        let mut v = vec![1, 2, 3, 4, 5];
        let [a] = index_many_mut(&mut v, [0]);
        *a += 10;
        assert_eq!(v, vec![11, 2, 3, 4, 5]);
    }

    #[test]
    fn test_ref_single_first() {
        let v = vec![1, 2, 3, 4, 5];
        let [a] = index_many(&v, [0]);
        assert_eq!(a, &1);
        assert_eq!(v, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_mut_single_last() {
        let mut v = vec![1, 2, 3, 4, 5];
        let [a] = index_many_mut(&mut v, [4]);
        *a += 10;
        assert_eq!(v, vec![1, 2, 3, 4, 15]);
    }

    #[test]
    fn test_ref_single_last() {
        let v = vec![1, 2, 3, 4, 5];
        let [a] = index_many(&v, [4]);
        assert_eq!(a, &5);
        assert_eq!(v, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    #[should_panic(
        expected = "Index 5 is out of bounds of slice with len 5 (indices [5], position 0)"
    )]
    fn test_mut_oob_nonempty() {
        let mut v = vec![1, 2, 3, 4, 5];
        index_many_mut(&mut v, [5]);
    }

    #[test]
    #[should_panic(
        expected = "Index 5 is out of bounds of slice with len 5 (indices [5], position 0)"
    )]
    fn test_ref_oob_nonempty() {
        let v = vec![1, 2, 3, 4, 5];
        index_many(&v, [5]);
    }

    #[test]
    #[should_panic(
        expected = "Index 0 is out of bounds of slice with len 0 (indices [0], position 0)"
    )]
    fn test_mut_oob_empty() {
        let mut v: Vec<i32> = vec![];
        index_many_mut(&mut v, [0]);
    }

    #[test]
    #[should_panic(
        expected = "Index 0 is out of bounds of slice with len 0 (indices [0], position 0)"
    )]
    fn test_ref_oob_empty() {
        let v: Vec<i32> = vec![];
        index_many(&v, [0]);
    }

    #[test]
    fn test_unsorted() {
        assert!(PresortedIndices::new([3, 1, 4]).is_err())
    }

    #[test]
    fn test_duplicate() {
        assert!(PresortedIndices::new([1, 3, 3, 4]).is_err())
    }
}