one-indexed-vec 0.2.0

A one-based (1-indexed) wrapper around Vec<T>: element at position N is accessed via vec[N].
Documentation
//! Window operations on `Vec1`.

use crate::Vec1;
use crate::vec1_core::index1::Index1;

impl<T> Vec1<T>
where
    T: Copy,
{
    /// Copy window `[start, end]` (1-based inclusive).
    ///
    /// ```rust
    /// use one_indexed_vec::vec1;
    /// let v = vec1![1, 2, 3, 4, 5];
    /// let w = v.window(2, 4);
    /// assert_eq!(w.as_slice(), &[2, 3, 4]);
    /// ```
    #[inline]
    pub fn window(&self, start: usize, end: usize) -> Vec1<T> {
        assert!(start >= 1, "window: start must be >= 1 (got {start})");
        assert!(end >= 1, "window: end must be >= 1 (got {end})");
        assert!(start <= end, "window: start ({start}) must be <= end ({end})");
        assert!(end <= self.len(), "window: end ({end}) exceeds length ({})", self.len());

        let mut out = Vec1::with_capacity(end - start + 1);
        for idx in start..=end {
            out.push(self[idx]);
        }
        out
    }

    /// Mutable window view.
    ///
    /// ```rust
    /// use one_indexed_vec::vec1;
    /// let mut v = vec1![1, 2, 3, 4, 5];
    /// {
    ///     let mut w = v.window_mut(2, 4);
    ///     for i in 1..=w.len() {
    ///         w[i] *= 2;
    ///     }
    /// }
    /// assert_eq!(v.as_slice(), &[1, 4, 6, 8, 5]);
    /// ```
    #[inline]
    pub fn window_mut(&mut self, start: usize, end: usize) -> WindowMut<'_, T> {
        assert!(start >= 1, "window_mut: start must be >= 1 (got {start})");
        assert!(end >= 1, "window_mut: end must be >= 1 (got {end})");
        assert!(start <= end, "window_mut: start ({start}) must be <= end ({end})");
        assert!(end <= self.len(), "window_mut: end ({end}) exceeds length ({})", self.len());
        WindowMut::new(self, start, end)
    }

    /// Type-safe window.
    #[inline]
    pub fn window_index1(&self, start: Index1, end: Index1) -> Vec1<T> {
        self.window(start.get(), end.get())
    }

    /// Type-safe mutable window.
    #[inline]
    pub fn window_mut_index1(&mut self, start: Index1, end: Index1) -> WindowMut<'_, T> {
        self.window_mut(start.get(), end.get())
    }

    /// Zero-copy read-only view of `[start, end]`.
    #[inline]
    pub fn window_view(&self, start: usize, end: usize) -> &[T] {
        assert!(start >= 1, "window_view: start must be >= 1 (got {start})");
        assert!(end >= 1, "window_view: end must be >= 1 (got {end})");
        assert!(start <= end, "window_view: start ({start}) must be <= end ({end})");
        assert!(end <= self.len(), "window_view: end ({end}) exceeds length ({})", self.len());
        &self.as_slice()[(start - 1)..end]
    }
}

/// A mutable window view into a [`Vec1`].
pub struct WindowMut<'a, T> {
    inner: &'a mut Vec1<T>,
    start: usize,
    end: usize,
}

impl<'a, T> WindowMut<'a, T> {
    #[inline]
    pub(crate) fn new(inner: &'a mut Vec1<T>, start: usize, end: usize) -> Self {
        WindowMut { inner, start, end }
    }

    /// Number of elements in the window.
    #[inline]
    pub fn len(&self) -> usize {
        self.end - self.start + 1
    }

    /// Whether the window is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Read-only slice.
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        &self.inner.as_slice()[(self.start - 1)..self.end]
    }

    /// Mutable slice.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        &mut self.inner.as_mut_slice()[(self.start - 1)..self.end]
    }
}

impl<'a, T> core::ops::Index<usize> for WindowMut<'a, T> {
    type Output = T;

    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        assert!(index >= 1, "WindowMut: index must be >= 1");
        assert!(index <= self.len(), "WindowMut: index out of bounds");
        &self.inner[self.start + index - 1]
    }
}

impl<'a, T> core::ops::IndexMut<usize> for WindowMut<'a, T> {
    #[inline]
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        assert!(index >= 1, "WindowMut: index must be >= 1");
        assert!(index <= self.len(), "WindowMut: index out of bounds");
        &mut self.inner[self.start + index - 1]
    }
}

impl<'a, T> AsRef<[T]> for WindowMut<'a, T> {
    #[inline]
    fn as_ref(&self) -> &[T] {
        self.as_slice()
    }
}

impl<'a, T> AsMut<[T]> for WindowMut<'a, T> {
    #[inline]
    fn as_mut(&mut self) -> &mut [T] {
        self.as_mut_slice()
    }
}

// ----- Sliding window iterators -----

/// Zero-copy sliding window iterator.
pub struct Windows<'a, T> {
    inner: &'a Vec1<T>,
    start: usize,
    end: usize,
}

impl<'a, T> Windows<'a, T> {
    #[inline]
    pub(crate) fn new(inner: &'a Vec1<T>, window_size: usize) -> Self {
        Windows { inner, start: 1, end: window_size }
    }
}

impl<'a, T> Iterator for Windows<'a, T> {
    type Item = &'a [T];

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.end > self.inner.len() {
            return None;
        }
        let slice = &self.inner.as_slice()[(self.start - 1)..self.end];
        self.start += 1;
        self.end += 1;
        Some(slice)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.inner.len().saturating_sub(self.end - 1);
        (remaining, Some(remaining))
    }
}

impl<'a, T> ExactSizeIterator for Windows<'a, T> {}

/// Mutable sliding window iterator.
pub struct WindowsMut<'a, T> {
    inner: *mut Vec1<T>,
    start: usize,
    end: usize,
    _marker: core::marker::PhantomData<&'a mut T>,
}

impl<'a, T> WindowsMut<'a, T> {
    #[inline]
    pub(crate) fn new(inner: &'a mut Vec1<T>, window_size: usize) -> Self {
        WindowsMut {
            inner: inner as *mut Vec1<T>,
            start: 1,
            end: window_size,
            _marker: core::marker::PhantomData,
        }
    }
}

impl<'a, T> Iterator for WindowsMut<'a, T> {
    type Item = &'a mut [T];

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let len = unsafe { (*self.inner).len() };
        if self.end > len {
            return None;
        }
        let start_idx = self.start - 1;
        let end_idx = self.end;
        let slice = unsafe {
            let ptr = (*self.inner).as_mut_ptr();
            core::slice::from_raw_parts_mut(ptr.add(start_idx), end_idx - start_idx)
        };
        self.start += 1;
        self.end += 1;
        //Some(unsafe { core::mem::transmute(slice) })
        Some(unsafe { core::mem::transmute::<&mut [T], &mut [T]>(slice) })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = unsafe { (*self.inner).len() };
        let remaining = len.saturating_sub(self.end - 1);
        (remaining, Some(remaining))
    }
}

impl<'a, T> ExactSizeIterator for WindowsMut<'a, T> {}

impl<T> Vec1<T> {
    /// Sliding window iterator.
    ///
    /// ```rust
    /// use one_indexed_vec::vec1;
    /// let v = vec1![1, 2, 3, 4, 5];
    /// let s: Vec<i32> = v.windows(3).map(|w| w.iter().sum()).collect();
    /// assert_eq!(s, vec![6, 9, 12]);
    /// ```
    #[inline]
    pub fn windows(&self, window_size: usize) -> Windows<'_, T> {
        assert!(window_size > 0, "windows: window_size must be > 0");
        Windows::new(self, window_size)
    }

    /// Mutable sliding window iterator.
    #[inline]
    pub fn windows_mut(&mut self, window_size: usize) -> WindowsMut<'_, T> {
        assert!(window_size > 0, "windows_mut: window_size must be > 0");
        WindowsMut::new(self, window_size)
    }
}

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

    #[test]
    fn window_basic() {
        let v = vec1![1, 2, 3, 4, 5];
        assert_eq!(v.window(2, 4).as_slice(), &[2, 3, 4]);
    }

    #[test]
    #[should_panic(expected = "window: start must be >= 1")]
    fn window_start_zero_panics() {
        let v = vec1![1, 2, 3];
        let _ = v.window(0, 2);
    }

    #[test]
    fn window_mut_modifies() {
        let mut v = vec1![1, 2, 3, 4, 5];
        {
            let mut w = v.window_mut(2, 4);
            for i in 1..=w.len() {
                w[i] *= 2;
            }
        }
        assert_eq!(v.as_slice(), &[1, 4, 6, 8, 5]);
    }

    #[test]
    fn windows_iterator() {
        let v = vec1![1, 2, 3, 4, 5];
        let mut w = v.windows(3);
        assert_eq!(w.next().unwrap(), &[1, 2, 3]);
        assert_eq!(w.next().unwrap(), &[2, 3, 4]);
        assert_eq!(w.next().unwrap(), &[3, 4, 5]);
        assert!(w.next().is_none());
    }

    #[test]
    fn windows_len() {
        let v = vec1![1, 2, 3, 4];
        assert_eq!(v.windows(2).len(), 3);
    }

    #[test]
    fn windows_mut_basic() {
        let mut v = vec1![1, 2, 3, 4, 5];
        for w in v.windows_mut(1) {
            w[0] *= 2;
        }
        assert_eq!(v.as_slice(), &[2, 4, 6, 8, 10]);
    }
}