Skip to content

Commit 3b8617b

Browse files
committed
Added [T; N]::zip()
1 parent 72da5a9 commit 3b8617b

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

library/core/src/array/mod.rs

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

library/core/tests/array.rs

+8
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,14 @@ fn array_map() {
317317
assert_eq!(b, [1, 2, 3]);
318318
}
319319

320+
#[test]
321+
fn array_zip() {
322+
let a = [1, 2, 3];
323+
let b = [4, 5, 6];
324+
let c = a.zip(b);
325+
assert_eq!(c, [(1, 4), (2, 5), (3, 6)]);
326+
}
327+
320328
// See note on above test for why `should_panic` is used.
321329
#[test]
322330
#[should_panic(expected = "test succeeded")]

library/core/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#![feature(array_from_ref)]
44
#![feature(array_methods)]
55
#![feature(array_map)]
6+
#![feature(array_zip)]
67
#![feature(array_windows)]
78
#![feature(bool_to_option)]
89
#![feature(bound_cloned)]

0 commit comments

Comments
 (0)