Skip to main content

zaun_community_protocol/client/cursors/
cursor.rs

1//! One stream's cursor and the events held behind a gap.
2
3use std::collections::BTreeMap;
4
5use crate::envelope::EventEnvelope;
6use crate::event::Event;
7
8/// An event waiting for its turn; `event` is `None` for unknown or malformed types, which
9/// only advance the cursor (ยง9.4).
10#[derive(Debug, Clone)]
11pub(in crate::client) struct Held {
12    pub(in crate::client) envelope: EventEnvelope,
13    pub(in crate::client) event: Option<Event>,
14}
15
16/// One stream's position: the highest contiguous sequence applied, and events held aside.
17#[derive(Debug, Clone, Default)]
18pub struct Cursor {
19    pub(super) applied: u64,
20    pub(super) held: BTreeMap<u64, Held>,
21}
22
23impl Cursor {
24    /// The highest contiguous sequence applied.
25    #[must_use]
26    pub const fn applied(&self) -> u64 {
27        self.applied
28    }
29
30    /// Events held aside behind a gap.
31    #[must_use]
32    pub fn held(&self) -> usize {
33        self.held.len()
34    }
35
36    /// Releases held events that are now contiguous, advancing the cursor.
37    pub(super) fn release(&mut self) -> Vec<Held> {
38        self.held = self.held.split_off(&self.applied.saturating_add(1));
39        let mut ready = Vec::new();
40        while let Some(next) = self.held.remove(&self.applied.saturating_add(1)) {
41            self.applied = self.applied.saturating_add(1);
42            ready.push(next);
43        }
44        ready
45    }
46}