1
Fork 0

Make mut_last return Option instead of failing on empty vector (and add a test for mut_last)

This commit is contained in:
Nathaniel Herman 2014-01-26 11:24:34 -05:00
parent 339603426e
commit d9fadbc04f
3 changed files with 17 additions and 7 deletions

View file

@ -662,7 +662,7 @@ impl<'a> CleanupHelperMethods<'a> for FunctionContext<'a> {
// Check if a landing pad block exists; if not, create one.
{
let mut scopes = self.scopes.borrow_mut();
let last_scope = scopes.get().mut_last();
let last_scope = scopes.get().mut_last().unwrap();
match last_scope.cached_landing_pad {
Some(llbb) => { return llbb; }
None => {

View file

@ -2031,7 +2031,7 @@ pub trait MutableVector<'a, T> {
fn mut_iter(self) -> MutItems<'a, T>;
/// Returns a mutable pointer to the last item in the vector.
fn mut_last(self) -> &'a mut T;
fn mut_last(self) -> Option<&'a mut T>;
/// Returns a reversed iterator that allows modifying each value
fn mut_rev_iter(self) -> RevMutItems<'a, T>;
@ -2298,10 +2298,10 @@ impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
}
#[inline]
fn mut_last(self) -> &'a mut T {
fn mut_last(self) -> Option<&'a mut T> {
let len = self.len();
if len == 0 { fail!("mut_last: empty vector") }
&mut self[len - 1]
if len == 0 { return None; }
Some(&mut self[len - 1])
}
#[inline]
@ -4305,6 +4305,16 @@ mod tests {
let mut y: &mut [int] = [];
assert!(y.mut_pop_ref().is_none());
}
#[test]
fn test_mut_last() {
let mut x = [1, 2, 3, 4, 5];
let h = x.mut_last();
assert_eq!(*h.unwrap(), 5);
let mut y: &mut [int] = [];
assert!(y.mut_last().is_none());
}
}
#[cfg(test)]

View file

@ -62,10 +62,10 @@ impl<T> OptVec<T> {
}
}
pub fn mut_last<'a>(&'a mut self) -> &'a mut T {
pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
match *self {
Vec(ref mut v) => v.mut_last(),
Empty => fail!("mut_last on empty opt_vec")
Empty => None
}
}