From d86e6d26c091b22e0ea544904771959c31433258 Mon Sep 17 00:00:00 2001 From: Mikolaj Wielgus Date: Sat, 26 Sep 2026 02:27:19 +0200 Subject: [PATCH] Implement `Index` and `IndexMut` traits It's useful to have `Index` and `IndexMut` traits implemented if you want to have code that is generic over indexable containers, like this: ``` fn increment(container: &mut C, index: usize) where C: std::ops::IndexMut, C::Output: std::ops::AddAssign, { container[index] += 1; } ``` Having these traits is also consistent with `Vec`, which also implements them. I have added two tests to test these traits. --- src/references.rs | 23 +++++++++++++++++++++-- tests/main.rs | 13 +++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/references.rs b/src/references.rs index 0582ea12..06b4a381 100644 --- a/src/references.rs +++ b/src/references.rs @@ -10,8 +10,11 @@ use { }, ops::{ Deref, - DerefMut - } + DerefMut, + Index, + IndexMut + }, + slice::SliceIndex } }; @@ -55,3 +58,19 @@ impl DerefMut for SmallVec { self.as_mut_slice() } } + +impl> Index for SmallVec { + type Output = >::Output; + + #[inline] + fn index(&self, index: I) -> &Self::Output { + &self.deref()[index] + } +} + +impl> IndexMut for SmallVec { + #[inline] + fn index_mut(&mut self, index: I) -> &mut Self::Output { + &mut self.deref_mut()[index] + } +} diff --git a/tests/main.rs b/tests/main.rs index 0c230d87..d58fcc02 100644 --- a/tests/main.rs +++ b/tests/main.rs @@ -629,6 +629,19 @@ fn borrow_mut() { assert_eq!(a.borrow_mut(), [1, 4, 3]); } +#[test] +fn index() { + let a = SmallVec::::from(&[1, 2, 3][..]); + assert_eq!(a[1], 2); +} + +#[test] +fn index_mut() { + let mut a = SmallVec::::from(&[1, 2, 3][..]); + a[1] = 22; + assert_eq!(a[1], 22); +} + #[test] fn from() { assert_eq!(&SmallVec::::from(&[1][..])[..], [1]);