from_enum/lib.rs
1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! This crate provides a derive macro [`FromEnum`](from_enum_derive::FromEnum) to easily generate
6//! conversion impls to extract an enum variant's value from a newtype-style enum.
7//!
8//! This is most useful when writing generic functions that can operate on any variant's inner type.
9//!
10//! # Example
11//! ```
12//! ## #[allow(dead_code)]
13//! #[derive(FromEnum)]
14//! enum Animal {
15//! Dog(DogParams),
16//! Cat(CatParams),
17//! }
18//!
19//! fn handle_animal<T: FromEnum<Animal> + Debug>(animal: &Animal) {
20//! match FromEnum::from_enum(animal) {
21//! Some(params) => println!("Found my animal {:?}", params),
22//! None => println!("This is not my animal"),
23//! }
24//! }
25//!
26//! ## #[derive(Debug)]
27//! ## struct DogParams;
28//! ## struct CatParams;
29//! ## fn main() {
30//! let animal = Animal::Dog(DogParams);
31//! handle_animal::<DogParams>(&animal);
32//! ## }
33
34pub use from_enum_derive::FromEnum;
35
36/// Attempts to match the enum `E` to find a variant with a single field of type `Self`.
37pub trait FromEnum<E> {
38 fn from_enum(e: &E) -> Option<&Self>;
39}