Add method .into_inner()

This commit is contained in:
root
2015-06-22 16:33:22 +02:00
parent 66d5d9a12e
commit 5c50c4dbc7
2 changed files with 59 additions and 0 deletions
+19
View File
@@ -323,6 +323,25 @@ impl<A: Array> ArrayVec<A> {
}
}
}
/// Return the inner fixed size array, if it is full to its capacity.
///
/// Return an **Ok** value with the array if length equals capacity,
/// return an **Err** with self otherwise.
///
/// **Note:** This function may incur unproportionally large overhead
/// to move the array out, its performance is not optimal.
pub fn into_inner(self) -> Result<A, Self> {
if self.len() < self.capacity() {
Err(self)
} else {
unsafe {
let array = ptr::read(&*self.xs);
mem::forget(self);
Ok(array)
}
}
}
}
impl<A: Array> Deref for ArrayVec<A> {
+40
View File
@@ -83,6 +83,21 @@ fn test_drop() {
}
assert_eq!(flag.get(), 4);
// test into_inner
flag.set(0);
{
let mut array = ArrayVec::<[_; 3]>::new();
array.push(Bump(flag));
array.push(Bump(flag));
array.push(Bump(flag));
let inner = array.into_inner();
assert!(inner.is_ok());
assert_eq!(flag.get(), 0);
drop(inner);
assert_eq!(flag.get(), 3);
}
}
#[test]
@@ -178,3 +193,28 @@ fn test_in_option() {
}
assert!(v.is_some());
}
#[test]
fn test_into_inner_1() {
let mut v = ArrayVec::from([1, 2]);
v.pop();
let u = v.clone();
assert_eq!(v.into_inner(), Err(u));
}
#[test]
fn test_into_inner_2() {
let mut v = ArrayVec::<[String; 4]>::new();
v.push("a".into());
v.push("b".into());
v.push("c".into());
v.push("d".into());
assert_eq!(v.into_inner().unwrap(), ["a", "b", "c", "d"]);
}
#[test]
fn test_into_inner_3_() {
let mut v = ArrayVec::<[i32; 4]>::new();
v.extend(1..);
assert_eq!(v.into_inner().unwrap(), [1, 2, 3, 4]);
}