Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Vec::flatten (as unstable, of course) #61680

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/liballoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
#![feature(box_syntax)]
#![feature(cfg_target_has_atomic)]
#![feature(coerce_unsized)]
#![cfg_attr(not(bootstrap), feature(const_generics))]
#![feature(dispatch_from_dyn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
Expand Down
79 changes: 79 additions & 0 deletions src/liballoc/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1369,6 +1369,85 @@ impl<T> Vec<T> {
}
}

#[cfg(not(bootstrap))]
impl<T, const N: usize> Vec<[T; N]> {
/// Flatten a `Vec<[T; N]>` into an N-times longer `Vec<T>`.
///
/// This is O(1) and non-allocating.
///
/// # Panics
///
/// If the length of the result would be too large to store in a `usize`,
/// which can only happen if `T` is a zero-sized type.
///
/// # Examples
///
/// ```
/// #![feature(vec_flatten)]
///
/// let v = vec![ [1, 2, 3], [7, 8, 9] ];
/// assert_eq!(v.flatten(), [1, 2, 3, 7, 8, 9]);
///
/// let v = vec![[0; 7]; 13];
/// assert_eq!(v.flatten().len(), 7 * 13);
///
/// let v = vec![[(); 500]; 2_000];
/// assert_eq!(v.flatten().len(), 1_000_000);
///
/// enum Never {}
/// let v: Vec<[Never; 0]> = vec![[], [], []];
/// assert_eq!(v.flatten().len(), 0);
/// ```
///
/// ```should_panic
/// #![feature(vec_flatten)]
///
/// let v = vec![[(); std::usize::MAX]; 2];
/// v.flatten(); // panics for length overflow
/// ```
#[inline]
#[unstable(feature = "vec_flatten", issue = "88888888",
reason = "new API, and needs const generics stabilized first")]
pub fn flatten(mut self) -> Vec<T> {
if N == 0 {
// The allocator-related safety implications of switching pointers
// between ZSTs and other types are non-obvious, so just do the
// simple thing -- this check is compile-time anyway.
return Vec::new();
}

let ptr = self.as_mut_ptr() as *mut T;
let (len, cap) =
if mem::size_of::<T>() == 0 {
// Since ZSTs are limited only by the size of the counters,
// it's completely possible to overflow here. Capacity just
// saturates because it usually comes in as `usize::MAX` so
// checking the multiplication would make it almost always panic.
(
self.len().checked_mul(N).expect("length overflow"),
self.capacity().saturating_mul(N),
)
} else {
// But for types with an actual size these multiplications
// cannot overflow as the memory is allocated in self, so don't
// codegen a reference to panic machinery.
(self.len() * N, self.capacity() * N)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
(self.len() * N, self.capacity() * N)
(self.len() * N, self.capacity() * N)

};
mem::forget(self);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's kind of unfortunate that we need to do a forget here, but I can't really think of what the alternative would be. Converting to a box first would shrink the capacity, which isn't really desired.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could have into_raw_parts(self) -> (*mut T, usize, usize), the reverse of Vec::from_raw_parts. It may be a slight footgun remembering which usize is the length and capacity though.

Copy link
Contributor

@clarfonthey clarfonthey Jun 11, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, in hindsight it would have been much better for from_raw_parts to take *mut [T] and usize, rather than *mut T, and two usizes. Unfortunately, we can't change this now.


// SAFETY:
// - The pointer came from the same allocator with which it's being used.
// - The layout of the allocation hasn't changed, because the alignment
// of an array matches that of its elements and we increased the length
// by the appropriate amount to counteract the decrease in type size.
// - Length is less than or equal to capacity because we increased both
// proportionately or set capacity to the largest possible value.
unsafe {
Vec::from_raw_parts(ptr, len, cap)
}
}
}

impl<T: Clone> Vec<T> {
/// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
///
Expand Down