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
#![cfg_attr(not(any(test, feature = "std")), no_std)]
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]

mod chain;
mod chunks;
mod cycle;
mod debug;
mod eq;
mod impls;
mod index;
mod interleave;
mod iter;
mod map;
mod reverse;
mod slicing;
mod windows;

#[cfg(test)]
mod test;

use core::ops::RangeBounds;

pub use chain::Chain;
pub use chunks::{ArrayChunksBorrowed, ArrayChunksOwned, ChunksBorrowed, ChunksOwned};
pub use cycle::Cycle;
pub use interleave::Interleave;
pub use iter::{IterBorrowed, IterOwned};
pub use map::{MapBorrowed, MapOwned};
pub use reverse::Reverse;
pub use slicing::SliceOf;
pub use windows::{ArrayWindowsBorrowed, ArrayWindowsOwned, WindowsBorrowed, WindowsOwned};

/// Clones each item on access; see [`SliceBorrowed::cloned`].
pub type Cloned<S> = MapBorrowed<S, for<'a> fn(&<S as Slice>::Output) -> <S as Slice>::Output>;

/// The base trait for [`SliceOwned`], [`SliceBorrowed`], and [`SliceMut`].
pub trait Slice {
    /// The type this slice returns; analagous to
    /// [`Index::Output`](core::ops::Index::Output).
    type Output;

    /// Returns the length of the slice.
    fn len(&self) -> usize;

    /// Returns whether or not the slice is empty.
    ///
    /// Equivalent to `slice.len() == 0`.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Call a closure with the indicated element, returning the result or
    /// `None` if the index was out-of-bounds.
    ///
    /// This allows operations that are independent of indexing method.
    fn get_with<W: FnMut(&Self::Output) -> R, R>(&self, index: usize, f: &mut W) -> Option<R>;

    /// Chains two slices together, back-to-back.
    ///
    /// Analagous to [`Iterator::chain`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::Slice;
    /// let a = [1, 2, 3];
    /// let b = [4, 5, 6];
    ///
    /// assert_eq!(a.chain(b), [1, 2, 3, 4, 5, 6]);
    /// ```
    fn chain<S: Slice<Output = Self::Output>>(self, other: S) -> Chain<Self, S>
    where
        Self: Sized,
    {
        Chain(self, other)
    }

    /// Cycles the slice infinitely.
    ///
    /// Analagous to [`Iterator::cycle`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::{Slice, SliceOwned};
    /// let slice = [1, 2, 3].cycle();
    /// assert_eq!(slice.get_owned(2), Some(3));
    /// assert_eq!(slice.get_owned(4), Some(2));
    /// assert_eq!(slice.get_owned(6), Some(1));
    /// ```
    fn cycle(self) -> Cycle<Self>
    where
        Self: Sized,
    {
        Cycle(self)
    }

    /// Interleaves two slices, e.g. [A, B, A, B, ...].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::Slice;
    /// let a = [1, 2, 3];
    /// let b = [4, 5, 6];
    /// let c = a.interleave(b);
    ///
    /// assert_eq!(c, [1, 4, 2, 5, 3, 6]);
    /// ```
    fn interleave<S: Slice<Output = Self::Output>>(self, other: S) -> Interleave<Self, S>
    where
        Self: Sized,
    {
        Interleave(self, other)
    }

    /// Reverses the slice.
    ///
    /// Analagous to [`Iterator::rev`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::Slice;
    /// let slice = [1, 2, 3].rev();
    /// assert_eq!(slice, [3, 2, 1]);
    /// ```
    fn rev(self) -> Reverse<Self>
    where
        Self: Sized,
    {
        Reverse(self)
    }

    /// Create a sub-slice of the slice.
    ///
    /// Analagous to slicing `&[T]`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::Slice;
    /// let slice = [1, 2, 3, 4, 5].slice(1..4).unwrap();
    /// assert_eq!(slice, [2, 3, 4]);
    /// ```
    fn slice<R: RangeBounds<usize>>(self, range: R) -> Option<SliceOf<Self>>
    where
        Self: Sized,
    {
        SliceOf::new(self, range)
    }

    /// Returns `(&self[..at], &self[at..])`.
    /// Returns `None` if `at` is out-of-bounds.
    ///
    /// Equivalent of [`slice::split`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::Slice;
    /// let slice = [1, 2, 3, 4, 5, 6];
    /// let (a, b) = slice.split(3).unwrap();
    ///
    /// assert_eq!(a, [1, 2, 3]);
    /// assert_eq!(b, [4, 5, 6]);
    /// ```
    fn split(&self, at: usize) -> Option<(SliceOf<&Self>, SliceOf<&Self>)> {
        Some((SliceOf::new(self, ..at)?, SliceOf::new(self, at..)?))
    }
}

/// A [`Slice`] that can return owned values.
pub trait SliceOwned: Slice {
    /// Index the slice, returning an owned value.
    fn get_owned(&self, index: usize) -> Option<Self::Output>;

    /// Return an iterator over arrays covering consecutive portions of the
    /// slice.
    ///
    /// Analagous to [`slice::array_chunks`].
    ///
    /// # Panics
    ///
    /// If `N == 0`, panics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::{SliceOwned};
    /// let slice = [1, 2, 3, 4, 5];
    /// let mut iter = slice.array_chunks::<2>();
    ///
    /// assert_eq!(iter.next(), Some([1, 2]));
    /// assert_eq!(iter.next(), Some([3, 4]));
    /// assert!(iter.next().is_none());
    /// assert_eq!(iter.remainder(), [5]);
    /// ```
    fn array_chunks<const N: usize>(self) -> ArrayChunksOwned<Self, N>
    where
        Self: Sized,
    {
        ArrayChunksOwned::new(self)
    }

    /// Return an iterator over arrays covering overlapping portions of the
    /// slice.
    ///
    /// Analagous to [`slice::array_windows`].
    ///
    /// # Panics
    ///
    /// If `N == 0`, panics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::{SliceOwned};
    /// let slice = [1, 2, 3, 4, 5];
    /// let mut iter = slice.array_windows::<3>();
    ///
    /// assert_eq!(iter.next(), Some([1, 2, 3]));
    /// assert_eq!(iter.next(), Some([2, 3, 4]));
    /// assert_eq!(iter.next(), Some([3, 4, 5]));
    /// assert!(iter.next().is_none());
    /// ```
    fn array_windows<const N: usize>(self) -> ArrayWindowsOwned<Self, N>
    where
        Self: Sized,
    {
        ArrayWindowsOwned::new(self)
    }

    /// Return an iterator over slices covering consecutive portions of the
    /// slice.
    ///
    /// Analagous to [`slice::chunks`].
    ///
    /// # Panics
    ///
    /// If `size == 0`, panics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::SliceOwned;
    /// let slice = [1, 2, 3, 4, 5];
    /// let mut iter = slice.chunks(2);
    ///
    /// assert_eq!(iter.next().unwrap(), [1, 2]);
    /// assert_eq!(iter.next().unwrap(), [3, 4]);
    /// assert_eq!(iter.next().unwrap(), [5]);
    /// assert!(iter.next().is_none());
    /// ```
    fn chunks(&self, size: usize) -> ChunksOwned<Self> {
        ChunksOwned::new(self, size)
    }

    /// Call a closure on index, returning a new type.
    ///
    /// Analagous to [`Iterator::map`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::SliceOwned;
    /// let slice = [0, 1, 2].map(|x| x != 0);
    /// assert_eq!(slice, [false, true, true]);
    /// ```
    fn map<F: Fn(Self::Output) -> R, R>(self, f: F) -> MapOwned<Self, F>
    where
        Self: Sized,
    {
        MapOwned(self, f)
    }

    /// Creates an iterator over the slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::{Slice, SliceOwned};
    /// let slice = [1, 2].chain([3]);
    /// let mut iter = slice.iter();
    /// assert_eq!(iter.next(), Some(1));
    /// assert_eq!(iter.next(), Some(2));
    /// assert_eq!(iter.next(), Some(3));
    /// assert!(iter.next().is_none());
    /// ```
    fn iter(self) -> IterOwned<Self>
    where
        Self: Sized,
    {
        IterOwned::new(self)
    }

    /// Return an iterator over slices covering overlapping portions of the
    /// slice. The last window may be smaller than the rest.
    ///
    /// Analagous to [`slice::windows`].
    ///
    /// # Panics
    ///
    /// If `size == 0`, panics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::{SliceOwned};
    /// let slice = [1, 2, 3, 4, 5];
    /// let mut iter = slice.windows(3);
    ///
    /// assert_eq!(iter.next().unwrap(), [1, 2, 3]);
    /// assert_eq!(iter.next().unwrap(), [2, 3, 4]);
    /// assert_eq!(iter.next().unwrap(), [3, 4, 5]);
    /// assert!(iter.next().is_none());
    /// ```
    fn windows(&self, size: usize) -> WindowsOwned<Self> {
        WindowsOwned::new(self, size)
    }

    /// Collect the slice into a `Vec`. Only available on feature `std`.
    ///
    /// Analagous to [`Iterator::collect`].
    #[cfg(feature = "std")]
    fn collect(&self) -> Vec<Self::Output> {
        let mut v = Vec::with_capacity(self.len());
        for i in 0..self.len() {
            v.push(self.get_owned(i).unwrap());
        }

        v
    }
}

/// A [`Slice`] that can return borrowed values.
pub trait SliceBorrowed: Slice {
    /// Index the slice, returning a borrowed value.
    fn get(&self, index: usize) -> Option<&Self::Output>;

    /// Return an iterator over arrays covering consecutive portions of the
    /// slice.
    ///
    /// Analagous to [`slice::array_chunks`].
    ///
    /// # Panics
    ///
    /// If `N == 0`, panics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::SliceBorrowed;
    /// let slice = [1, 2, 3, 4, 5];
    /// let mut iter = slice.array_chunks::<2>();
    ///
    /// assert_eq!(iter.next(), Some([&1, &2]));
    /// assert_eq!(iter.next(), Some([&3, &4]));
    /// assert!(iter.next().is_none());
    /// assert_eq!(iter.remainder(), [5]);
    /// ```
    fn array_chunks<const N: usize>(&self) -> ArrayChunksBorrowed<Self, N> {
        ArrayChunksBorrowed::new(self)
    }

    /// Return an iterator over arrays covering overlapping portions of the
    /// slice.
    ///
    /// Analagous to [`slice::array_windows`].
    ///
    /// # Panics
    ///
    /// If `N == 0`, panics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::SliceBorrowed;
    /// let slice = [1, 2, 3, 4, 5];
    /// let mut iter = slice.array_windows::<3>();
    ///
    /// assert_eq!(iter.next(), Some([&1, &2, &3]));
    /// assert_eq!(iter.next(), Some([&2, &3, &4]));
    /// assert_eq!(iter.next(), Some([&3, &4, &5]));
    /// assert!(iter.next().is_none());
    /// ```
    fn array_windows<const N: usize>(&self) -> ArrayWindowsBorrowed<Self, N> {
        ArrayWindowsBorrowed::new(self)
    }

    /// Return an iterator over slices covering consecutive portions of the
    /// slice.
    ///
    /// Analagous to [`slice::chunks`].
    ///
    /// # Panics
    ///
    /// If `size == 0`, panics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::SliceBorrowed;
    /// let slice = [1, 2, 3, 4, 5];
    /// let mut iter = slice.chunks(2);
    ///
    /// assert_eq!(iter.next().unwrap(), [1, 2]);
    /// assert_eq!(iter.next().unwrap(), [3, 4]);
    /// assert_eq!(iter.next().unwrap(), [5]);
    /// assert!(iter.next().is_none());
    /// ```
    fn chunks(&self, size: usize) -> ChunksBorrowed<Self> {
        ChunksBorrowed::new(self, size)
    }

    /// Call a closure on index, returning a new type.
    ///
    /// Analagous to [`Iterator::map`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::SliceBorrowed;
    /// let slice = [0, 1, 2].map(|x| x != 0);
    /// assert_eq!(slice, [false, true, true]);
    /// ```
    fn map<F: Fn(&Self::Output) -> R, R>(self, f: F) -> MapBorrowed<Self, F>
    where
        Self: Sized,
    {
        MapBorrowed(self, f)
    }

    /// Create a new slice that clones each value on access.
    /// Analagous to <code>self.[map](SliceBorrowed::map)([Clone::clone])</code>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::SliceBorrowed;
    /// # #[derive(Debug, PartialEq)]
    /// struct Foo(u32);
    /// impl Clone for Foo {
    ///     fn clone(&self) -> Foo { Foo(self.0 + 1) }
    /// }
    ///
    /// let slice = [Foo(1), Foo(2)];
    /// assert_eq!(slice.cloned(), [Foo(2), Foo(3)]);
    /// ```
    fn cloned(self) -> Cloned<Self>
    where
        Self: Sized,
        Self::Output: Clone,
    {
        MapBorrowed(self, Clone::clone)
    }

    /// Creates an iterator over the slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::{Slice, SliceBorrowed};
    /// let slice = [1, 2].chain([3]);
    /// let mut iter = slice.iter();
    /// assert_eq!(iter.next(), Some(&1));
    /// assert_eq!(iter.next(), Some(&2));
    /// assert_eq!(iter.next(), Some(&3));
    /// assert!(iter.next().is_none());
    /// ```
    fn iter(&self) -> IterBorrowed<Self> {
        IterBorrowed::new(self)
    }

    /// Return an iterator over slices covering overlapping portions of the
    /// slice. The last window may be smaller than the rest.
    ///
    /// Analagous to [`slice::windows`].
    ///
    /// # Panics
    ///
    /// If `size == 0`, panics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_utils::{SliceBorrowed};
    /// let slice = [1, 2, 3, 4, 5];
    /// let mut iter = slice.windows(3);
    ///
    /// assert_eq!(iter.next().unwrap(), [1, 2, 3]);
    /// assert_eq!(iter.next().unwrap(), [2, 3, 4]);
    /// assert_eq!(iter.next().unwrap(), [3, 4, 5]);
    /// assert!(iter.next().is_none());
    /// ```
    fn windows(&self, size: usize) -> WindowsBorrowed<Self> {
        WindowsBorrowed::new(self, size)
    }
}

/// A [`Slice`] that can return mutably borrowed values.
pub trait SliceMut: Slice {
    /// Index the slice, returning a mutably borrowed value.
    fn get_mut(&mut self, index: usize) -> Option<&mut Self::Output>;
}