Skip to content

Implement Index/IndexMut for [T] #18698

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

Merged
merged 1 commit into from
Nov 7, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/libcore/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ shr_impl!(uint u8 u16 u32 u64 int i8 i16 i32 i64)
* ```
*/
#[lang="index"]
pub trait Index<Index, Sized? Result> {
pub trait Index<Index, Sized? Result> for Sized? {
/// The method for the indexing (`Foo[Bar]`) operation
fn index<'a>(&'a self, index: &Index) -> &'a Result;
}
Expand Down Expand Up @@ -669,7 +669,7 @@ pub trait Index<Index, Sized? Result> {
* ```
*/
#[lang="index_mut"]
pub trait IndexMut<Index, Result> {
pub trait IndexMut<Index, Result> for Sized? {
/// The method for the indexing (`Foo[Bar]`) operation
fn index_mut<'a>(&'a mut self, index: &Index) -> &'a mut Result;
}
Expand Down
17 changes: 16 additions & 1 deletion src/libcore/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,6 @@ pub trait SlicePrelude<T> for Sized? {
#[inline]
#[experimental = "not triaged yet"]
fn is_empty(&self) -> bool { self.len() == 0 }

/// Returns a mutable reference to the element at the given index,
/// or `None` if the index is out of bounds
#[unstable = "waiting on final error conventions"]
Expand Down Expand Up @@ -698,6 +697,22 @@ impl<T> SlicePrelude<T> for [T] {
}
}

impl<T> ops::Index<uint, T> for [T] {
fn index(&self, &index: &uint) -> &T {
assert!(index < self.len());

unsafe { mem::transmute(self.repr().data.offset(index as int)) }
}
}

impl<T> ops::IndexMut<uint, T> for [T] {
fn index_mut(&mut self, &index: &uint) -> &mut T {
assert!(index < self.len());

unsafe { mem::transmute(self.repr().data.offset(index as int)) }
}
}

impl<T> ops::Slice<uint, [T]> for [T] {
#[inline]
fn as_slice_<'a>(&'a self) -> &'a [T] {
Expand Down