Skip to content

Commit

Permalink
Index and IndexMut traits
Browse files Browse the repository at this point in the history
  • Loading branch information
amunra committed Sep 25, 2024
1 parent ff1d658 commit 531b229
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use alloc::alloc::Allocator;
use alloc::collections::TryReserveError;
use alloc::vec::Vec as InnerVec;
use core::fmt::Debug;
use core::ops::{Index, IndexMut};
use core::slice::SliceIndex;

pub struct Vec<T, A: Allocator> {
inner: InnerVec<T, A>,
Expand Down Expand Up @@ -71,6 +73,22 @@ impl<T, A: Allocator> Vec<T, A> {
}
}

impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
type Output = I::Output;

#[inline]
fn index(&self, index: I) -> &Self::Output {
self.inner.index(index)
}
}

impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
#[inline]
fn index_mut(&mut self, index: I) -> &mut Self::Output {
self.inner.index_mut(index)
}
}

impl<T: Debug, A: Allocator> Debug for Vec<T, A> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.inner.fmt(f)
Expand Down Expand Up @@ -255,4 +273,18 @@ mod tests {
assert_eq!(*ptr.add(5), 'f');
}
}

#[test]
fn test_index() {
let wma = WatermarkAllocator::new(32);
let mut vec = Vec::new_in(wma);
vec.try_push(1).unwrap();
vec.try_push(2).unwrap();
vec.try_push(3).unwrap();
vec.try_push(4).unwrap();
assert_eq!(vec[0], 1);
assert_eq!(vec[1], 2);
assert_eq!(vec[2], 3);
assert_eq!(vec[3], 4);
}
}

0 comments on commit 531b229

Please sign in to comment.