enum_update/
lib.rs

1#![warn(missing_docs)]
2#![no_std]
3//! This crate provides several derive macros that help with representing
4//! changes to structs using enums.
5//!
6//! For api documentation, see the [`EnumUpdate`](macro@EnumUpdate) documentation. Otherwise,
7//! here is an example of two threads using the generated enum type to keep
8//! their state in sync.
9//!
10//! ```rust
11//! # use enum_update::{ EnumUpdate, EnumUpdateSetters };
12//! #[derive(Debug, EnumUpdate, Clone, EnumUpdateSetters)]
13//! #[enum_update(derive(Debug, Clone, PartialEq))]
14//! pub struct SharedState {
15//!     value: String,
16//! }
17//! let mut thread_a_state = SharedState { value: "Hello".to_string() };
18//! let mut thread_b_state = thread_a_state.clone();
19//!
20//! let (sender, receiver) = std::sync::mpsc::sync_channel(1);
21//! let thread_a = std::thread::Builder::new()
22//!     .spawn(move || {
23//!         let change = thread_a_state.modify_value("World".to_string());
24//!         sender.send(change).unwrap();
25//!     })
26//!     .unwrap();
27//! let thread_b = std::thread::Builder::new()
28//!     .spawn(move || {
29//!         assert_eq!(thread_b_state.value, "H
30//! ello".to_string());
31//!         // now, we receive the change
32//!         let change = receiver.recv().unwrap();
33//!         assert_eq!(change, SharedStateUpdate::Value("World".to_string()));
34//!         // applying the change
35//!         thread_b_state.apply(change);
36//!         // it becomes true
37//!         assert_eq!(thread_b_state.value, "World".to_string());
38//!     })
39//!     .unwrap();
40//! ```
41
42pub use enum_update_derive::{EnumUpdate, EnumUpdateSetters};
43
44/// Implemented on structs that have their updates represented by
45/// some enum `U`. Implement this trait using the derive
46/// macro [`EnumUpdate`].
47pub trait EnumUpdate<U> {
48    /// Apply the given update and mutate the state.
49    fn apply(&mut self, update: U);
50}