Skip to content

Commit 9a02c81

Browse files
authored
Simplify macro implementation for tuples (#1340)
1 parent e42c385 commit 9a02c81

File tree

1 file changed

+33
-32
lines changed

1 file changed

+33
-32
lines changed

src/distributions/other.rs

+33-32
Original file line numberDiff line numberDiff line change
@@ -191,49 +191,50 @@ where
191191
}
192192
}
193193

194+
/// Implement `Distribution<(A, B, C, ...)> for Standard, using the list of
195+
/// identifiers
194196
macro_rules! tuple_impl {
195-
// use variables to indicate the arity of the tuple
196-
($($tyvar:ident),* ) => {
197-
// the trailing commas are for the 1 tuple
198-
impl< $( $tyvar ),* >
199-
Distribution<( $( $tyvar ),* , )>
200-
for Standard
201-
where $( Standard: Distribution<$tyvar> ),*
197+
($($tyvar:ident)*) => {
198+
impl< $($tyvar,)* > Distribution<($($tyvar,)*)> for Standard
199+
where $(
200+
Standard: Distribution< $tyvar >,
201+
)*
202202
{
203203
#[inline]
204-
fn sample<R: Rng + ?Sized>(&self, _rng: &mut R) -> ( $( $tyvar ),* , ) {
205-
(
204+
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> ( $($tyvar,)* ) {
205+
let out = ($(
206206
// use the $tyvar's to get the appropriate number of
207207
// repeats (they're not actually needed)
208-
$(
209-
_rng.gen::<$tyvar>()
210-
),*
211-
,
212-
)
208+
rng.gen::<$tyvar>()
209+
,)*);
210+
211+
// Suppress the unused variable warning for empty tuple
212+
let _rng = rng;
213+
214+
out
213215
}
214216
}
215217
}
216218
}
217219

218-
impl Distribution<()> for Standard {
219-
#[allow(clippy::unused_unit)]
220-
#[inline]
221-
fn sample<R: Rng + ?Sized>(&self, _: &mut R) -> () {
222-
()
223-
}
220+
/// Looping wrapper for `tuple_impl`. Given (A, B, C), it also generates
221+
/// implementations for (A, B) and (A,)
222+
macro_rules! tuple_impls {
223+
($($tyvar:ident)*) => {tuple_impls!{[] $($tyvar)*}};
224+
225+
([$($prefix:ident)*] $head:ident $($tail:ident)*) => {
226+
tuple_impl!{$($prefix)*}
227+
tuple_impls!{[$($prefix)* $head] $($tail)*}
228+
};
229+
230+
231+
([$($prefix:ident)*]) => {
232+
tuple_impl!{$($prefix)*}
233+
};
234+
224235
}
225-
tuple_impl! {A}
226-
tuple_impl! {A, B}
227-
tuple_impl! {A, B, C}
228-
tuple_impl! {A, B, C, D}
229-
tuple_impl! {A, B, C, D, E}
230-
tuple_impl! {A, B, C, D, E, F}
231-
tuple_impl! {A, B, C, D, E, F, G}
232-
tuple_impl! {A, B, C, D, E, F, G, H}
233-
tuple_impl! {A, B, C, D, E, F, G, H, I}
234-
tuple_impl! {A, B, C, D, E, F, G, H, I, J}
235-
tuple_impl! {A, B, C, D, E, F, G, H, I, J, K}
236-
tuple_impl! {A, B, C, D, E, F, G, H, I, J, K, L}
236+
237+
tuple_impls! {A B C D E F G H I J K L}
237238

238239
impl<T, const N: usize> Distribution<[T; N]> for Standard
239240
where Standard: Distribution<T>

0 commit comments

Comments
 (0)