Skip to content

Commit

Permalink
Auto merge of #48 - SergioBenitez:master, r=emilio
Browse files Browse the repository at this point in the history
Add from_vec method for efficient creation from a Vec.

I also bumped the version to 0.3.3 for easy publishing.

<!-- Reviewable:start -->
---
This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/rust-smallvec/48)
<!-- Reviewable:end -->
  • Loading branch information
bors-servo authored Mar 29, 2017
2 parents e3e9cc9 + 0bf0141 commit 46ef708
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "smallvec"
version = "0.3.2"
version = "0.3.3"
authors = ["Simon Sapin <[email protected]>"]
license = "MPL-2.0"
repository = "https://github.com/servo/rust-smallvec"
Expand Down
58 changes: 58 additions & 0 deletions lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,31 @@ impl<A: Array> SmallVec<A> {
}
}

/// Construct a new `SmallVec` from a `Vec<A::Item>` 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<A::Item>) -> SmallVec<A> {
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
Expand Down Expand Up @@ -1363,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);
}
}

0 comments on commit 46ef708

Please sign in to comment.