observe

Macro observe 

Source
observe!() { /* proc-macro */ }
Expand description

Observe and collect mutations within a closure.

This macro wraps a closure’s operations to track all mutations that occur within it. The closure receives a mutable reference to the value, and any mutations made are automatically collected and returned.

§Syntax

observe!(Adapter, |mut_binding| { /* mutations */ })
observe!(|mut_binding| { /* mutations */ })     // Type inference

§Parameters

  • Adapter (optional) - adapter to use for serialization (e.g., JsonAdapter)
  • mut_binding - binding pattern for the mutable value in the closure

§Returns

Returns Result<Option<Mutation<A>>, A::Error> where:

  • Ok(None) - No mutations were made
  • Ok(Some(mutation)) - Contains the collected mutations
  • Err(error) - Serialization failed

§Examples

With explicit adapter type:

use serde::Serialize;
use morphix::{JsonAdapter, Observe, observe};

#[derive(Serialize, Observe)]
struct Point {
    x: f64,
    y: f64,
}

let mut point = Point { x: 1.0, y: 2.0 };

let mutation = observe!(JsonAdapter, |mut point| {
    point.x += 1.0;
    point.y *= 2.0;
}).unwrap();

assert_eq!(point.x, 2.0);
assert_eq!(point.y, 4.0);

With type inference:

use morphix::{JsonAdapter, Mutation, observe};

let mut point = Point { x: 1.0, y: 2.0 };

let mutation: Option<Mutation<JsonAdapter>> = observe!(|mut point| {
    point.x += 1.0;
    point.y *= 2.0;
}).unwrap();