flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
Documentation
//! Reading `Instant` and `Duration` from ISO 8601 text.
//!
//! Writing them is `flow-value`'s text form, which is the canonical one.
//! Reading accepts more than that form writes, as decoding accepts any JSON
//! number syntax: an instant may carry an offset from UTC instead of `Z`, and
//! a duration may be written in weeks, days, hours and minutes as well as
//! seconds. Both are still exact, and neither is ever rounded.
//!
//! Units whose length depends on the calendar — years and months in a
//! duration — have no one length in seconds, so they are refused rather than
//! given one. A week is seven days of 86 400 seconds, as fixed as a day.

use flow_value::{Decimal, Duration, Instant};
use num_bigint::BigInt;
use num_integer::Integer;

const SECONDS_PER_DAY: i64 = 86_400;

/// The instant `text` writes: `[±]YYYY-MM-DDTHH:MM:SS[.fraction]` followed by
/// `Z` or an offset `±HH:MM`, on the proleptic Gregorian calendar with no leap
/// seconds. A year of more than four digits carries a sign. The `T` and `Z`
/// may be lowercase, as RFC 3339 §5.6 allows.
pub fn instant(text: &str) -> Option<Instant> {
    let mut cursor = Cursor(text);
    let sign = cursor.sign();
    let year = cursor.digits();
    if year.len() < 4 || (year.len() > 4 && sign.is_none()) {
        return None;
    }
    let year: BigInt = year.parse().ok()?;
    let year = if sign == Some(-1) { -year } else { year };
    cursor.expect('-')?;
    let month = cursor.fixed(2, 1, 12)?;
    cursor.expect('-')?;
    let day = cursor.fixed(2, 1, days_in_month(&year, month))?;
    if !(cursor.eat('T') || cursor.eat('t')) {
        return None;
    }
    let hour = cursor.fixed(2, 0, 23)?;
    cursor.expect(':')?;
    let minute = cursor.fixed(2, 0, 59)?;
    cursor.expect(':')?;
    let second = cursor.fixed(2, 0, 59)?;
    let fraction = if cursor.eat('.') {
        let digits = cursor.digits();
        if digits.is_empty() {
            return None;
        }
        decimal(&format!("0.{digits}"))?
    } else {
        decimal("0")?
    };
    let offset = if cursor.eat('Z') || cursor.eat('z') {
        0
    } else {
        let sign = cursor.sign()?;
        let hours = cursor.fixed(2, 0, 23)?;
        cursor.expect(':')?;
        let minutes = cursor.fixed(2, 0, 59)?;
        sign * (hours * 3600 + minutes * 60)
    };
    if !cursor.0.is_empty() {
        return None;
    }
    let days = days_from_civil(year, month, day);
    let whole = days * SECONDS_PER_DAY + (hour * 3600 + minute * 60 + second - offset);
    let seconds = Decimal::new(whole, 0).ok()?.add(&fraction).ok()?;
    Some(Instant::from_unix_seconds(seconds))
}

/// The duration `text` writes: `P`, optionally a count of weeks and `W` and a
/// count of days and `D`, then optionally `T` and at least one of hours `H`,
/// minutes `M` and seconds `S`, each a number that may carry a `-`; only the
/// seconds may have a fraction.
pub fn duration(text: &str) -> Option<Duration> {
    let mut cursor = Cursor(text);
    cursor.expect('P')?;
    let mut total = decimal("0")?;
    let mut any = false;
    for (unit, scale) in [('W', "604800"), ('D', "86400")] {
        if let Some(count) = cursor.component(unit, Fraction::Refused) {
            total = total.add(&count.mul(&decimal(scale)?).ok()?).ok()?;
            any = true;
        }
    }
    if cursor.eat('T') {
        let mut timed = false;
        for (unit, scale, fraction) in [
            ('H', "3600", Fraction::Refused),
            ('M', "60", Fraction::Refused),
            ('S', "1", Fraction::Allowed),
        ] {
            if let Some(count) = cursor.component(unit, fraction) {
                total = total.add(&count.mul(&decimal(scale)?).ok()?).ok()?;
                timed = true;
            }
        }
        if !timed {
            return None;
        }
        any = true;
    }
    if !any || !cursor.0.is_empty() {
        return None;
    }
    Some(Duration::from_seconds(total))
}

fn decimal(spelling: &str) -> Option<Decimal> {
    Decimal::parse(spelling)
}

struct Cursor<'t>(&'t str);

impl<'t> Cursor<'t> {
    fn eat(&mut self, expected: char) -> bool {
        match self.0.strip_prefix(expected) {
            Some(rest) => {
                self.0 = rest;
                true
            }
            None => false,
        }
    }

    fn expect(&mut self, expected: char) -> Option<()> {
        self.eat(expected).then_some(())
    }

    fn sign(&mut self) -> Option<i64> {
        if self.eat('+') {
            Some(1)
        } else if self.eat('-') {
            Some(-1)
        } else {
            None
        }
    }

    fn digits(&mut self) -> &'t str {
        let end = self
            .0
            .find(|c: char| !c.is_ascii_digit())
            .unwrap_or(self.0.len());
        let (digits, rest) = self.0.split_at(end);
        self.0 = rest;
        digits
    }

    /// Exactly `width` digits naming a number from `low` to `high`.
    fn fixed(&mut self, width: usize, low: i64, high: i64) -> Option<i64> {
        let digits = self.0.get(..width)?;
        if !digits.bytes().all(|byte| byte.is_ascii_digit()) {
            return None;
        }
        self.0 = &self.0[width..];
        let number: i64 = digits.parse().ok()?;
        (low..=high).contains(&number).then_some(number)
    }

    /// A number followed by `unit`, or `None`, with nothing read, when
    /// there is none here.
    fn component(&mut self, unit: char, fraction: Fraction) -> Option<Decimal> {
        let saved = self.0;
        let found = self.number(fraction).filter(|_| self.eat(unit));
        if found.is_none() {
            self.0 = saved;
        }
        found
    }

    /// Digits with an optional leading `-` and, when `fraction` allows it,
    /// a `.` and more digits.
    fn number(&mut self, fraction: Fraction) -> Option<Decimal> {
        let negative = self.eat('-');
        let whole = self.digits();
        if whole.is_empty() {
            return None;
        }
        let mut spelling = format!("{}{whole}", if negative { "-" } else { "" });
        if fraction == Fraction::Allowed && self.eat('.') {
            let digits = self.digits();
            if digits.is_empty() {
                return None;
            }
            spelling.push('.');
            spelling.push_str(digits);
        }
        decimal(&spelling)
    }
}

/// Whether a duration's number may have a fractional part: only its
/// seconds may.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Fraction {
    Allowed,
    Refused,
}

fn is_leap(year: &BigInt) -> bool {
    let divides = |n: u32| year.mod_floor(&BigInt::from(n)) == BigInt::from(0);
    divides(4) && (!divides(100) || divides(400))
}

fn days_in_month(year: &BigInt, month: i64) -> i64 {
    match month {
        2 if is_leap(year) => 29,
        2 => 28,
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}

/// The day number of `year-month-day` counted from 1970-01-01: Howard
/// Hinnant's `days_from_civil`, over 400-year eras so that only the era count
/// needs more than 64 bits.
fn days_from_civil(year: BigInt, month: i64, day: i64) -> BigInt {
    let year = if month <= 2 { year - 1 } else { year };
    let (era, year_of_era) = year.div_mod_floor(&BigInt::from(400));
    let year_of_era: i64 = i64::try_from(&year_of_era).expect("a remainder below 400");
    let shifted_month = if month > 2 { month - 3 } else { month + 9 };
    let day_of_year = (153 * shifted_month + 2) / 5 + day - 1;
    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
    era * 146_097 + day_of_era - 719_468
}