wrapping 0.2.0

Wrapping slices and arrays
Documentation
//! 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())
    }
}