Perstruct
perstruct is a crate that provides a macro to transform a Rust struct into a settings struct.
It facilitates the loading and saving of struct fields as key/value pairs. This is particularly
useful for application settings or configurations, where each setting can be individually
updated and persisted.
This approach offers significant advantages over whole-struct serialization and deserialization, especially in scenarios where the application's configuration or user preferences need to be flexible and resilient to changes.
The field values are serialized as json. Other formats may be supported in the future.
Below is an example demonstrating how to use the perstruct macro to manage user ferences in an application:
use perstruct;
// Define a struct for user preferences.
// Apply the `perstruct` macro to enable key/value storage capabilities.
// Simulate loading preferences from a key-value store (like a database or config file).
// These might be values previously saved by the user.
let kv_store_simulation = vec!.into_iter.collect;
let result = from_map;
// Access the loaded preferences, handle deserialization errors or unknown fields.
let mut preferences = result.value;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert!;
// Modify preferences using the auto-generated setters.
preferences.set_ui_theme;
preferences.set_enable_notifications;
// Retrieve changes (dirty fields) to persist them.
let mut changes = preferences.perstruct_get_changes.unwrap;
changes.sort_by_key;
assert_eq!;
// Simulate saving the changes to the kv store.
// ...
// Mark changes as saved using `perstruct_saved`.
preferences.perstruct_saved;
// Verify that there are no unsaved changes.
assert_eq!;
Restrictions
The perstruct macro can only be applied to structs that meet the following requirements:
- All non-skipped field types must implement
serde::Serializeandserde::Deserialize. - All non-skipped fields must implement
Defaultor have a default value specified using perstruct(default = ...)]or#[perstruct(default_fn = "...")]`.