Add get_opt to std::vec
This commit is contained in:
parent
9883a6250b
commit
21b24e148b
@ -840,6 +840,7 @@ pub trait ImmutableVector<'self, T> {
|
||||
fn window_iter(self, size: uint) -> WindowIter<'self, T>;
|
||||
fn chunk_iter(self, size: uint) -> ChunkIter<'self, T>;
|
||||
|
||||
fn get_opt(&self, index: uint) -> Option<&'self T>;
|
||||
fn head(&self) -> &'self T;
|
||||
fn head_opt(&self) -> Option<&'self T>;
|
||||
fn tail(&self) -> &'self [T];
|
||||
@ -1019,6 +1020,13 @@ impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
|
||||
ChunkIter { v: self, size: size }
|
||||
}
|
||||
|
||||
/// Returns the element of a vector at the given index, or `None` if the
|
||||
/// index is out of bounds
|
||||
#[inline]
|
||||
fn get_opt(&self, index: uint) -> Option<&'self T> {
|
||||
if index < self.len() { Some(&self[index]) } else { None }
|
||||
}
|
||||
|
||||
/// Returns the first element of a vector, failing if the vector is empty.
|
||||
#[inline]
|
||||
fn head(&self) -> &'self T {
|
||||
@ -2574,6 +2582,16 @@ mod tests {
|
||||
assert_eq!(v2.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_opt() {
|
||||
let mut a = ~[11];
|
||||
assert_eq!(a.get_opt(1), None);
|
||||
a = ~[11, 12];
|
||||
assert_eq!(a.get_opt(1).unwrap(), &12);
|
||||
a = ~[11, 12, 13];
|
||||
assert_eq!(a.get_opt(1).unwrap(), &12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head() {
|
||||
let mut a = ~[11];
|
||||
|
Loading…
x
Reference in New Issue
Block a user