Skip to content

Commit cb67715

Browse files
committed
Merge #10
10: Simplify discriminant matching r=cuviper a=cuviper We don't actually need to know the expressions assigned to each variant, nor compute offsets for those without an expression. We can just cast each `#name::#ident` directly to `i64` for comparison.
2 parents 6f8d5e6 + 53f2b33 commit cb67715

File tree

1 file changed

+5
-32
lines changed

1 file changed

+5
-32
lines changed

src/lib.rs

Lines changed: 5 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,6 @@ pub fn from_primitive(input: TokenStream) -> TokenStream {
3535
};
3636

3737
let from_i64_var = quote! { n };
38-
let mut expr = quote! { 0i64 };
39-
let mut offset = 0i64;
4038
let clauses: Vec<_> = variants.iter()
4139
.map(|variant| {
4240
let ident = &variant.ident;
@@ -47,21 +45,8 @@ pub fn from_primitive(input: TokenStream) -> TokenStream {
4745
},
4846
}
4947

50-
let discriminant_expr = match variant.discriminant {
51-
Some((_, ref const_expr)) => {
52-
expr = quote! { (#const_expr) as i64 };
53-
offset = 1;
54-
expr.clone()
55-
}
56-
None => {
57-
let tt = quote! { #expr + #offset };
58-
offset += 1;
59-
tt
60-
}
61-
};
62-
6348
quote! {
64-
if #from_i64_var == #discriminant_expr {
49+
if #from_i64_var == #name::#ident as i64 {
6550
Some(#name::#ident)
6651
}
6752
}
@@ -105,8 +90,6 @@ pub fn to_primitive(input: TokenStream) -> TokenStream {
10590
_ => panic!("`ToPrimitive` can be applied only to the enums, {} is not an enum", name)
10691
};
10792

108-
let mut expr = quote! { 0i64 };
109-
let mut offset = 0i64;
11093
let variants: Vec<_> = variants.iter()
11194
.map(|variant| {
11295
let ident = &variant.ident;
@@ -117,20 +100,10 @@ pub fn to_primitive(input: TokenStream) -> TokenStream {
117100
},
118101
}
119102

120-
let discriminant_expr = match variant.discriminant {
121-
Some((_, ref const_expr)) => {
122-
expr = quote! { (#const_expr) as i64 };
123-
offset = 1;
124-
expr.clone()
125-
}
126-
None => {
127-
let tt = quote! { #expr + #offset };
128-
offset += 1;
129-
tt
130-
}
131-
};
132-
133-
quote!(#name::#ident => (#discriminant_expr))
103+
// NB: We have to check each variant individually, because we'll only have `&self`
104+
// for the input. We can't move from that, and it might not be `Clone` or `Copy`.
105+
// (Otherwise we could just do `*self as i64` without a `match` at all.)
106+
quote!(#name::#ident => #name::#ident as i64)
134107
})
135108
.collect();
136109

0 commit comments

Comments
 (0)