psicose 0.2.3

no_std, heapless reliable byte transport: 1-byte payload, 4-byte frame, stop-and-wait and windowed (N ≤ 8).
Documentation
//! Cooperative session pump: one RX step, one TX step, never a loop.
//!
//! ```text
//!                    PSICOSE SESSION
//! ┌──────────────────────────────────────────────┐
//! │  Sender (TxState)     Receiver (RxState)     │
//! │                 └── Pump ──┘                 │
//! └───────────────────┬──────────────────────────┘
//!                     │
//!               TYPE|SEQ|DATA|CRC
//! ```
//!
//! [`Pump::poll`] returns immediately. The caller decides when to call
//! again. [`Pump::send_all`] is only that loop stacked on top.

use crate::error::Error;
use crate::rx::{PollOutcome, Receiver};
use crate::stream::StreamError;
use crate::timeout::RetryPolicy;
use crate::transport::{ByteSource, ByteTransport};
use crate::tx::{Sender, TxPoll, TxState};

/// Session counters. `Copy`, stack-only, no logging.
///
/// These fields are the future PSICOSE-8 registers (`BYTES_*`, `RETRIES`,
/// `NACKS`, `CRC_ERRORS`, `DUPLICATES`) without turning the runtime into
/// a VM.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SessionStats {
    /// Payload bytes the receiver delivered (after the ACK was written).
    pub bytes_delivered: u32,
    /// Frames whose four bytes fully left the sender `OutBuf`.
    pub frames_sent: u32,
    /// Times the sender entered retransmission.
    pub retries: u32,
    /// NACKs generated by the receiver.
    pub nacks: u32,
    /// Duplicate DATA frames the receiver re-ACKed without delivering.
    pub duplicates: u32,
    /// Frames the receiver rejected for CRC (also counted in [`Self::nacks`]).
    pub crc_errors: u32,
    /// How many times [`Pump::poll`] was called.
    pub ticks: u64,
}

impl SessionStats {
    /// All counters at zero. `const` twin of `Default::default()`.
    pub const fn new() -> Self {
        SessionStats {
            bytes_delivered: 0,
            frames_sent: 0,
            retries: 0,
            nacks: 0,
            duplicates: 0,
            crc_errors: 0,
            ticks: 0,
        }
    }
}

/// Outcome of one cooperative [`Pump::poll`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PumpEvent {
    /// Both sides were quiet.
    Idle,
    /// Work happened (write, retry, START, NACK, …) without a payload event.
    Progress,
    /// A DATA byte was ACKed on the sender.
    Sent,
    /// A new payload byte was delivered on the receiver.
    Received(u8),
    /// FINISH was completed on either side.
    Completed,
    /// ABORT cancelled the session.
    Aborted,
}

/// One session: a [`Sender`] and a [`Receiver`] driven by the same poll.
///
/// `Rx::Error` must be the same type as `Tx::Error` so a single
/// [`Error`] covers the pair.
pub struct Pump<Tx, Rx>
where
    Tx: ByteTransport,
    Rx: ByteTransport<Error = Tx::Error>,
{
    tx: Sender<Tx>,
    rx: Receiver<Rx>,
    stats: SessionStats,
    last_acked: bool,
}

impl<Tx, Rx> Pump<Tx, Rx>
where
    Tx: ByteTransport,
    Rx: ByteTransport<Error = Tx::Error>,
{
    /// Wraps an existing sender/receiver pair.
    pub fn new(tx: Sender<Tx>, rx: Receiver<Rx>) -> Self {
        Pump {
            tx,
            rx,
            stats: SessionStats::default(),
            last_acked: false,
        }
    }

    /// A pump on raw transports: `Pump::on(uart_tx, uart_rx)`.
    pub fn on(tx: Tx, rx: Rx) -> Self {
        Self::new(Sender::new(tx), Receiver::new(rx))
    }

    /// [`Self::on`] with an explicit [`RetryPolicy`].
    pub fn on_with(tx: Tx, rx: Rx, policy: RetryPolicy) -> Self {
        Self::new(Sender::with_policy(tx, policy), Receiver::new(rx))
    }

    /// Current counters. Copy them; the pump keeps owning the live set.
    pub fn stats(&self) -> SessionStats {
        self.stats
    }

    /// The sender.
    pub fn sender(&self) -> &Sender<Tx> {
        &self.tx
    }

    /// The sender, mutably (for `offer` / `offer_start` / `offer_finish`).
    pub fn sender_mut(&mut self) -> &mut Sender<Tx> {
        &mut self.tx
    }

    /// The receiver.
    pub fn receiver(&self) -> &Receiver<Rx> {
        &self.rx
    }

    /// The receiver, mutably.
    pub fn receiver_mut(&mut self) -> &mut Receiver<Rx> {
        &mut self.rx
    }

    /// Cancels the session: drops any in-flight TX frame and sends ABORT.
    pub fn abort(&mut self) -> Result<(), Error<Tx::Error>> {
        self.tx.offer_abort()
    }

    /// One non-blocking step: RX first, then TX. Never loops.
    ///
    /// 1. Give RX a chance (ACK/NACK/ABORT/DATA).
    /// 2. If RX accepted ABORT, locally cancel TX (do not send a second ABORT).
    /// 3. Let TX write or wait.
    /// 4. Return immediately.
    pub fn poll(&mut self) -> Result<PumpEvent, Error<Tx::Error>> {
        self.stats.ticks = self.stats.ticks.saturating_add(1);

        let rx = self.rx.poll()?;
        match rx {
            PollOutcome::Delivered(_) => {
                self.stats.bytes_delivered = self.stats.bytes_delivered.saturating_add(1);
            }
            PollOutcome::DuplicateIgnored => {
                self.stats.duplicates = self.stats.duplicates.saturating_add(1);
            }
            PollOutcome::Rejected => {
                self.stats.nacks = self.stats.nacks.saturating_add(1);
            }
            PollOutcome::CrcRejected => {
                self.stats.nacks = self.stats.nacks.saturating_add(1);
                self.stats.crc_errors = self.stats.crc_errors.saturating_add(1);
            }
            PollOutcome::Aborted => {
                // Peer abort cancels DATA. Do not kill our own ABORT/START
                // handshake — RX may still emit Aborted while finishing ACK 0.
                if !self.tx.holds_session_control() {
                    self.tx.force_abort();
                }
            }
            PollOutcome::Pending
            | PollOutcome::Started
            | PollOutcome::TransferFinished => {}
        }

        let tx = self.tx.poll()?;
        self.last_acked = matches!(tx, TxPoll::Acked);
        let mark = self.tx.take_mark();
        if mark.frame_on_wire {
            self.stats.frames_sent = self.stats.frames_sent.saturating_add(1);
        }
        if mark.retransmit {
            self.stats.retries = self.stats.retries.saturating_add(1);
        }

        if matches!(rx, PollOutcome::Aborted) || matches!(tx, TxPoll::Aborted) {
            return Ok(PumpEvent::Aborted);
        }
        if matches!(rx, PollOutcome::TransferFinished) || matches!(tx, TxPoll::TransferDone) {
            return Ok(PumpEvent::Completed);
        }
        if let PollOutcome::Delivered(byte) = rx {
            return Ok(PumpEvent::Received(byte));
        }
        if matches!(tx, TxPoll::Acked) {
            return Ok(PumpEvent::Sent);
        }

        let progress = !matches!(rx, PollOutcome::Pending)
            || !matches!(tx, TxPoll::Pending)
            || mark.frame_on_wire
            || mark.retransmit
            || mark.nack;
        if progress {
            Ok(PumpEvent::Progress)
        } else {
            Ok(PumpEvent::Idle)
        }
    }

    /// Drain `src` through the pump, then FINISH. Convenience over [`Self::poll`].
    ///
    /// Returns how many DATA bytes the peer ACKed. On a single-thread pair
    /// this works because each poll serves RX (so ACKs are written) and TX.
    pub fn send_all<S: ByteSource>(
        &mut self,
        src: &mut S,
    ) -> Result<u64, StreamError<Tx::Error, S::Error>> {
        let mut n = 0u64;
        let mut hold = None;
        let mut exhausted = false;
        let mut finish_offered = false;
        loop {
            if hold.is_none() && !exhausted {
                match src.read_byte().map_err(StreamError::Application)? {
                    Some(b) => hold = Some(b),
                    None => exhausted = true,
                }
            }
            if self.tx.state() == TxState::Idle {
                if let Some(b) = hold.take() {
                    self.tx.offer(b).map_err(StreamError::Protocol)?;
                } else if exhausted && !finish_offered {
                    match self.tx.offer_finish() {
                        Ok(()) => finish_offered = true,
                        Err(Error::NotIdle) => {}
                        Err(e) => return Err(StreamError::Protocol(e)),
                    }
                }
            }
            let ev = self.poll().map_err(StreamError::Protocol)?;
            if self.last_acked {
                n = n.saturating_add(1);
            }
            match ev {
                PumpEvent::Completed => return Ok(n),
                PumpEvent::Aborted => return Err(StreamError::Protocol(Error::Aborted)),
                PumpEvent::Idle
                | PumpEvent::Progress
                | PumpEvent::Sent
                | PumpEvent::Received(_) => {}
            }
        }
    }
}