| Crates.io | morphix |
| lib.rs | morphix |
| version | 0.13.7 |
| created_at | 2025-10-07 19:30:02.191561+00 |
| updated_at | 2026-01-05 14:27:55.483216+00 |
| description | Observing and serializing mutations |
| homepage | |
| repository | https://github.com/shigma/morphix |
| max_upload_size | |
| id | 1872588 |
| size | 241,945 |
A Rust library for observing and serializing mutations.
Add this to your Cargo.toml:
[dependencies]
morphix = { version = "0.13", features = ["json"] }
use serde::Serialize;
use serde_json::json;
use morphix::adapter::Json;
use morphix::{Mutation, MutationKind, Observe, observe};
// 1. Define any data structure with `#[derive(Observe)]`.
#[derive(Serialize, PartialEq, Debug, Observe)]
struct Foo {
pub bar: Bar,
pub qux: String,
}
#[derive(Serialize, PartialEq, Debug, Observe)]
struct Bar {
pub baz: i32,
}
let mut foo = Foo {
bar: Bar { baz: 42 },
qux: "hello".to_string(),
};
// 2. Use `observe!` to mutate data and track mutations.
let Json(mutation) = observe!(foo => {
foo.bar.baz += 1;
foo.qux.push(' ');
foo.qux += "world";
}).unwrap();
// 3. Inspect the mutations.
assert_eq!(
mutation,
Some(Mutation {
path: vec![].into(),
kind: MutationKind::Batch(vec![
Mutation {
path: vec!["bar".into(), "baz".into()].into(),
kind: MutationKind::Replace(json!(43)),
},
Mutation {
path: vec!["qux".into()].into(),
kind: MutationKind::Append(json!(" world")),
},
]),
}),
);
// 4. The original data structure is also mutated.
assert_eq!(
foo,
Foo {
bar: Bar { baz: 43 },
qux: "hello world".to_string(),
},
);
Morphix recognizes three types of mutations:
The most general mutation type, used for any mutation that replaces a value:
foo.a.b = 1; // Replace at .a.b
foo.num *= 2; // Replace at .num
foo.vec.clear(); // Replace at .vec
Optimized for appending to strings and vectors:
foo.a.b += "text"; // Append to .a.b
foo.a.b.push_str("text"); // Append to .a.b
foo.vec.push(1); // Append to .vec
foo.vec.extend(iter); // Append to .vec
Optimized for truncating strings and vectors:
foo.a.b.truncate(5); // Truncate n-5 chars from .a.b
foo.vec.pop(); // Truncate 1 element from .vec
Multiple mutations combined into a single operation.
derive (default): Enables the Observe derive macroappend (default): Enables Append mutation kindtruncate (default): Enables Truncate mutation kindjson: Includes JSON serialization support via serde_jsonyaml: Includes YAML serialization support via serde_yaml_ng