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
//! Type-safe 1-based position index.

use core::fmt;

/// A 1-based position index.
///
/// Internally stores a position value starting at `1`.
/// `Index1::new(1)` refers to the first element.
///
/// # Examples
///
/// ```rust
/// use one_indexed_vec::Index1;
///
/// let i = Index1::new(3);
/// assert_eq!(i.get(), 3);
/// assert_eq!(i.to_zero_based(), Some(2));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Index1(usize);

impl Index1 {
    /// Constructs from a 1-based position.
    #[inline]
    pub const fn new(index: usize) -> Self {
        Self(index)
    }

    /// Alias for [`Self::new`].
    #[inline]
    pub const fn from_one_based(index: usize) -> Self {
        Self(index)
    }

    /// Constructs from a 0-based subscript (`0` → position `1`).
    ///
    /// # Panics
    ///
    /// Panics on overflow (`index0 == usize::MAX`).
    #[inline]
    pub const fn from_zero_based(index0: usize) -> Self {
        match index0.checked_add(1) {
            Some(v) => Self(v),
            _ => panic!("Index1::from_zero_based: overflow"),
        }
    }

    /// Tries to construct from a 0-based subscript.
    #[inline]
    pub const fn try_from_zero_based(index0: usize) -> Option<Self> {
        match index0.checked_add(1) {
            Some(v) => Some(Self(v)),
            _ => Option::None,
        }
    }

    /// Returns the 1-based position value.
    #[inline]
    pub const fn get(self) -> usize {
        self.0
    }

    /// Returns `true` when the position is valid (`>= 1`).
    #[inline]
    pub const fn is_valid(self) -> bool {
        self.0 >= 1
    }

    /// Converts to the underlying 0-based subscript.
    #[inline]
    pub const fn to_zero_based(self) -> Option<usize> {
        self.0.checked_sub(1)
    }

    /// Alias for [`Self::to_zero_based`].
    #[inline]
    pub const fn to_index0(self) -> Option<usize> {
        self.to_zero_based()
    }

    /// Saturating addition.
    #[inline]
    pub const fn saturating_add(self, rhs: usize) -> Self {
        Self(self.0.saturating_add(rhs))
    }

    /// Saturating subtraction (lower bound = 1).
    ///
    /// Unlike `usize::saturating_sub`, this never returns `0`; if the result
    /// would be `0`, it returns `1`.
    #[inline]
    pub const fn saturating_sub(self, rhs: usize) -> Self {
        let v = self.0.saturating_sub(rhs);
        if v < 1 { Self(1) } else { Self(v) }
    }
}

impl fmt::Display for Index1 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<Index1> for usize {
    #[inline]
    fn from(i: Index1) -> Self {
        i.0
    }
}

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

    #[test]
    fn new_and_get_roundtrip() {
        let i = Index1::new(5);
        assert_eq!(i.get(), 5);
        assert_eq!(Index1::from_one_based(5), i);
    }

    #[test]
    fn to_zero_based_conversion() {
        assert_eq!(Index1::new(1).to_zero_based(), Some(0));
        assert_eq!(Index1::new(3).to_zero_based(), Some(2));
        assert_eq!(Index1::new(0).to_zero_based(), None);
    }

    #[test]
    fn from_zero_based_basic() {
        assert_eq!(Index1::from_zero_based(0), Index1::new(1));
        assert_eq!(Index1::from_zero_based(2), Index1::new(3));
    }

    #[test]
    fn try_from_zero_based_basic() {
        assert_eq!(Index1::try_from_zero_based(0), Some(Index1::new(1)));
        assert_eq!(Index1::try_from_zero_based(usize::MAX), None);
    }

    #[test]
    fn is_valid_check() {
        assert!(Index1::new(1).is_valid());
        assert!(!Index1::new(0).is_valid());
    }

    #[test]
    fn saturating_arithmetic() {
        assert_eq!(Index1::new(3).saturating_add(2).get(), 5);
        assert_eq!(Index1::new(3).saturating_sub(2).get(), 1);
        assert_eq!(Index1::new(1).saturating_sub(10).get(), 1);
    }

    #[test]
    fn display_and_into_usize() {
        assert_eq!(Index1::new(42).to_string(), "42");
        let n: usize = Index1::new(7).into();
        assert_eq!(n, 7);
    }
}