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//!     #[variant_group]
16//!     value: String,
17//! }
18//! let mut thread_a_state = SharedState { value: "Hello".to_string() };
19//! let mut thread_b_state = thread_a_state.clone();
20//!
21//! let (sender, receiver) = std::sync::mpsc::sync_channel(1);
22//! let thread_a = std::thread::Builder::new()
23//!     .spawn(move || {
24//!         let change = thread_a_state.modify_value("World".to_string());
25//!         sender.send(change).unwrap();
26//!     })
27//!     .unwrap();
28//! let thread_b = std::thread::Builder::new()
29//!     .spawn(move || {
30//!         assert_eq!(thread_b_state.value, "H
31//! ello".to_string());
32//!         // now, we receive the change
33//!         let change = receiver.recv().unwrap();
34//!         assert_eq!(change, SharedStateUpdate::Value{ value: "World".to_string() });
35//!         // applying the change
36//!         thread_b_state.apply(change);
37//!         // it becomes true
38//!         assert_eq!(thread_b_state.value, "World".to_string());
39//!     })
40//!     .unwrap();
41//! ```
42
43pub use enum_update_derive::{EnumUpdate, EnumUpdateSetters};
44
45/// Implemented on structs that have their updates represented by
46/// some enum `U`. Implement this trait using the derive
47/// macro [`EnumUpdate`].
48pub trait EnumUpdate<U> {
49    /// Apply the given update and mutate the state.
50    fn apply(&mut self, update: U);
51}