Cotton code
79 lines · 2.9 KB · RustRaw
//! Where an owner's message to a session got to, as typed facts.//!//! The engine fills two columns of a `session_message` row — `delivery`, one//! of [`Delivery`]'s values, and `delivered_on`, the Mac a delivered message//! reached — and the definition says the words (`labels` on the choice, the//! conversation's `footer` naming the columns). Nothing here composes a//! sentence: a rewording is data. The server's table read and the phone's//! `read.session` both answer through [`delivery`], so the two cannot disagree./// Where the owner's message stands. The strings are the `delivery` column's/// choices in `session_message.json`.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Delivery {    /// Open: no session has it yet.    Waiting,    /// Claimed by a session, not yet handled.    PickedUp,    /// Done on a session Cotton holds: the Mac holding it handed it over.    Delivered,    /// Done on a session Cotton only reads: handled at the session's own poll.    Done,    /// Refused; the refusal is the message's body.    Withdrawn,}impl Delivery {    pub fn as_str(self) -> &'static str {        match self {            Delivery::Waiting => "waiting",            Delivery::PickedUp => "picked_up",            Delivery::Delivered => "delivered",            Delivery::Done => "done",            Delivery::Withdrawn => "withdrawn",        }    }}/// The session a message is addressed to, as far as delivery needs it.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct Addressed<'a> {    /// Cotton holds this session's terminal (`cotton_sessions.host_owned`).    pub host_owned: bool,    /// The Mac it runs on (`cotton_sessions.machine`).    pub machine: Option<&'a str>,}/// A message's delivery facts: the state, and the Mac when it was delivered.#[derive(Debug, Clone, PartialEq, Eq)]pub struct DeliveryFacts {    pub delivery: Delivery,    pub delivered_on: Option<String>,}/// The delivery facts of one message, or `None` where there are none: a/// session's own message, or a status the table does not hold.pub fn delivery(from_kind: &str, status: &str, addressed: Option<Addressed<'_>>) -> Option<DeliveryFacts> {    if from_kind != "owner" {        return None;    }    let machine = addressed        .filter(|session| session.host_owned)        .and_then(|session| session.machine)        .map(str::trim)        .filter(|machine| !machine.is_empty());    let delivery = match (status, machine) {        ("open", _) => Delivery::Waiting,        ("claimed", _) => Delivery::PickedUp,        ("done", Some(_)) => Delivery::Delivered,        ("done", None) => Delivery::Done,        ("withdrawn", _) => Delivery::Withdrawn,        _ => return None,    };    let delivered_on = machine.filter(|_| delivery == Delivery::Delivered).map(str::to_string);    Some(DeliveryFacts { delivery, delivered_on })}#[cfg(test)]#[path = "session_delivery_tests.rs"]mod tests;