From 5c50c4dbc77707ce1f957c46d15bb7633a52fa63 Mon Sep 17 00:00:00 2001 From: root Date: Mon, 22 Jun 2015 16:33:22 +0200 Subject: [PATCH] Add method .into_inner() --- src/lib.rs | 19 +++++++++++++++++++ tests/tests.rs | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 9780e89..c6e54ca 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -323,6 +323,25 @@ impl ArrayVec { } } } + + /// 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 { + if self.len() < self.capacity() { + Err(self) + } else { + unsafe { + let array = ptr::read(&*self.xs); + mem::forget(self); + Ok(array) + } + } + } } impl Deref for ArrayVec { diff --git a/tests/tests.rs b/tests/tests.rs index d58b527..c2cf272 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -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]); +}