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
//! Wrapping around for slices.
//!
//! Implements a wrapper around slices that allows for indexing beyond the
//! length of the slice, by taking the index always modulo the length.
//!
//! # Example
//! ```
//! use wrapping::Wrapping;
//!
//! let array: [&str; 1] = ["hello"];
//! let wrapping = Wrapping::from(&array[..]);
//!
//! assert_eq!(wrapping[0], "hello");
//! assert_eq!(wrapping[1], "hello");
//! ```
#![deny(missing_docs)]
#![deny(clippy::all)]

use std::ops::{Index, IndexMut};

/// Wrapper around an immutable slice that allows for indexing out of bounds.
///
/// # Example
/// ```
/// use wrapping::Wrapping;
///
/// let array: [&str; 1] = ["hello"];
/// let wrapping = Wrapping::from(&array[..]);
///
/// assert_eq!(wrapping[0], "hello");
/// assert_eq!(wrapping[1], "hello");
/// ```
pub struct Wrapping<'a, T>(&'a [T]);

impl<'a, T> Index<usize> for Wrapping<'a, T> {
    type Output = T;

    fn index(&self, idx: usize) -> &T {
        &self.0[idx % self.0.len()]
    }
}

impl<'a, T, I: Into<&'a [T]>> From<I> for Wrapping<'a, T> {
    fn from(into: I) -> Self {
        Self(into.into())
    }
}

/// Wrapper around a mutable slice that allows for indexing out of bounds.
///
/// # Example
/// ```
/// use wrapping::MutWrapping;
///
/// let mut array: [&str; 1] = ["hello"];
/// let mut wrapping = MutWrapping::from(&mut array[..]);
///
/// assert_eq!(wrapping[0], "hello");
/// wrapping[1] = "world";
/// assert_eq!(wrapping[0], "world");
/// ```
pub struct MutWrapping<'a, T>(&'a mut [T]);

impl<'a, T> Index<usize> for MutWrapping<'a, T> {
    type Output = T;

    fn index(&self, idx: usize) -> &T {
        &self.0[idx % self.0.len()]
    }
}

impl<'a, T> IndexMut<usize> for MutWrapping<'a, T> {
    fn index_mut(&mut self, idx: usize) -> &mut T {
        &mut self.0[idx % self.0.len()]
    }
}

impl<'a, T, I: Into<&'a mut [T]>> From<I> for MutWrapping<'a, T> {
    fn from(into: I) -> Self {
        Self(into.into())
    }
}