Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Index and IndexMut traits for ArrayVec #191

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 26 additions & 6 deletions src/array_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::convert::TryFrom;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::mem::MaybeUninit;
use std::ops::{Deref, DerefMut};
use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::ptr;
use std::slice;
use std::str;
Expand Down Expand Up @@ -261,7 +261,7 @@ impl<const CAP: usize> ArrayString<CAP>
///
/// ```
/// use arrayvec::ArrayString;
///
///
/// let mut s = ArrayString::<3>::from("foo").unwrap();
///
/// assert_eq!(s.pop(), Some('o'));
Expand Down Expand Up @@ -301,7 +301,7 @@ impl<const CAP: usize> ArrayString<CAP>
pub fn truncate(&mut self, new_len: usize) {
if new_len <= self.len() {
assert!(self.is_char_boundary(new_len));
unsafe {
unsafe {
// In libstd truncate is called on the underlying vector,
// which in turns drops each element.
// As we know we don't have to worry about Drop,
Expand All @@ -321,7 +321,7 @@ impl<const CAP: usize> ArrayString<CAP>
///
/// ```
/// use arrayvec::ArrayString;
///
///
/// let mut s = ArrayString::<3>::from("foo").unwrap();
///
/// assert_eq!(s.remove(0), 'f');
Expand Down Expand Up @@ -429,7 +429,7 @@ impl<const CAP: usize> PartialEq<ArrayString<CAP>> for str
}
}

impl<const CAP: usize> Eq for ArrayString<CAP>
impl<const CAP: usize> Eq for ArrayString<CAP>
{ }

impl<const CAP: usize> Hash for ArrayString<CAP>
Expand All @@ -449,6 +449,26 @@ impl<const CAP: usize> AsRef<str> for ArrayString<CAP>
fn as_ref(&self) -> &str { self }
}

impl<I, const CAP: usize> Index<I> for ArrayString<CAP>
where
str: Index<I>,
{
type Output = <str as Index<I>>::Output;

fn index(&self, index: I) -> &Self::Output {
&(**self)[index]
}
}

impl<I, const CAP: usize> IndexMut<I> for ArrayString<CAP>
where
str: IndexMut<I>,
{
fn index_mut(&mut self, index: I) -> &mut Self::Output {
&mut (**self)[index]
}
}

impl<const CAP: usize> fmt::Debug for ArrayString<CAP>
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) }
Expand Down Expand Up @@ -545,7 +565,7 @@ impl<const CAP: usize> Serialize for ArrayString<CAP>

#[cfg(feature="serde")]
/// Requires crate feature `"serde"`
impl<'de, const CAP: usize> Deserialize<'de> for ArrayString<CAP>
impl<'de, const CAP: usize> Deserialize<'de> for ArrayString<CAP>
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
Expand Down
32 changes: 26 additions & 6 deletions src/arrayvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use std::cmp;
use std::iter;
use std::mem;
use std::ops::{Bound, Deref, DerefMut, RangeBounds};
use std::ops::{Bound, Deref, DerefMut, Index, IndexMut, RangeBounds};
use std::ptr;
use std::slice;

Expand Down Expand Up @@ -373,7 +373,7 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {

/// Remove the element at `index` and swap the last element into its place.
///
/// This is a checked version of `.swap_remove`.
/// This is a checked version of `.swap_remove`.
/// This operation is O(1).
///
/// Return `Some(` *element* `)` if the index is in bounds, else `None`.
Expand Down Expand Up @@ -989,11 +989,11 @@ impl<T, Data, F> Drop for ScopeExitGuard<T, Data, F>


/// Extend the `ArrayVec` with an iterator.
///
///
/// ***Panics*** if extending the vector exceeds its capacity.
impl<T, const CAP: usize> Extend<T> for ArrayVec<T, CAP> {
/// Extend the `ArrayVec` with an iterator.
///
///
/// ***Panics*** if extending the vector exceeds its capacity.
fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
unsafe {
Expand All @@ -1002,6 +1002,26 @@ impl<T, const CAP: usize> Extend<T> for ArrayVec<T, CAP> {
}
}

impl<I, T, const CAP: usize> Index<I> for ArrayVec<T, CAP>
where
[T]: Index<I>,
{
type Output = <[T] as Index<I>>::Output;

fn index(&self, index: I) -> &Self::Output {
&(**self)[index]
}
}

impl<I, T, const CAP: usize> IndexMut<I> for ArrayVec<T, CAP>
where
[T]: IndexMut<I>,
{
fn index_mut(&mut self, index: I) -> &mut Self::Output {
&mut (**self)[index]
}
}

#[inline(never)]
#[cold]
fn extend_panic() {
Expand Down Expand Up @@ -1072,11 +1092,11 @@ unsafe fn raw_ptr_add<T>(ptr: *mut T, offset: usize) -> *mut T {
}

/// Create an `ArrayVec` from an iterator.
///
///
/// ***Panics*** if the number of elements in the iterator exceeds the arrayvec's capacity.
impl<T, const CAP: usize> iter::FromIterator<T> for ArrayVec<T, CAP> {
/// Create an `ArrayVec` from an iterator.
///
///
/// ***Panics*** if the number of elements in the iterator exceeds the arrayvec's capacity.
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Self {
let mut array = ArrayVec::new();
Expand Down
80 changes: 80 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,46 @@ fn array_clone_from() {
assert_eq!(&t, &reference[..]);
}

#[test]
fn array_index_usize() {
let v = ArrayVec::from([1, 2, 3]);
assert_eq!(v[1], 2);
}

#[should_panic(expected="index out of bounds: the len is 3 but the index is 3")]
#[test]
fn array_index_usize_out_of_bounds() {
let v = ArrayVec::from([1, 2, 3]);
let _ = v[3]; // out of bounds
}

#[test]
fn array_index_range() {
let v = ArrayVec::from([1, 2, 3]);
assert_eq!(&v[1..3], [2, 3].as_ref());
}

#[should_panic(expected="range end index 4 out of range for slice of length 3")]
#[test]
fn array_index_range_out_of_bounds() {
let v = ArrayVec::from([1, 2, 3]);
let _ = v[1..4]; // out of bounds
}

#[test]
fn array_indexmut_usize() {
let mut v = ArrayVec::from([1, 2, 3]);
v[1] = 0;
assert_eq!(v, ArrayVec::from([1, 0, 3]));
}

#[should_panic(expected="index out of bounds: the len is 3 but the index is 3")]
#[test]
fn array_indexmut_usize_out_of_bounds() {
let mut v = ArrayVec::from([1, 2, 3]);
v[3] = 0; // out of bounds
}

#[cfg(feature="std")]
#[test]
fn test_string() {
Expand Down Expand Up @@ -604,6 +644,46 @@ fn test_string_push() {
assert!(s.try_push('x').is_err());
}

#[test]
fn string_index() {
let v = ArrayString::<9>::from("abcαβγ").unwrap();
assert_eq!(&v[1..5], "bcα");
}

#[should_panic(expected="byte index 4 is out of bounds of `abc`")]
#[test]
fn string_index_out_of_bounds() {
let v = ArrayString::<3>::from("abc").unwrap();
let _ = v[1..4]; // out of bounds
}

#[should_panic(expected="byte index 1 is not a char boundary; it is inside 'α' (bytes 0..2) of `αβγabc`")]
#[test]
fn string_index_char_boundary_error() {
let v = ArrayString::<9>::from("αβγabc").unwrap();
let _ = v[1..4]; // not at char boundary
}

#[test]
fn string_indexmut() {
let mut v = ArrayString::<9>::from("αβγabc").unwrap();
v[4..7].make_ascii_uppercase();
assert_eq!(&*v, "αβγAbc");
}

#[should_panic(expected="byte index 4 is out of bounds of `abc`")]
#[test]
fn string_indexmut_out_of_bounds() {
let mut v = ArrayString::<3>::from("abc").unwrap();
v[2..4].make_ascii_uppercase(); // out of bounds
}

#[should_panic(expected="byte index 1 is not a char boundary; it is inside 'α' (bytes 0..2) of `αβγabc`")]
#[test]
fn string_indexmut_char_boundary_error() {
let mut v = ArrayString::<9>::from("αβγabc").unwrap();
v[1..4].make_ascii_uppercase(); // not at char boundary
}

#[test]
fn test_insert_at_length() {
Expand Down