From c6b259fa3f561e70eb996994cf4f0d1b1e2c6edd Mon Sep 17 00:00:00 2001 From: Mikolaj Wielgus Date: Tue, 3 Nov 2026 21:42:01 +0100 Subject: [PATCH] Implement `Index` and `IndexMut` for `Deque` This continues f70f19c7946c0d3dd8ac3c121c03975f6e056274. This is consistent with standard library's `VecDeque`, which also has `Index` and `IndexMut` implemented. --- CHANGELOG.md | 2 +- src/deque.rs | 28 +++++++++++++++++++++++++++- src/vec/mod.rs | 4 ++-- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f710f83b05..c913283227 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Limited max size of `IndexMap` to u16::MAX + 1. The implementation for sizes higher than u16::MAX were unsound anyway. - Added `shift_remove`, `shift_remove_entry` and `shift_remove_full` to `IndexMap` and `IndexSet`. -- Implemented `Index` and `IndexMut` for `Vec`. +- Implemented `Index` and `IndexMut` for `Vec`, `Deque`. ## [v0.9.3] 2025-04-15 diff --git a/src/deque.rs b/src/deque.rs index a1e4ddf9dd..d2b0aba7ee 100644 --- a/src/deque.rs +++ b/src/deque.rs @@ -43,7 +43,7 @@ use core::{ iter::FusedIterator, marker::PhantomData, mem::{ManuallyDrop, MaybeUninit}, - ptr, slice, + ops, ptr, slice, }; #[cfg(feature = "zeroize")] @@ -1364,6 +1364,22 @@ where impl Eq for Deque {} +impl + ?Sized> ops::Index for DequeInner { + type Output = T; + + #[inline] + fn index(&self, index: usize) -> &Self::Output { + self.get(index).expect("out of bounds access") + } +} + +impl + ?Sized> ops::IndexMut for DequeInner { + #[inline] + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + self.get_mut(index).expect("out of bounds access") + } +} + impl TryFrom<[T; NS]> for Deque { /// Converts a `[T; NS]` into a `Deque`. /// @@ -1871,6 +1887,16 @@ mod tests { assert_eq!(q.pop_front(), None); } + #[test] + fn index() { + let mut q = Deque::<_, 4>::try_from([1, 2, 3]).unwrap(); + assert_eq!(q[1], 2); + q[1] = 9; + assert_eq!(q[1], 9); + q[2] += 1; + assert_eq!(q[2], 4); + } + #[test] fn swap() { let mut q: Deque = Deque::new(); diff --git a/src/vec/mod.rs b/src/vec/mod.rs index 1a6a804ca8..6846203446 100644 --- a/src/vec/mod.rs +++ b/src/vec/mod.rs @@ -1943,14 +1943,14 @@ mod tests { increment(&mut v, 1); assert_eq!(v[1], 10); - fn get(container: &mut C, index: usize) -> &>::Output + fn get(container: &C, index: usize) -> &>::Output where C: std::ops::Index, { &container[index] } - assert_eq!(*get(&mut v, 1), 10); + assert_eq!(*get(&v, 1), 10); } #[test]