2 releases
0.1.1 | Jan 25, 2023 |
---|---|
0.1.0 | Jan 24, 2023 |
#1864 in Procedural macros
8KB
108 lines
ace_it
Auto Convert Enums
Description
Just a small proc_macro to automatically generate From trait impls for each unnamed variant of an enum
Usage
Cargo.toml:
[dependencies]
ace_it = "0.1"
Example
#[macro_use]
extern crate ace_it;
#[derive(Debug)]
#[ace_it]
enum Error {
Io(std::io::Error),
ParseInt(std::num::ParseIntError),
ParseFloat(std::num::ParseFloatError),
}
use std::io::Read;
fn read_int<R: Read>(reader: &mut R) -> Result<i32, Error> {
let mut buf = String::new();
reader.read_to_string(&mut buf)?;
Ok(buf.parse()?)
}
Future features
- Attribute for ignoring a variant
lib.rs
:
Auto Convert Enums
This crate provides a proc macro that generates [From] impls for unnamed enum fields that have a type.
Ever get tired of writing the same From impls to enable using ?
on some [Result] types? This crate is for you!
This is useful for enums that are used as a wrapper for a collecting multiple errors into one big enum.
Example
#[macro_use] extern crate ace_it;
#[derive(Debug)]
#[ace_it]
enum Error {
Io(std::io::Error),
ParseInt(std::num::ParseIntError),
ParseFloat(std::num::ParseFloatError),
}
After this, Error has three [From] impls:
- [From]<std::io::Error> for Error
- [From]<std::num::ParseIntError> for Error
- [From]<std::num::ParseFloatError> for Error
Now you can use ?
on any of these types and get an Error back.
use std::io::Read;
fn read_int<R: Read>(reader: &mut R) -> Result<i32, Error> {
let mut buf = String::new();
reader.read_to_string(&mut buf)?;
Ok(buf.parse()?)
}
Dependencies
~1.5MB
~36K SLoC