Skip to content

Commit 963a4d3

Browse files
committed
Rework the multizip macros for log2 nesting depth
1 parent faf347a commit 963a4d3

File tree

1 file changed

+41
-14
lines changed

1 file changed

+41
-14
lines changed

src/iter/multizip.rs

Lines changed: 41 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -82,31 +82,58 @@ pub struct MultiZip<T> {
8282
tuple: T,
8383
}
8484

85+
// These macros greedily consume 4 or 2 items first to achieve log2 nesting depth.
86+
// For example, 5 => 4,1 => (2,2),1.
87+
//
88+
// The tuples go up to 12, so we might want to greedily consume 8 too, but
89+
// the depth works out the same if we let that expand on the right:
90+
// 9 => 4,5 => (2,2),(4,1) => (2,2),((2,2),1)
91+
// 12 => 4,8 => (2,2),(4,4) => (2,2),((2,2),(2,2))
92+
//
93+
// But if we ever increase to 13, we would want to split 8,5 rather than 4,9.
94+
8595
macro_rules! zip {
86-
($first:expr, $( $iter:expr, )*) => {
87-
$first $( .zip($iter) )*
96+
($a:expr, $b:expr, $c:expr, $d:expr, $( $x:expr, )+) => {
97+
zip!(zip!($a, $b, $c, $d,), zip!($( $x, )+),)
98+
};
99+
($a:expr, $b:expr, $( $x:expr, )+) => {
100+
zip!(zip!($a, $b,), zip!($( $x, )+),)
101+
};
102+
($a:expr, $( $x:expr, )*) => {
103+
$a $( .zip($x) )*
88104
};
89105
}
90106

91107
macro_rules! min {
92-
($x:expr,) => { $x };
93-
($x:expr, $( $y:expr, )+) => { cmp::min($x, min!($( $y, )+)) };
108+
($a:expr, $b:expr, $c:expr, $d:expr, $( $x:expr, )+) => {
109+
min!(min!($a, $b, $c, $d,), min!($( $x, )+),)
110+
};
111+
($a:expr, $b:expr, $( $x:expr, )+) => {
112+
min!(min!($a, $b,), min!($( $x, )+),)
113+
};
114+
($a:expr, $b:expr,) => { cmp::min($a, $b) };
115+
($a:expr,) => { $a };
116+
}
117+
118+
macro_rules! nest {
119+
($A:tt, $B:tt, $C:tt, $D:tt, $( $X:tt, )+) => {
120+
(nest!($A, $B, $C, $D,), nest!($( $X, )+))
121+
};
122+
($A:tt, $B:tt, $( $X:tt, )+) => {
123+
(($A, $B), nest!($( $X, )+))
124+
};
125+
($A:tt, $B:tt,) => { ($A, $B) };
126+
($A:tt,) => { $A };
94127
}
95128

96129
macro_rules! flatten {
97-
(|$a:tt : $A:tt| -> ($( $X:ident, )+) { $tuple:tt };) => {{
98-
fn flatten<$( $X ),+>($a : $A) -> ($( $X, )*) {
99-
$tuple
130+
($( $T:ident, )+) => {{
131+
#[allow(non_snake_case)]
132+
fn flatten<$( $T ),+>(nest!($( $T, )+) : nest!($( $T, )+)) -> ($( $T, )+) {
133+
($( $T, )+)
100134
}
101135
flatten
102136
}};
103-
(|$a:tt : $A:tt| -> ($( $X:ident, )+) { ($( $x:ident, )+) };
104-
$B:ident, $( $T:ident, )*) => {
105-
flatten!(|($a, b): ($A, $B)| -> ($( $X, )+ $B,) { ($( $x, )+ b,) }; $( $T, )*)
106-
};
107-
($A:ident, $( $T:ident, )*) => {
108-
flatten!(|a: $A| -> ($A,) { (a,) }; $( $T, )*)
109-
};
110137
}
111138

112139
macro_rules! multizip_impls {

0 commit comments

Comments
 (0)