Skip to content

Commit 5bf0e51

Browse files
committed
Add from_vec method for efficient creation from a Vec.
1 parent e3e9cc9 commit 5bf0e51

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

lib.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,31 @@ impl<A: Array> SmallVec<A> {
207207
}
208208
}
209209

210+
/// Construct a new `SmallVec` from a `Vec<A::Item>` without copying
211+
/// elements.
212+
///
213+
/// ```rust
214+
/// use smallvec::SmallVec;
215+
///
216+
/// let vec = vec![1, 2, 3, 4, 5];
217+
/// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec);
218+
///
219+
/// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
220+
/// ```
221+
#[inline]
222+
pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
223+
let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
224+
mem::forget(vec);
225+
226+
SmallVec {
227+
len: len,
228+
data: SmallVecData::Heap {
229+
ptr: ptr,
230+
capacity: cap
231+
}
232+
}
233+
}
234+
210235
/// Sets the length of a vector.
211236
///
212237
/// This will explicitly set the size of the vector, without actually

0 commit comments

Comments
 (0)