2 releases

new 0.1.1 Jan 31, 2025
0.1.0 Jan 27, 2025

#124 in #derive-debug

Download history 95/week @ 2025-01-25

95 downloads per month
Used in enum-update

MIT license

23KB
317 lines

enum-update

Crates.io Version docs.rs GitHub License GitHub contributors

enum-update is a set of macros and traits for representing state changes as enums.

Note: enum-update is currently at v0.1.0 and is not at stable v1.0.0 yet. Overall functionality should stay the same, but trait and macro names may change between versions.

Adding enum-update to your project

Import enum-update into your project by running this command.

cargo add enum-update

All enum-update-derive macros are re-exported by enum-update. There is no need to manually add enum-update-derive to your project dependency list.

Macros

The following derive macros are provided by enum-update

Derive macro Description
EnumUpdate Creates a new enum representing updates to a struct
EnumUpdateSetters Add setter methods to a struct that also return enums generated by EnumUpdate

Examples

EnumUpdate

Basic example

use enum_update::*;
#[derive(Debug, PartialEq, EnumUpdate)]
pub struct MyState {
    value: String,
    another_value: u32,
}
// `EnumUpdate` will generate:
// pub enum MyStateUpdate {
//     Value(String),
//     AnotherValue(String),
// }
// impl EnumUpdate<MyStateUpdate> for MyState {
//     fn apply(&mut self, update: MyStateUpdate) {
//         match update {
//             MyStateUpdate::Value(value) => {
//                 self.value = value;
//             },
//             MyStateUpdate::AnotherValue(another_value) => {
//                 self.another_value = another_value;
//             }
//         }
//     }
// }
let mut state = MyState {
    value: "initial_string_value".to_string(),
    another_value: 123,
};
let first_change = MyStateUpdate::Value("new string value".to_string());
state.apply(first_change);
assert_eq!(state, MyState {
    value: "new string value".to_string(),
    another_value: 123
});

EnumUpdateSetters

Basic example

use enum_update::*;
#[derive(Debug, PartialEq, EnumUpdate, EnumUpdateSetters)]
pub struct MyState<'a> {
    value: String,
    my_reference: &'a str
}
// `EnumUpdateSetters` will generate:
// impl<'a> MyState<'a> {
//     fn modify_value(&mut self, value: String) -> MyStateUpdate {
//         self.value = value.clone();
//     }
//     fn modify_my_reference(&mut self, my_reference: &'a str) -> MyStateUpdate {
//         self.my_reference = my_reference;
//     }
// }
let mut state: MyState<'static> = MyState {
    value: "hello".to_string(),
    my_reference: "world",
};
state.modify_my_reference("enum updates");
assert_eq!(state, MyState {
    value: "hello".to_string(),
    my_reference: "enum updates"
});

Contributing

Contributions and bug fixes are always welcome. Please open an issue first before implementing a feature or fixing a bug. It is possible that I am already implementing it locally.

Dependencies

~0.7–1.1MB
~22K SLoC