Skip to content

Commit 006440a

Browse files
authored
Rollup merge of rust-lang#61447 - scottmcm:vec-vecdeque, r=sfackler
Add some Vec <-> VecDeque documentation These are more than just `.into_iter().collect()`, so talk about some of their nuances. For VecDeque -> Vec I'm trying to intentionally not write a guarantee for people making their own `Vec`s, since the rules are more complicated than I think we want to commit to forever. The "Vec -> VecDeque doesn't reallocate" guarantee seems reasonable, though. (And I'm intentionally ambiguous about when it's O(1) instead of O(n).)
2 parents 0dc9e9c + 0150448 commit 006440a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/liballoc/collections/vec_deque.rs

+31
Original file line numberDiff line numberDiff line change
@@ -2709,6 +2709,11 @@ impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
27092709

27102710
#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
27112711
impl<T> From<Vec<T>> for VecDeque<T> {
2712+
/// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
2713+
///
2714+
/// This avoids reallocating where possible, but the conditions for that are
2715+
/// strict, and subject to change, and so shouldn't be relied upon unless the
2716+
/// `Vec<T>` came from `From<VecDeque<T>>` and hasn't been reallocated.
27122717
fn from(mut other: Vec<T>) -> Self {
27132718
unsafe {
27142719
let other_buf = other.as_mut_ptr();
@@ -2735,6 +2740,32 @@ impl<T> From<Vec<T>> for VecDeque<T> {
27352740

27362741
#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
27372742
impl<T> From<VecDeque<T>> for Vec<T> {
2743+
/// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
2744+
///
2745+
/// This never needs to re-allocate, but does need to do O(n) data movement if
2746+
/// the circular buffer doesn't happen to be at the beginning of the allocation.
2747+
///
2748+
/// # Examples
2749+
///
2750+
/// ```
2751+
/// use std::collections::VecDeque;
2752+
///
2753+
/// // This one is O(1).
2754+
/// let deque: VecDeque<_> = (1..5).collect();
2755+
/// let ptr = deque.as_slices().0.as_ptr();
2756+
/// let vec = Vec::from(deque);
2757+
/// assert_eq!(vec, [1, 2, 3, 4]);
2758+
/// assert_eq!(vec.as_ptr(), ptr);
2759+
///
2760+
/// // This one needs data rearranging.
2761+
/// let mut deque: VecDeque<_> = (1..5).collect();
2762+
/// deque.push_front(9);
2763+
/// deque.push_front(8);
2764+
/// let ptr = deque.as_slices().1.as_ptr();
2765+
/// let vec = Vec::from(deque);
2766+
/// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
2767+
/// assert_eq!(vec.as_ptr(), ptr);
2768+
/// ```
27382769
fn from(other: VecDeque<T>) -> Self {
27392770
unsafe {
27402771
let buf = other.buf.ptr();

0 commit comments

Comments
 (0)