Cotton code
237 lines · 9.4 KB · RustRaw
//! Computed columns' arithmetic: what a formula makes of a record's values//! and what a rollup makes of the values of the records linking here. Which//! records and values those are is the host's to gather (the phone's cache,//! its store, the Worker's rows); what they add up to is decided here, once.//!//! Vectors: `vectors/computed.json`.use serde::{Deserialize, Serialize};use serde_json::{json, Value};/// What a formula does with the columns it names.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum FormulaOp {    /// The numbers among the values, added; empty when none is a number.    Sum,    /// The first number less every later number; empty while the first is    /// (an absent number is not zero), and an empty later one takes nothing.    Difference,    /// The mathematical sign of one number: -1, 0 or 1.    Sign,    /// One number or amount, turned over while `flip_when` holds.    Signed,    /// The non-empty words of the values, `separator` between them (absent:    /// one space); empty when none has words.    Join,}/// What a rollup makes of the values of the records that link here.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum RollupOp {    Count,    Sum,    Min,    Max,    First,    Latest,    Average,}/// A whole f64 as a whole number, so `2.0` reads `2` on every side.pub fn number(n: f64) -> Value {    if n.fract() == 0.0 && n.abs() < 9.0e15 {        json!(n as i64)    } else {        json!(n)    }}/// Whole numbers stay whole (saturating); one fraction makes the total a float.pub fn sum_numbers<'a>(values: impl Iterator<Item = &'a Value>) -> Value {    let mut whole: i64 = 0;    let mut fraction: f64 = 0.0;    let mut any_fraction = false;    for value in values {        if let Some(n) = value.as_i64() {            whole = whole.saturating_add(n);        } else if let Some(f) = value.as_f64() {            any_fraction = true;            fraction += f;        }    }    if any_fraction {        number(whole as f64 + fraction)    } else {        json!(whole)    }}/// A value as the words a `join` joins and a `where` compares.pub fn words_of(value: &Value) -> Option<String> {    match value {        Value::String(words) => Some(words.clone()),        Value::Number(number) => Some(number.to_string()),        Value::Bool(yes) => Some(yes.to_string()),        _ => None,    }}/// A formula over the values its `of` names, in order. `flip` is whether the/// record's `flip_when` holds (`signed` only); `separator` is `join`'s.pub fn formula(op: FormulaOp, values: &[Value], flip: bool, separator: Option<&str>) -> Value {    let numbers = || values.iter().filter(|value| value.is_number());    match op {        FormulaOp::Sum => {            if numbers().next().is_none() {                return Value::Null;            }            sum_numbers(numbers())        }        FormulaOp::Difference => {            let Some(first) = values.first().filter(|value| value.is_number()) else {                return Value::Null;            };            let rest: Vec<&Value> = values.iter().skip(1).filter(|value| value.is_number()).collect();            match (first.as_i64(), rest.iter().map(|value| value.as_i64()).collect::<Option<Vec<i64>>>()) {                (Some(first), Some(rest)) => json!(rest.into_iter().fold(first, i64::saturating_sub)),                _ => number(rest.iter().filter_map(|value| value.as_f64()).fold(first.as_f64().unwrap_or(0.0), |acc, b| acc - b)),            }        }        FormulaOp::Sign => match values.first().and_then(Value::as_f64) {            Some(n) if n > 0.0 => json!(1),            Some(n) if n < 0.0 => json!(-1),            Some(_) => json!(0),            None => Value::Null,        },        FormulaOp::Signed => {            let Some(value) = values.first().filter(|value| value.is_number()) else {                return Value::Null;            };            if !flip {                return value.clone();            }            match value.as_i64() {                Some(whole) => json!(whole.saturating_neg()),                None => number(-value.as_f64().unwrap_or(0.0)),            }        }        FormulaOp::Join => {            let words: Vec<String> = values.iter().filter_map(words_of).filter(|words| !words.trim().is_empty()).collect();            if words.is_empty() {                Value::Null            } else {                json!(words.join(separator.unwrap_or(" ")))            }        }    }}/// A rollup over the gathered records: `count` of them, and `values` the/// rolled-up column's value of each, in the order the host gathered them/// (first and latest take the ends of that order).pub fn rollup(op: RollupOp, count: usize, values: &[Value]) -> Value {    let numbers: Vec<&Value> = values.iter().filter(|value| value.is_number()).collect();    let mut texts: Vec<&str> = values.iter().filter_map(Value::as_str).filter(|text| !text.is_empty()).collect();    texts.sort_unstable();    let extreme = |pick_max: bool| -> Value {        let picked = numbers.iter().filter_map(|value| value.as_f64().map(|n| (n, *value))).reduce(|a, b| {            let keep_b = if pick_max { b.0 > a.0 } else { b.0 < a.0 };            if keep_b { b } else { a }        });        match picked {            Some((_, value)) => value.clone(),            None => {                let text = if pick_max { texts.last() } else { texts.first() };                text.map_or(Value::Null, |text| json!(text))            }        }    };    match op {        RollupOp::Count => json!(count),        RollupOp::Sum => sum_numbers(numbers.into_iter()),        RollupOp::Min => extreme(false),        RollupOp::Max => extreme(true),        RollupOp::Average => {            if numbers.is_empty() {                return Value::Null;            }            let total: f64 = numbers.iter().filter_map(|value| value.as_f64()).sum();            number(total / numbers.len() as f64)        }        RollupOp::First => values.first().cloned().unwrap_or(Value::Null),        RollupOp::Latest => values.last().cloned().unwrap_or(Value::Null),    }}/// The most decimals a reading may name.pub const MOST_DECIMALS: u32 = 6;/// A number as a person writes it in a reading: rounded half-up (away from/// zero) to `decimals` places, or to 2 when none is named, with trailing/// zeros dropped, so a whole number stays whole ("12", never "12.0") and an/// average reads "4.7". Only the reading rounds; the stored value never does./// Rounded on the number's shortest decimal spelling, so 1.005 to 2 places/// is "1.01", as written, not "1" as its binary neighbour would round.pub fn figure(n: f64, decimals: Option<u32>) -> String {    if !n.is_finite() {        return n.to_string();    }    let places = decimals.unwrap_or(2).min(MOST_DECIMALS) as usize;    let spelled = format!("{}", n.abs());    let (whole, fraction) = spelled.split_once('.').unwrap_or((&spelled, ""));    let mut digits: Vec<u8> = whole.bytes().chain(fraction.bytes().chain(std::iter::repeat(b'0')).take(places)).map(|b| b - b'0').collect();    if fraction.as_bytes().get(places).is_some_and(|next| *next >= b'5') {        let mut at = digits.len();        loop {            if at == 0 {                digits.insert(0, 1);                break;            }            at -= 1;            if digits[at] == 9 {                digits[at] = 0;            } else {                digits[at] += 1;                break;            }        }    }    let split = digits.len() - places;    let whole: String = digits[..split].iter().map(|d| char::from(b'0' + d)).collect();    let fraction: String = digits[split..].iter().map(|d| char::from(b'0' + d)).collect();    let fraction = fraction.trim_end_matches('0');    let whole = whole.trim_start_matches('0');    let whole = if whole.is_empty() { "0" } else { whole };    let unsigned = if fraction.is_empty() { whole.to_string() } else { format!("{whole}.{fraction}") };    if n < 0.0 && unsigned != "0" { format!("-{unsigned}") } else { unsigned }}#[cfg(test)]mod tests {    use super::*;    /// RULE: a formula and a rollup answer what the shared vectors say, here,    /// on the phone and on the Worker (`vectors/computed.json`).    #[test]    fn computed_columns_answer_the_shared_vectors() {        let file: Value = serde_json::from_str(include_str!("../vectors/computed.json")).unwrap();        for case in file["formula"].as_array().unwrap() {            let op: FormulaOp = serde_json::from_value(case["op"].clone()).unwrap();            let values = case["values"].as_array().unwrap();            let got = formula(op, values, case["flip"] == json!(true), case["separator"].as_str());            assert_eq!(got, case["want"], "{case}");        }        for case in file["rollup"].as_array().unwrap() {            let op: RollupOp = serde_json::from_value(case["op"].clone()).unwrap();            let values = case["values"].as_array().unwrap();            let count = case["count"].as_u64().map_or(values.len(), |n| n as usize);            assert_eq!(rollup(op, count, values), case["want"], "{case}");        }        for case in file["figure"].as_array().unwrap() {            let decimals = case["decimals"].as_u64().map(|d| d as u32);            assert_eq!(json!(figure(case["value"].as_f64().unwrap(), decimals)), case["want"], "{case}");        }    }}