StatefulObserver

Trait StatefulObserver 

Source
pub trait StatefulObserver<'i, T>: Observer<'i, T> {
    // Required method
    fn mutation_state(this: &mut Self) -> &mut Option<MutationState>;

    // Provided methods
    fn mark_replace(this: &mut Self) { ... }
    fn mark_append(this: &mut Self, start_index: usize) { ... }
}
Expand description

An Observer that maintains internal state about mutations.

Unlike ShallowObserver which only tracks whether a mutation occurred, StatefulObserver implementations can distinguish between different types of mutations (replace vs. append) and optimize the resulting mutation representation accordingly.

§Implementation Notes

Implementing StatefulObserver allows an observer to track its own mutation state (e.g., replace or append), but this doesn’t preclude tracking additional mutations. Complex types like Vec<T> may need to track both:

  • Their own mutation state (via StatefulObserver)
  • Changes to their elements (via nested observers)

These different sources of mutations are then combined into a final result:

// Example from VecObserver implementation
impl<'i, T: Observe> Observer<'i, Vec<T>> for VecObserver<'i, T> {
    fn collect<A: Adapter>(mut this: Self) -> Result<Option<Mutation<A>>, A::Error> {
        let mut mutations = vec![];

        // 1. Collect own mutation state (replacement or append)
        if let Some(state) = Self::mutation_state(&mut this).take() {
            mutations.push(Mutation {
                operation: match state {
                    MutationState::Replace => MutationKind::Replace(..),
                    MutationState::Append(idx) => MutationKind::Append(..),
                },
                // ...
            });
        }

        // 2. Collect mutations from nested element observers
        for (index, observer) in element_observers {
            if let Some(mutation) = observer.collect()? {
                mutations.push(mutation);
            }
        }

        // 3. Combine all mutations (may result in a Batch)
        Ok(Batch::build(mutations))
    }
}

This design allows for sophisticated mutation tracking where:

  • Simple operations (like vec.push()) produce an Append mutation
  • Element modifications (like vec[0].field = value) produce element-specific mutations
  • Multiple operations produce a Batch containing all mutations

Currently implemented for:

  • String
  • Vec<T>

Required Methods§

Source

fn mutation_state(this: &mut Self) -> &mut Option<MutationState>

Provided Methods§

Source

fn mark_replace(this: &mut Self)

Source

fn mark_append(this: &mut Self, start_index: usize)

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§