Skip to content

Commit 2f9f7f4

Browse files
authored
Merge pull request #165 from nvzqz/master
Change derive behavior for enums with less than three variants
2 parents 07676c3 + 4fbc623 commit 2f9f7f4

File tree

2 files changed

+41
-12
lines changed

2 files changed

+41
-12
lines changed

rand-derive/src/lib.rs

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,11 @@ fn impl_rand_derive(ast: &syn::MacroInput) -> quote::Tokens {
6363
}
6464

6565
let len = body.len();
66-
let mut variants = body
66+
let mut arms = body
6767
.iter()
68-
.enumerate()
69-
.map(|(index, variant)| {
68+
.map(|variant| {
7069
let ident = &variant.ident;
71-
let arm = match variant.data {
70+
match variant.data {
7271
syn::VariantData::Struct(ref body) => {
7372
let fields = body
7473
.iter()
@@ -85,13 +84,24 @@ fn impl_rand_derive(ast: &syn::MacroInput) -> quote::Tokens {
8584
quote! { #name::#ident (#(#fields),*) }
8685
},
8786
syn::VariantData::Unit => quote! { #name::#ident }
88-
};
87+
}
88+
});
8989

90-
quote! { #index => #arm }
91-
})
92-
.collect::<Vec<_>>();
93-
variants.push(quote! { _ => unreachable!() });
94-
quote! { match __rng.gen_range(0, #len) { #(#variants,)* } }
90+
match len {
91+
1 => quote! { #(#arms)* },
92+
2 => {
93+
let (a, b) = (arms.next(), arms.next());
94+
quote! { if __rng.gen() { #a } else { #b } }
95+
},
96+
_ => {
97+
let mut variants = arms
98+
.enumerate()
99+
.map(|(index, arm)| quote! { #index => #arm })
100+
.collect::<Vec<_>>();
101+
variants.push(quote! { _ => unreachable!() });
102+
quote! { match __rng.gen_range(0, #len) { #(#variants,)* } }
103+
},
104+
}
95105
}
96106
};
97107

rand-derive/tests/rand_macros.rs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,23 @@ struct Tuple(i16, Option<f64>);
1919
struct Unit;
2020

2121
#[derive(Rand)]
22-
enum Enum {
22+
enum EnumUnit {
23+
X,
24+
}
25+
26+
#[derive(Rand)]
27+
enum Enum1 {
28+
X(u8, f32),
29+
}
30+
31+
#[derive(Rand)]
32+
enum Enum2 {
33+
X(bool),
34+
Y,
35+
}
36+
37+
#[derive(Rand)]
38+
enum Enum3 {
2339
X { x: u8, y: isize },
2440
Y([bool; 4]),
2541
Z,
@@ -34,6 +50,9 @@ fn smoke() {
3450
let _ = rng.gen::<Struct>();
3551
let _ = rng.gen::<Tuple>();
3652
let _ = rng.gen::<Unit>();
37-
let _ = rng.gen::<Enum>();
53+
let _ = rng.gen::<EnumUnit>();
54+
let _ = rng.gen::<Enum1>();
55+
let _ = rng.gen::<Enum2>();
56+
let _ = rng.gen::<Enum3>();
3857
}
3958
}

0 commit comments

Comments
 (0)