Cotton code
671 lines · 29.0 KB · RustRaw
//! The words a database's sync is said in (sync programme, lane A — the//! architect's brief of 12 Oct 2026, which replaces the four-string line).//!//! Under a database's cap there is always exactly one line, and sync has four//! things it may put there; when it has none, the line is the people line//! ("only you" / "with Bella") and [`Standing::words`] is empty://!//!   * `syncing · 62%` — more than [`SAY_ABOVE`] changes were owed when the//!     catch-up began. Fewer move without a word: the cap turns and that is//!     all ([`State::Moving`]).//!   * `copying · 400 MB to go` — the whole file is being copied instead//!     (lane C says so through [`HomeLine::copying`]; the string is here).//!   * `offline` — no Mac has answered for [`OFFLINE_AFTER_MS`].//!   * `update app` — the serving Mac refuses this build (`426`).//!   * `update your Mac` — the mirror: this build is NEWER than the serving//!     Mac's file, which takes nothing from it until the Mac is updated.//!//! "catching up", "up to date" and every count of changes are gone from the//! cap. The database page's top says the same things in a sentence//! ([`Standing::page`]) and the device row reads the same [`Standing`], with//! what each tool still has coming ([`Standing::coming`]: "Email · 41,000 of//! 58,900", "Everything else · up to date").//!//! THE PERCENT is `(sent + received) / (outbox + owed)`, both directions,//! bytes never counted — and every term in CHANGES (receipts), the unit the//! Mac counts what it owes in: a row arrives as several receipts, and some//! receipts are never sent at all (a phone's keep rules leave them out), so//! rows taken in would stop short of the whole. What counts as received is//! what the Mac's answers moved this device past (`ExchangeResponse::passed`).//! The whole is measured ONCE, at the start//! of the pass that found the device behind: the outbox as it stood, plus//! what the serving Mac counted it was owed (`owedAtStart`, counted exactly,//! once per catch-up, outside the Mac's write hold — architect's ruling,//! 07:45 IST). It moves only forward, and it is gone the moment the device//! is level, so the next catch-up starts from its own whole.//!//! A catch-up outlives the process: a phone catching up over hours is//! relaunched many times, so the catch-ups in flight — and when a Mac last//! answered — are kept in a small file of this device's own ([`store`],//! [`stored`]).//!//! One implementation, in the engine, so a Mac and a phone say the same//! words: [`HomeLine`] is fed each database's section of every pass, and the//! shell (`cotton-ffi`) puts [`HomeLine::standing`] on the frame and the//! status read.use std::collections::BTreeMap;use std::path::Path;use serde::{Deserialize, Serialize};/// What a catch-up's line starts with; the percent follows.pub const SYNCING: &str = "syncing";/// What a file copy's line starts with; what is left follows.pub const COPYING: &str = "copying";/// No Mac has answered for [`OFFLINE_AFTER_MS`].pub const OFFLINE: &str = "offline";/// The serving Mac refuses this build's exchanges (`426 upgrade_required`):/// nothing moves until this app is updated.pub const UPDATE_APP: &str = "update app";/// The serving Mac's file is on an OLDER schema than this build: what this/// device holds waits, whole, and goes on its own once the Mac is updated.pub const UPDATE_MAC: &str = "update your Mac";/// What a tool with nothing left to come is — on the device's own page, in/// "What is coming"; never under a cap.pub const UP_TO_DATE: &str = "up to date";/// A catch-up is said in words only when it began owing more than this many/// changes. Fewer are over before a percent could be read.pub const SAY_ABOVE: u64 = 2_000;/// How long no Mac must have answered before the line says [`OFFLINE`]. A/// missed pass is a blip — a lift, a tunnel — and a line that said so every/// time would be noise.pub const OFFLINE_AFTER_MS: i64 = 15 * 60 * 1000;/// The serving Mac counts what still waits after an answer only up to here/// (`cotton_core::constants::BEHIND_BY_CAP`, the server's own cap): a count/// below it is exact, a count at it means "at least this many".pub const COUNTED_UP_TO: u64 = cotton_core::constants::BEHIND_BY_CAP;/// How often, at most, the time a Mac last answered is written to this/// device's file while nothing else about its lines has changed.const ANSWER_KEPT_EVERY_MS: i64 = 5 * 60 * 1000;/// One database's section of a pass that answered.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub struct Answered {    /// CHANGES (receipts), like everything a percent is made of here — never    /// rows: a row arrives as several receipts, and the Mac counts what it    /// owes in receipts. Those of this device's outbox the pass handed over.    pub sent: u64,    /// Changes the Mac's answers moved this device past    /// (`ExchangeReport::passed`): what arrived and what was left out — by    /// this device's keep rules, as its own writes echoed — alike.    pub received: u64,    /// Changes still in this device's outbox when the pass ended.    pub unsent: u64,    /// What the Mac counted this device was owed when this catch-up began.    /// `None` until the Mac has counted, and from a Mac that does not.    pub owed_at_start: Option<u64>,    /// What the Mac said still waits after the pass's last answer, counted    /// up to [`COUNTED_UP_TO`]; `None` when it did not say.    pub remaining: Option<u64>,    /// The pass ended with more still to ask for.    pub behind: bool,}/// A catch-up in flight.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]struct CatchUp {    /// The outbox as it stood when the catch-up began.    outbox: u64,    /// Outbox plus owed, measured once; `None` until the Mac has counted.    whole: Option<u64>,    /// Changes sent and received since it began.    moved: u64,    /// How far through the line has said it is.    percent: u8,    /// It began owing more than [`SAY_ABOVE`], so it is said in words until    /// it is over — a line that fell silent at 97% would read as done.    said: bool,    /// What the Mac last said still waits.    #[serde(default)]    remaining: Option<u64>,}/// One table's part of a catch-up: changes the Mac's answers have moved this/// device past since it began, and how many the Mac counted it owed of that/// table at the start — both in receipts.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]struct TableCatchUp {    received: u64,    #[serde(default, skip_serializing_if = "Option::is_none")]    owed: Option<u64>,}/// What this device's file keeps of one database's line.#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]struct Kept {    #[serde(default, skip_serializing_if = "Option::is_none")]    catch_up: Option<CatchUp>,    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]    tables: BTreeMap<String, TableCatchUp>,    #[serde(default, skip_serializing_if = "Option::is_none")]    answered_at: Option<i64>,    #[serde(default, skip_serializing_if = "Option::is_none")]    synced_at: Option<i64>,    /// The first pass that went unanswered since the last answer — kept, so    /// "not reachable since" is the first failure across a relaunch, never    /// the first one this run saw (walker pass 4 offline, row 2).    #[serde(default, skip_serializing_if = "Option::is_none")]    silent_since: Option<i64>,    #[serde(default, skip_serializing_if = "Option::is_none")]    applied_at: Option<i64>,}/// Which of its lines a database is on.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "camelCase")]pub enum State {    /// Level. The people line; the cap is still.    Current,    /// Changes are moving, too few to say. The people line; the cap turns.    Moving,    Syncing,    Copying,    Offline,    UpdateApp,    /// This device is ahead of the serving Mac ([`UPDATE_MAC`]).    MacBehind,}/// Where one database's sync stands, as every surface reads it.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]#[serde(rename_all = "camelCase")]pub struct Standing {    pub state: State,    /// The line under the cap. Empty is the people line.    pub words: String,    /// The database page's top line. Empty when there is nothing to say —    /// and for [`State::Offline`] and [`State::MacBehind`], whose sentences    /// name a Mac (and a time of day), which the app that draws it knows.    pub page: String,    /// How far through a catch-up ([`State::Syncing`]) or a file copy    /// ([`State::Copying`]) — what the page's thin bar draws.    pub percent: Option<u8>,    /// Changes still to move in a catch-up whose whole is known.    pub to_go: Option<u64>,    /// Bytes still to copy, while [`State::Copying`].    pub bytes_to_go: Option<u64>,    /// When a Mac last answered (epoch milliseconds), while    /// [`State::Offline`]; `None` when none ever has.    pub since: Option<i64>,    /// What is coming, a line a tool that still has rows to come ("Email ·    /// 41,000 of 58,900"), the rest as one ("Everything else · up to date").    /// Never empty. What the device's own page lists.    pub coming: Vec<String>,}/// A copy of the whole file in flight: the bytes still to arrive, and the/// most that were ever said to be left — its whole, as far as the line knows.#[derive(Debug, Clone, Copy, PartialEq, Eq)]struct FileCopy {    to_go: u64,    whole: u64,}/// One database's line, kept across passes.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct HomeLine {    catch_up: Option<CatchUp>,    /// The catch-up in flight, by store table.    tables: BTreeMap<String, TableCatchUp>,    /// The Mac has said what the catch-up owed by table.    counted_by_table: bool,    copying: Option<FileCopy>,    /// When a Mac last answered for this database.    answered_at: Option<i64>,    /// Last exchange that left both directions level.    synced_at: Option<i64>,    /// When the passes since stopped answering.    silent_since: Option<i64>,    /// The serving Mac and this build disagree about the schema: which of    /// them is behind, said at once and kept until a pass answers.    refused: Option<super::SchemaStanding>,    /// When a pass last moved this device past any receipts.    applied_at: Option<i64>,    /// Receipts moved past since this process began, by store table —    /// `sync.status`'s "received since open"; never kept in the file.    since_open: BTreeMap<String, u64>,}impl HomeLine {    /// Raw observations for `read.sync_state`, including small backlogs the    /// cap's presentation deliberately keeps silent. Never includes outbox writes.    pub fn facts(&self) -> CopyFacts {        CopyFacts {            answered_at: self.answered_at,            synced_at: self.synced_at,            silent_since: self.silent_since,            remaining: self.catch_up.and_then(|running| running.remaining)                .or_else(|| (self.answered_at.is_some() && self.catch_up.is_none()).then_some(0)),            catching_up: self.catch_up.is_some(),            copying: self.copying.is_some(),            mac_answered_at: self.answered_at,            mac_silent_since: self.silent_since,        }    }    /// A pass answered for this database, at `now_ms`.    pub fn answered(&mut self, pass: Answered, now_ms: i64) {        self.answered_at = Some(now_ms);        if pass.received > 0 {            self.applied_at = Some(now_ms);        }        self.silent_since = None;        self.refused = None;        if !pass.behind && pass.remaining.unwrap_or(0) == 0 {            if pass.unsent == 0 { self.synced_at = Some(now_ms); }            // Level: the catch-up is over and its whole goes with it.            self.catch_up = None;            self.tables.clear();            self.counted_by_table = false;            return;        }        // The pass that found it behind measures the outbox as it stood        // before anything of it went.        let running = self.catch_up.get_or_insert(CatchUp {            outbox: pass.unsent.saturating_add(pass.sent),            ..CatchUp::default()        });        running.moved = running.moved.saturating_add(pass.sent).saturating_add(pass.received);        running.remaining = pass.remaining;        if running.whole.is_none() {            // MEASURED ONCE. The Mac's own count of the start when it has            // one; else, from a count small enough to be exact, what has            // moved plus what is left.            running.whole = match (pass.owed_at_start, pass.remaining) {                (Some(owed), _) => Some(owed.saturating_add(running.outbox)),                (None, Some(remaining)) if remaining < COUNTED_UP_TO => {                    Some(running.moved.saturating_add(remaining).saturating_add(pass.unsent))                }                _ => None,            };        }        // WHAT THE MAC SAYS IS LEFT, once that count is small enough to be        // exact, is a floor under what has moved: the whole less what still        // waits on either side. It holds whatever this device's own count        // missed — a Mac a build behind does not say what its pages left out        // — so the last stretch of a catch-up is never stuck short of its end.        if let (Some(whole), Some(remaining)) = (running.whole, pass.remaining) {            if remaining < COUNTED_UP_TO {                let left = remaining.saturating_add(pass.unsent);                running.moved = running.moved.max(whole.saturating_sub(left));            }        }        running.said |= running.whole.is_some_and(|whole| whole > SAY_ABOVE)            || pass.remaining.is_some_and(|remaining| remaining > SAY_ABOVE);        running.percent = running.percent.max(through(running.whole, running.moved));    }    /// The changes an answered pass moved this device past, by store table    /// (`ExchangeReport::passed` — receipts, as the Mac counts them), and — once the Mac    /// has counted it — what the catch-up owed of each table at its start.    /// Said straight after [`Self::answered`]; outside a catch-up it is    /// nothing to keep.    pub fn came(        &mut self,        received: &BTreeMap<String, usize>,        owed_by_table: Option<&BTreeMap<String, u64>>,    ) {        for (table, rows) in received {            let rows = u64::try_from(*rows).unwrap_or(u64::MAX);            let since = self.since_open.entry(table.clone()).or_default();            *since = since.saturating_add(rows);        }        if self.catch_up.is_none() {            return;        }        for (table, rows) in received {            let rows = u64::try_from(*rows).unwrap_or(u64::MAX);            let of = self.tables.entry(table.clone()).or_default();            of.received = of.received.saturating_add(rows);        }        // MEASURED ONCE, like the whole it sums to.        if let (false, Some(owed)) = (self.counted_by_table, owed_by_table) {            for (table, owed) in owed {                self.tables.entry(table.clone()).or_default().owed = Some(*owed);            }            self.counted_by_table = true;        }    }    /// A pass did not answer for this database, at `now_ms`. `refused` is    /// the Mac and this build disagreeing about the schema, which is said at    /// once; anything else is a blip until no Mac has answered for    /// [`OFFLINE_AFTER_MS`]. A catch-up in flight keeps its place either way.    pub fn unanswered(&mut self, refused: Option<super::SchemaStanding>, now_ms: i64) {        self.silent_since.get_or_insert(now_ms);        self.refused = refused;    }    /// The Mac answered no. Keep the backlog and last successful sync, while    /// recording contact independently of whether this database advanced.    pub fn contacted(&mut self, refused: Option<super::SchemaStanding>, now_ms: i64) {        self.answered_at = Some(now_ms);        self.silent_since = None;        self.refused = refused;    }    /// A copy of the whole file is in progress with `bytes_to_go` still to    /// arrive, or (`None`) there is none. Lane C's to say; a count of bytes    /// is never a part of the percent.    pub fn copying(&mut self, bytes_to_go: Option<u64>) {        let whole = self.copying.map_or(0, |copy| copy.whole);        self.copying = bytes_to_go.map(|to_go| FileCopy { to_go, whole: whole.max(to_go) });    }    /// Is this line at the same place as `other`, as far as this device's    /// file is concerned — the same catch-up at the same percent, and a last    /// answer not much newer? What decides whether the file is written again.    pub fn same_place(&self, other: &HomeLine) -> bool {        let kept = |line: &HomeLine| line.answered_at.map(|at| at.div_euclid(ANSWER_KEPT_EVERY_MS));        self.catch_up.map(|running| (running.whole, running.percent, running.said))            == other.catch_up.map(|running| (running.whole, running.percent, running.said))            && self.counted_by_table == other.counted_by_table            && kept(self) == kept(other)            && self.synced_at.map(|at| at.div_euclid(ANSWER_KEPT_EVERY_MS))                == other.synced_at.map(|at| at.div_euclid(ANSWER_KEPT_EVERY_MS))            && self.silent_since == other.silent_since    }    /// Where this database's sync stands at `now_ms`.    pub fn standing(&self, now_ms: i64) -> Standing {        let quiet = Standing {            state: State::Current,            words: String::new(),            page: String::new(),            percent: None,            to_go: None,            bytes_to_go: None,            since: None,            coming: self.coming(),        };        match self.refused {            Some(super::SchemaStanding::PhoneBehind) => {                return Standing {                    state: State::UpdateApp,                    words: UPDATE_APP.to_string(),                    page: "Update the app to sync again".to_string(),                    ..quiet                };            }            Some(super::SchemaStanding::ServerBehind) => {                return Standing {                    state: State::MacBehind,                    words: UPDATE_MAC.to_string(),                    ..quiet                };            }            None => {}        }        // No answer since the last one, or since the passes began to fail on        // a device no Mac has ever answered.        let silent_from = self.silent_since.map(|since| self.answered_at.unwrap_or(since));        if silent_from.is_some_and(|from| now_ms.saturating_sub(from) >= OFFLINE_AFTER_MS) {            return Standing {                state: State::Offline,                words: OFFLINE.to_string(),                since: self.answered_at,                ..quiet            };        }        if let Some(copy) = self.copying {            let left = megabytes(copy.to_go);            return Standing {                state: State::Copying,                words: format!("{COPYING} \u{00B7} {left} to go"),                page: format!("Copying your database \u{00B7} {left} to go"),                percent: Some(through(Some(copy.whole), copy.whole - copy.to_go)),                bytes_to_go: Some(copy.to_go),                ..quiet            };        }        let Some(running) = self.catch_up else { return quiet };        if !running.said {            return Standing { state: State::Moving, ..quiet };        }        // What is left of the whole — never less than the Mac says waits,        // and never nothing while the device is still behind.        let to_go = running.whole.map(|whole| {            whole.saturating_sub(running.moved).max(running.remaining.unwrap_or(0)).max(1)        });        let percent = running.percent;        Standing {            state: State::Syncing,            words: format!("{SYNCING} \u{00B7} {percent}%"),            page: match to_go {                Some(1) => format!("Syncing \u{00B7} {percent}% \u{00B7} 1 change to go"),                Some(to_go) => {                    format!("Syncing \u{00B7} {percent}% \u{00B7} {} changes to go", grouped(to_go))                }                None => format!("Syncing \u{00B7} {percent}%"),            },            percent: Some(percent),            to_go,            ..quiet        }    }    /// The line under the cap at `now_ms`; empty is the people line.    pub fn words(&self, now_ms: i64) -> String {        self.standing(now_ms).words    }    /// When a pass last moved this device past any receipts.    pub fn applied_at(&self) -> Option<i64> {        self.applied_at    }    /// Receipts moved past since this process began, by store table.    pub fn since_open(&self) -> &BTreeMap<String, u64> {        &self.since_open    }}/// The stored observation rather than the cap's presentation of it.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct CopyFacts {    pub answered_at: Option<i64>,    pub synced_at: Option<i64>,    pub silent_since: Option<i64>,    pub remaining: Option<u64>,    pub catching_up: bool,    pub copying: bool,    /// The serving Mac's contact as ONE fact per Mac (295 rule 16): when it    /// last answered any database it serves to this device, and the first    /// pass since that went unanswered ([`mac_contact`] over every line at    /// its origin). [`HomeLine::facts`] answers this line's own; the shell    /// fills the Mac's.    pub mac_answered_at: Option<i64>,    pub mac_silent_since: Option<i64>,}/// A failure stamped this soon after an answer is the same pass's: one/// database's section refused while the Mac answered the rest (each section/// is told the time it is reported, milliseconds apart).pub const SAME_PASS_MS: i64 = 5_000;/// ONE MAC'S CONTACT, from the lines of every database it serves to this/// device (295 rule 16 — Personal's Me said the Mac was not heard while/// another database's said "Up to date · synced 6 min ago" and Copies "heard/// just now", the relay unreachable): heard at the latest answer any of them/// had, and not heard since the first failure after it. A failure after the/// latest answer is the Mac's when it is the line that had that answer (a/// pass that cannot reach the Mac fails every section), or when it came/// later than [`SAME_PASS_MS`] after it; a section refused in a pass that/// answered the rest is that database's own, not the Mac's.pub fn mac_contact<'a>(lines: impl IntoIterator<Item = &'a HomeLine>) -> (Option<i64>, Option<i64>) {    let lines: Vec<&HomeLine> = lines.into_iter().collect();    let latest = lines.iter().filter(|line| line.answered_at.is_some()).max_by_key(|line| line.answered_at);    let Some(latest) = latest else {        return (None, lines.iter().filter_map(|line| line.silent_since).min());    };    let answered = latest.answered_at.unwrap_or_default();    let later = lines        .iter()        .filter_map(|line| line.silent_since)        .filter(|at| *at > answered.saturating_add(SAME_PASS_MS));    let silent = latest.silent_since.into_iter().chain(later).min();    (latest.answered_at, silent)}impl HomeLine {    /// What is coming, a line a tool: [`Standing::coming`].    fn coming(&self) -> Vec<String> {        let Some(running) = self.catch_up else {            return vec![format!("Everything \u{00B7} {UP_TO_DATE}")];        };        if !self.counted_by_table {            // The Mac has not said what is whose: one line for the lot.            return vec![match running.whole {                Some(whole) => format!(                    "Everything \u{00B7} {} of {}",                    grouped(running.moved.min(whole)),                    grouped(whole)                ),                None => "Everything \u{00B7} counting".to_string(),            }];        }        // By tool: what has come of what was owed. A table no tool's card        // stands for, and a tool with nothing left to come, is the rest.        let mut tools: BTreeMap<&'static str, (u64, u64)> = BTreeMap::new();        let mut rest = (0u64, 0u64);        for (table, of) in &self.tables {            let Some(owed) = of.owed else { continue };            let came = of.received.min(owed);            let sum = match cotton_core::rules::home_arrangement::tool_of_store_table(table) {                Some(tool) => tools.entry(tool).or_default(),                None => &mut rest,            };            sum.0 = sum.0.saturating_add(came);            sum.1 = sum.1.saturating_add(owed);        }        let mut waiting: Vec<(&str, u64, u64)> = Vec::new();        for (tool, (came, owed)) in tools {            if came < owed {                waiting.push((tool, came, owed));            } else {                rest.0 = rest.0.saturating_add(came);                rest.1 = rest.1.saturating_add(owed);            }        }        // Most still to come first.        waiting.sort_by_key(|(tool, came, owed)| (std::cmp::Reverse(owed - came), *tool));        let mut lines: Vec<String> = waiting            .into_iter()            .map(|(tool, came, owed)| {                format!("{tool} \u{00B7} {} of {}", grouped(came), grouped(owed))            })            .collect();        lines.push(if rest.0 < rest.1 {            let rest_is = if lines.is_empty() { "Everything" } else { "Everything else" };            format!("{rest_is} \u{00B7} {} of {}", grouped(rest.0), grouped(rest.1))        } else if lines.is_empty() {            // Every row the Mac counted at the start is here and it still            // says more waits: what arrived there since.            "Everything \u{00B7} finishing".to_string()        } else {            format!("Everything else \u{00B7} {UP_TO_DATE}")        });        lines    }}/// What this device's file keeps of `lines` — the catch-ups in flight and/// when a Mac last answered — written at `path`. Best effort: a file that/// cannot be written costs a relaunch its place in the percent, never a pass.pub fn store(path: &Path, lines: &BTreeMap<String, HomeLine>) {    let kept: BTreeMap<&str, Kept> = lines        .iter()        .map(|(database, line)| {            let kept = Kept {                catch_up: line.catch_up,                tables: line.tables.clone(),                answered_at: line.answered_at,                synced_at: line.synced_at,                silent_since: line.silent_since,                applied_at: line.applied_at,            };            (database.as_str(), kept)        })        .filter(|(_, kept)| *kept != Kept::default())        .collect();    if let Some(parent) = path.parent() {        let _ = std::fs::create_dir_all(parent);    }    if let Ok(body) = serde_json::to_string(&kept) {        // not a copy: the sync line's own small file.        let _ = std::fs::write(path, body);    }}/// What a previous run of this device left. No file, or one this build/// cannot read, is nothing in flight: the next pass measures afresh.pub fn stored(path: &Path) -> BTreeMap<String, HomeLine> {    std::fs::read_to_string(path)        .ok()        .and_then(|text| serde_json::from_str::<BTreeMap<String, Kept>>(&text).ok())        .unwrap_or_default()        .into_iter()        .map(|(database, kept)| {            let catch_up = kept                .catch_up                .map(|running| CatchUp { percent: running.percent.min(99), ..running });            let counted_by_table = kept.tables.values().any(|of| of.owed.is_some());            let line = HomeLine {                catch_up,                tables: if catch_up.is_some() { kept.tables } else { BTreeMap::new() },                counted_by_table,                answered_at: kept.answered_at,                synced_at: kept.synced_at,                silent_since: kept.silent_since,                applied_at: kept.applied_at,                ..HomeLine::default()            };            (database, line)        })        .collect()}/// How far through `whole` a catch-up or a copy that has moved `moved` of/// it is, in whole percent — never 100 while anything waits, and 0 until the/// whole is known.fn through(whole: Option<u64>, moved: u64) -> u8 {    let Some(whole) = whole.filter(|whole| *whole > 0) else { return 0 };    let percent = u128::from(moved.min(whole)) * 100 / u128::from(whole);    u8::try_from(percent.min(99)).unwrap_or(99)}/// `41000` as `41,000`.fn grouped(count: u64) -> String {    let digits = count.to_string();    let mut out = String::with_capacity(digits.len() + digits.len() / 3);    for (at, digit) in digits.chars().enumerate() {        if at > 0 && (digits.len() - at) % 3 == 0 {            out.push(',');        }        out.push(digit);    }    out}/// A count of bytes as a person reads it: whole megabytes (never "0 MB"/// while anything is left), and gigabytes to one place from a thousand of/// them.fn megabytes(bytes: u64) -> String {    let megabytes = bytes.div_ceil(1_000_000).max(1);    if megabytes < 1_000 {        return format!("{megabytes} MB");    }    let tenths = bytes.div_ceil(100_000_000);    format!("{}.{} GB", tenths / 10, tenths % 10)}#[cfg(test)]#[path = "line_tests.rs"]mod tests;