From 5bf0e513b9bea5d332dcd6d4dfb62620e05e489c Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Wed, 29 Mar 2017 01:36:34 -0700 Subject: [PATCH 1/3] Add from_vec method for efficient creation from a Vec. --- lib.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/lib.rs b/lib.rs index e9ba620..9d03ee1 100644 --- a/lib.rs +++ b/lib.rs @@ -207,6 +207,31 @@ impl SmallVec { } } + /// Construct a new `SmallVec` from a `Vec` without copying + /// elements. + /// + /// ```rust + /// use smallvec::SmallVec; + /// + /// let vec = vec![1, 2, 3, 4, 5]; + /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec); + /// + /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); + /// ``` + #[inline] + pub fn from_vec(mut vec: Vec) -> SmallVec { + let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len()); + mem::forget(vec); + + SmallVec { + len: len, + data: SmallVecData::Heap { + ptr: ptr, + capacity: cap + } + } + } + /// Sets the length of a vector. /// /// This will explicitly set the size of the vector, without actually From bd892e83fdb36bab65923880e320008a0f1a1152 Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Wed, 29 Mar 2017 01:37:00 -0700 Subject: [PATCH 2/3] Bump to 0.3.3. --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index e1bbd05..2a64c04 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "smallvec" -version = "0.3.2" +version = "0.3.3" authors = ["Simon Sapin "] license = "MPL-2.0" repository = "https://github.com/servo/rust-smallvec" From 0bf014131b4e7af8df5b256f58cda3ded51f1c42 Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Wed, 29 Mar 2017 03:14:25 -0700 Subject: [PATCH 3/3] Add tests for from_vec. --- lib.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/lib.rs b/lib.rs index 9d03ee1..f03108a 100644 --- a/lib.rs +++ b/lib.rs @@ -1388,4 +1388,37 @@ pub mod tests { let vec = SmallVec::<[u8; 2]>::from_iter(0..3); assert_eq!(vec.into_vec(), vec![0, 1, 2]); } + + #[test] + fn test_from_vec() { + let vec = vec![]; + let small_vec: SmallVec<[u8; 3]> = SmallVec::from_vec(vec); + assert_eq!(&*small_vec, &[]); + drop(small_vec); + + let vec = vec![]; + let small_vec: SmallVec<[u8; 1]> = SmallVec::from_vec(vec); + assert_eq!(&*small_vec, &[]); + drop(small_vec); + + let vec = vec![1]; + let small_vec: SmallVec<[u8; 3]> = SmallVec::from_vec(vec); + assert_eq!(&*small_vec, &[1]); + drop(small_vec); + + let vec = vec![1, 2, 3]; + let small_vec: SmallVec<[u8; 3]> = SmallVec::from_vec(vec); + assert_eq!(&*small_vec, &[1, 2, 3]); + drop(small_vec); + + let vec = vec![1, 2, 3, 4, 5]; + let small_vec: SmallVec<[u8; 3]> = SmallVec::from_vec(vec); + assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); + drop(small_vec); + + let vec = vec![1, 2, 3, 4, 5]; + let small_vec: SmallVec<[u8; 1]> = SmallVec::from_vec(vec); + assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); + drop(small_vec); + } }