Simple Rust derive-macro that simplifies integral enum creation

Overview

Integral enum

A simple way to define integer-like enums. This macro implements bunch of traits that are usually implemented via looooong derive(..) attribute.

Tour

IntegralEnum

By default [IntegralEnum] assumes that you want all trait implementations: PartialOrd, Ord, PartialEq, Eq, Debug, Clone, Copy, TryFrom

use integral_enum::IntegralEnum;

#[derive(IntegralEnum)]
pub enum Sex {
    Male,
    Female,
}

assert_ne!(Sex::Male, Sex::Female);
assert!(Sex::Female > Sex::Male);
assert_eq!(Sex::try_from(0), Ok(Sex::Male));
assert_eq!(format!("{:?}", Sex::Male), "Male");
assert_eq!(Sex::Female.clone(), Sex::Female);

But you may disable some implementations by applying the #[enum_disable(..)] attribute (this will fail to compile due to disabled Debug trait implementation):

#[derive(IntegralEnum)]
#[enum_disable(debug)]
pub enum Sex {
    Male,
    Female,
}

assert_eq!(format!("{:?}", Sex::Male), "Male");

This is useful if you want to compose [IntegralEnum] with some other macro or your own trait implementations, consider example with the thiserror::Error macro (IT IS MARKED AS COMPILE FAIL ONLY DUE TO LACK OF thiserror DEPENDENCY):

use integral_enum::IntegralEnum;
use thiserror::Error;

#[derive(IntegralEnum, Error)]
pub enum SendError {
    #[error("The remote side is closed connection")]
    Closed,

    #[error("Client with specified id was not found")]
    NotFound,
}

StrictIntegralEnum

On the other hand you may want to enable certain implementations, here the [StrictIntegralEnum] serves you:

use integral_enum::StrictIntegralEnum;

#[derive(StrictIntegralEnum)]
#[enum_impl(debug, partial_eq, try_from)]
pub enum Sex {
    Male,
    Female
}

assert_eq!(Sex::try_from(0), Ok(Sex::Male));

There's no other real use-case other than implementing the try_from, but I left possibility to autoimplement other traits for convenience.

Dependencies

Some traits are depending on others, for example Copy depends on Clone, so, if you disable Clone implementation, then Copy implementation will be disabled too. For strict enums rules are the same, but differs in details: if you enable Clone implementation it will not enable the Copy. So, here the dependencies:

  • Clone depends on Copy
  • Eq depends on PartialEq
  • PartialOrd depends on Eq, Copy
  • Ord depends on PartialOrd

Limitations

IntegralEnum tries to determine the discriminant exact type based on the following conditions:

  • #[repr(..)] attribute
  • deducing by the number of variants

And there's no type inference, wontfix.

So, macro will generate wrong code if there is no #[repr(..)] or discriminant type will deduced wrongly. It is quite hard to infer exact discriminant type with the only AST data, consider the following examples:

// Deduction is not watching to the enum tag's values
// (it is quite hard or even impossible to do it the correct way as stated above, 
//  since tags are just expressions, whose types we can't precisely infer and it just,
//  overcomplicated? This crate is not a all-in solution, just simple pattern implementation,
//  own type-inference will be overkill)
pub enum U16Tag {
    Tag = 0xFF_FF,
}
You might also like...
Proc macro implementation of #[naked]

#[naked] Documentation This crate provide a proc macro version of the #[naked] attribute which can be used on stable Rust. Example // The SYSV64 calli

Macro for fast implementing serialize methods in serde::Serializer trait

impl_serialize! This library provides a simple procedural macro for fast implementing serialize methods in serde::Serializer trait. [dependencies] imp

hashmap macro for creating hashmap from provided key/value pairs

HashMap Macro Creates a HashMap from provided key/value pairs. Usage use std::collections::HashMap; use hashmap_macro::hashmap; let m: HashMap&str,

proc-macro to help with using surrealdb's custom functions

SurrealDB Functions This is a proc-macro crate that given a path to a .surql file or a folder of .surql files, will parse DEFINE FUNCTION fn::s inside

todo2(a.k.a. todo or die) - A better todo! macro inspired from searls/todo_or_die

todo2 todo2(a.k.a. todo or die) - A better todo! macro inspired from searls/todo_or_die This crate provides a better todo! macro, which allows you to

A procedural macro to generate a new function implementation for your struct.

Impl New 🦀 A procedural macro to generate a new function implementation for your struct. 🚀 Add to your project Add this to your Cargo.toml: [depende

Simple autoclicker written in Rust, to learn the Rust language.

RClicker is an autoclicker written in Rust, written to learn more about the Rust programming language. RClicker was was written by me to learn more ab

TypeRust - simple Rust playground where you can build or run your Rust code and share it with others

Rust playground Welcome to TypeRust! This is a simple Rust playground where you can build or run your Rust code and share it with others. There are a

Simple and performant hot-reloading for Rust

reloady Simple, performant hot-reloading for Rust. Requires Rust nightly and only works on Linux for now. installing CLI To install the CLI helper car

Owner
null
Procedural macro to derive Serde serializer-deserializer for Prost

prost-serde-derive prost-serde-derive is a procedural macro to generate Serde serializers and deserializers for Prost-generated structs. Rationale Cur

Park Joon-Kyu 4 Dec 15, 2022
API for the creation character based games in Linux.

Console Game Engine for Linux. API for the creation of character based games in Linux. The inspiration came from the olcConsoleGameEngine. This is my

Arjob Mukherjee 4 Sep 27, 2022
Derive `clone_from` for `Clone` in Rust

Derive Clone including clone_from This crate offers a derive macro called CloneFrom to derive Clone with a specialized clone_from implementation. When

Moritz Hoffmann 7 Mar 13, 2023
Derive AsyncRead and AsyncWrite.

derive-tokio-io Derive AsyncRead and AsyncWrite. Usage If the struct has only one field, AsyncRead and AsyncWrite are derived for that field. use deri

Eray Karatay 3 Nov 17, 2022
Derive conversion traits when items are structurally similar.

structural-convert Derive conversion traits when items are structurally similar. Inspired by serde and struct-convert crates. Features One to one fiel

Julius Lungys 3 Feb 22, 2024
A Rust macro for writing nested loop expressions

loop_chain A Rust macro for writing nested loop expressions Usage | Examples | Docs Dependencies [dependencies] loop_chain = "0.1.1" Usage For express

Takayuki Maeda 5 Jul 30, 2021
Macro assembler for Rust

Macro Assembler This crate implement JSC/SpiderMonkey like macro assembler. Macro assembler purpose is to generate machine code for different platform

playX 6 Nov 26, 2022
A Rust attribute macro that adds memoization to a function (rhymes with Mickey)

michie (sounds like Mickey) — an attribute macro that adds memoization to a function. Table of contents Features Non-features key_expr key_type store_

Mobus Operandi 16 Dec 20, 2022
Library and proc macro to analyze memory usage of data structures in rust.

Allocative: memory profiler for Rust This crate implements a lightweight memory profiler which allows object traversal and memory size introspection.

Meta Experimental 19 Jan 6, 2023
A procedural macro for configuring constant values across crates

toml-cfg Rough ideas: Crates can declare variables that can be overridden Anything const, e.g. usize, strings, etc. (Only) The "root crate" can overri

James Munns 43 Dec 24, 2022