lamarge 0.8.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! Fill state tracking over the event stream.

use std::collections::HashMap;

use super::{Change, Snapshot};
use crate::{
    model::{EventData, FillPreview},
    types::{FillId, Revision},
};

/// The reader's fills, kept current from the [`Change`]s of a private
/// [`EventStream`](super::EventStream). Events repeat and may arrive late: a fill is replaced only
/// by a newer revision.
#[derive(Debug, Clone, Default)]
pub struct FillTracker {
    fills: HashMap<FillId, (Revision, FillPreview)>,
    synced: bool,
}

impl FillTracker {
    /// Applies one change: a private resync replaces every fill; a `fill.changed` event replaces
    /// its fill when its revision is newer than the one held. Public resyncs carry no fills and
    /// change nothing.
    pub fn apply(&mut self, change: &Change) {
        match change {
            Change::Resync(Snapshot::Private(snapshot)) => {
                self.fills.clear();
                for fill in &snapshot.fills {
                    self.update(fill.revision, fill.fill.clone());
                }
                self.synced = true;
            }
            Change::Resync(Snapshot::Public(_)) => {}
            Change::Events(page) => {
                for event in &page.events {
                    if let EventData::FillChanged(preview) = &event.data
                        && self.is_newer(preview.id, event.revision)
                    {
                        self.update(event.revision, preview.clone());
                    }
                }
            }
        }
    }

    /// Whether a private resync has been applied: before it, the tracker holds only fills seen
    /// in events.
    pub fn is_synced(&self) -> bool {
        self.synced
    }

    /// The fill `id`, if held.
    pub fn get(&self, id: FillId) -> Option<&FillPreview> {
        self.fills.get(&id).map(|(_, preview)| preview)
    }

    /// Every fill held, in no particular order.
    pub fn iter(&self) -> impl Iterator<Item = &FillPreview> {
        self.fills.values().map(|(_, preview)| preview)
    }

    fn is_newer(&self, id: FillId, revision: Revision) -> bool {
        self.fills.get(&id).is_none_or(|(held, _)| revision > *held)
    }

    fn update(&mut self, revision: Revision, preview: FillPreview) {
        if self.is_newer(preview.id, revision) {
            self.fills.insert(preview.id, (revision, preview));
        }
    }
}

#[cfg(test)]
mod tests;