Skip to content

Commit 4c04148

Browse files
Added derived From<Variant> for Enum implementations. Added to documentation.
1 parent 976e425 commit 4c04148

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/lib.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,24 @@
6969
//! }
7070
//! }
7171
//! }
72+
//!
73+
//! impl From<Cat> for Animal {
74+
//! fn from(from: Cat) -> Self {
75+
//! Animal::Cat(from)
76+
//! }
77+
//! }
78+
//!
79+
//! impl From<Lion> for Animal {
80+
//! fn from(from: Lion) -> Self {
81+
//! Animal::Lion(from)
82+
//! }
83+
//! }
84+
//!
85+
//! impl From<Mouse> for Animal {
86+
//! fn from(from: Mouse) -> Self {
87+
//! Animal::Mouse(from)
88+
//! }
89+
//! }
7290
//! }
7391
//! ```
7492
//! This, however, will only compile if `Cat`, `Lion` and `Mouse` all have a method called `feed`.
@@ -314,6 +332,22 @@ impl GenerateProxyImpl {
314332
.get(&path)
315333
.unwrap_or_else(|| panic!("missing declaration of trait `{}`", path))
316334
}
335+
336+
fn impl_from_variants(&self, module: &mut ItemMod) {
337+
let proxy_enum = &self.proxy_enum;
338+
for WrapperVariant { variant, wrapped, .. } in self.get_variants() {
339+
let variant = &variant.ident;
340+
let tokens = quote! {
341+
impl From<#wrapped> for #proxy_enum {
342+
fn from(from: #wrapped) -> Self {
343+
#proxy_enum :: #variant(from)
344+
}
345+
}
346+
};
347+
let from_impl: ItemImpl = syn::parse2(tokens).unwrap();
348+
module.content.as_mut().unwrap().1.push(from_impl.into());
349+
}
350+
}
317351
}
318352

319353
impl VisitMut for GenerateProxyImpl {
@@ -360,6 +394,7 @@ impl VisitMut for GenerateProxyImpl {
360394
true
361395
}
362396
});
397+
self.impl_from_variants(module);
363398
}
364399

365400
// scan for trait declarations and store them

0 commit comments

Comments
 (0)