use core::fmt;
#[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 {
#[inline]
pub const fn new(index: usize) -> Self {
Self(index)
}
#[inline]
pub const fn from_one_based(index: usize) -> Self {
Self(index)
}
#[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"),
}
}
#[inline]
pub const fn try_from_zero_based(index0: usize) -> Option<Self> {
match index0.checked_add(1) {
Some(v) => Some(Self(v)),
_ => Option::None,
}
}
#[inline]
pub const fn get(self) -> usize {
self.0
}
#[inline]
pub const fn is_valid(self) -> bool {
self.0 >= 1
}
#[inline]
pub const fn to_zero_based(self) -> Option<usize> {
self.0.checked_sub(1)
}
#[inline]
pub const fn to_index0(self) -> Option<usize> {
self.to_zero_based()
}
#[inline]
pub const fn saturating_add(self, rhs: usize) -> Self {
Self(self.0.saturating_add(rhs))
}
#[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);
}
}