Attribute Macro binroots::binroots_struct
source · #[binroots_struct]Expand description
binroots_struct
A procedural macro attribute that enables serialization and structured file-saving for it and its fields.
Usage
#[binroots_struct] can be applied to any named struct with named fields. The attribute generates an implementation of binroots::Serialize (re-exported from serde::Serialize) for the struct, as well as a set of methods for serializing, deserializing, and saving instances of the struct to disk.
use binroots::binroots_struct;
#[binroots_struct] // Saves to `/tmp/<CARGO_PKG_NAME>/my-struct/` on Unix
pub struct MyStruct {
field1: i32,
field2: String,
field3: bool,
}
// --- OR ---
#[binroots_struct(persistent)] // Saves to `$HOME/.cache/<CARGO_PKG_NAME>/my-persistent-struct/` on Unix
pub struct MyPersistentStruct {
field1: i32,
field2: String,
field3: bool,
}The generated code includes a new implementation of the input struct with the following changes:
- Wraps each field in a binroots::field::BinrootsField
- derives [Debug] and binroots::Serialize
- Generates Self::ROOT_FOLDER, the kebab-case name of the struct
- Adds a new method to the struct, which constructs a new instance of the struct from its fields.
- Adds a save method to the struct, which serializes the struct and saves it to disk using the binroots::save::Save trait, saving to Self::ROOT_FOLDER.
- A [Default] implementation is added to the struct, which constructs a default instance of the struct with default values for all fields.
use binroots::binroots_struct;
use binroots::save::RootType;
#[binroots_struct] // Root save path on Unix is `/tmp/<CARGO_PKG_NAME>/person/` because we didn't annotate with `#[binroots_struct(persistent)]`
pub struct Person {
name: String,
gender: String,
age: u8,
email: Option<String>,
}
fn main() {
let mut person = Person::new(
"Alex".into(),
"Male".into(),
42,
Some("alex@example.com".into()),
);
// We need to dereference because `person.alice` is `binroots::field::BinrootsField<"name", u8>`
*person.name = "Alice".into();
*person.gender = "Female".into();
person.save().unwrap(); // Saves the entire struct to the disk
*person.email = Some("alice@example.com".into());
person.email.save(Person::ROOT_FOLDER, RootType::InMemory).unwrap(); // Saves only person.email to the disk in its appropriate location
}