SyncState

Trait SyncState 

Source
pub trait SyncState:
    Clone
    + Send
    + Sync
    + 'static {
    type Diff: Clone + Send + Sync;

    const STATE_TYPE_ID: &'static str;

    // Required methods
    fn diff_from(&self, old: &Self) -> Self::Diff;
    fn apply_diff(&mut self, diff: &Self::Diff) -> Result<(), ApplyError>;
    fn encode_diff(diff: &Self::Diff) -> Vec<u8> ;
    fn decode_diff(data: &[u8]) -> Result<Self::Diff, DecodeError>;

    // Provided method
    fn is_diff_empty(diff: &Self::Diff) -> bool { ... }
}
Expand description

Core trait for any state that can be synchronized.

Implements the state type interface from 3-SYNC.md.

§Requirements

  • diff_from MUST produce idempotent diffs
  • apply_diff MUST handle repeated application
  • encode_diff/decode_diff MUST roundtrip correctly

§Example

#[derive(Clone)]
struct Counter { value: u64 }

#[derive(Clone)]
struct CounterDiff { delta: i64 }

impl SyncState for Counter {
    type Diff = CounterDiff;
    const STATE_TYPE_ID: &'static str = "example.counter.v1";

    fn diff_from(&self, old: &Self) -> Self::Diff {
        CounterDiff { delta: self.value as i64 - old.value as i64 }
    }

    fn apply_diff(&mut self, diff: &Self::Diff) -> Result<(), ApplyError> {
        self.value = (self.value as i64 + diff.delta) as u64;
        Ok(())
    }

    fn encode_diff(diff: &Self::Diff) -> Vec<u8> {
        diff.delta.to_le_bytes().to_vec()
    }

    fn decode_diff(data: &[u8]) -> Result<Self::Diff, DecodeError> {
        if data.len() < 8 {
            return Err(DecodeError::UnexpectedEof);
        }
        let delta = i64::from_le_bytes(data[..8].try_into().unwrap());
        Ok(CounterDiff { delta })
    }
}

Required Associated Constants§

Source

const STATE_TYPE_ID: &'static str

Unique type identifier (e.g., “nomad.echo.v1”).

Required Associated Types§

Source

type Diff: Clone + Send + Sync

Diff representation (must be idempotent when applied).

Required Methods§

Source

fn diff_from(&self, old: &Self) -> Self::Diff

Create diff from old_state to self.

MUST be idempotent: applying twice has no additional effect.

Source

fn apply_diff(&mut self, diff: &Self::Diff) -> Result<(), ApplyError>

Apply diff to produce new state.

MUST handle repeated application (idempotent).

Source

fn encode_diff(diff: &Self::Diff) -> Vec<u8>

Serialize diff for wire transmission.

Source

fn decode_diff(data: &[u8]) -> Result<Self::Diff, DecodeError>

Deserialize diff from wire format.

Provided Methods§

Source

fn is_diff_empty(diff: &Self::Diff) -> bool

Check if diff is empty (optimization for ack-only).

Returns true if the diff represents no change.

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§