Skip to content

Commit f9b9e5d

Browse files
authored
Rollup merge of rust-lang#79451 - usbalbin:array_zip, r=m-ou-se
Added [T; N]::zip() This is my first PR to rust so I hope I have done everything right, or at least close :) --- This is PR adds the array method `[T; N]::zip()` which, in my mind, is a natural extension to rust-lang#75212. My implementation of `zip()` is mostly just a modified copy-paste of `map()`. Should I keep the comments? Also am I right in assuming there should be no way for the `for`-loop to panic, thus no need for the dropguard seen in the `map()`-function? The doc comment is in a similar way a slightly modified copy paste of [`Iterator::zip()`](https://doc.rust-lang.org/beta/std/iter/trait.Iterator.html#method.zip) `@jplatte` mentioned in [rust-lang#75490](rust-lang#75490 (comment)) `zip_with()`, > zip and zip_with seem like they would be useful :) is this something I should add (assuming there is interest for this PR at all :))
2 parents aec379f + 8b37259 commit f9b9e5d

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

library/core/src/array/mod.rs

+31
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,37 @@ impl<T, const N: usize> [T; N] {
463463
unsafe { crate::mem::transmute_copy::<_, [U; N]>(&dst) }
464464
}
465465

466+
/// 'Zips up' two arrays into a single array of pairs.
467+
///
468+
/// `zip()` returns a new array where every element is a tuple where the
469+
/// first element comes from the first array, and the second element comes
470+
/// from the second array. In other words, it zips two arrays together,
471+
/// into a single one.
472+
///
473+
/// # Examples
474+
///
475+
/// ```
476+
/// #![feature(array_zip)]
477+
/// let x = [1, 2, 3];
478+
/// let y = [4, 5, 6];
479+
/// let z = x.zip(y);
480+
/// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
481+
/// ```
482+
#[unstable(feature = "array_zip", issue = "80094")]
483+
pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
484+
use crate::mem::MaybeUninit;
485+
486+
let mut dst = MaybeUninit::uninit_array::<N>();
487+
for (i, (lhs, rhs)) in IntoIter::new(self).zip(IntoIter::new(rhs)).enumerate() {
488+
dst[i].write((lhs, rhs));
489+
}
490+
// FIXME: Convert to crate::mem::transmute once it works with generics.
491+
// unsafe { crate::mem::transmute::<[MaybeUninit<U>; N], [U; N]>(dst) }
492+
// SAFETY: At this point we've properly initialized the whole array
493+
// and we just need to cast it to the correct type.
494+
unsafe { crate::mem::transmute_copy::<_, [(T, U); N]>(&dst) }
495+
}
496+
466497
/// Returns a slice containing the entire array. Equivalent to `&s[..]`.
467498
#[unstable(feature = "array_methods", issue = "76118")]
468499
pub fn as_slice(&self) -> &[T] {

0 commit comments

Comments
 (0)