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
//! The Rust types that map to a Flow type without a message's codec of
//! their own, and [`wire_impl!`](crate::wire_impl!), which gives a type
//! defined elsewhere its [`Shape`] and its [`Shaped`] mapping from its
//! field list.
//!
//! A value crosses as a value of the Flow type its form projects to,
//! written and read part by part ([`crate::crossing`]). A native type that
//! holds less than its Flow type, such as a `std::time::Duration`, which
//! cannot be negative, has no Rust value for the Flow values it cannot
//! hold.

use std::collections::{BTreeMap, BTreeSet};
use std::convert::Infallible;

use flow_value::{Decimal, Duration, Instant};

use crate::catalog::StdForm;
use crate::error::{DecodeError, EncodeError};
use crate::form::{Form, form};

use super::{Shaped, Type, ValueReader, ValueWriter, WireForm, form_of};

/// A scalar: its form, and the writer and reader of its value.
macro_rules! scalar {
    ($rust:ty, $form:ident, $write:ident) => {
        impl Shaped for $rust {
            const FORM: WireForm = WireForm::$form;

            fn write_at(
                &self,
                out: &mut ValueWriter<'_, '_>,
                ty: &Type,
            ) -> Result<(), EncodeError> {
                out.$write(ty, self)
            }

            fn read_at(
                input: &mut ValueReader<'_, '_, '_>,
                ty: &Type,
            ) -> Result<Self, DecodeError> {
                input.$write(ty)
            }
        }
    };
}

scalar!(Decimal, Decimal, decimal);
scalar!(Duration, Duration, duration);

impl Shaped for () {
    const FORM: WireForm = WireForm::Unit;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.unit(ty)
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.unit(ty)
    }
}

/// `Never`, which has no values.
impl Shaped for Infallible {
    const FORM: WireForm = WireForm::Never;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        let _ = (out, ty);
        match *self {}
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        Err(input.mismatch(ty))
    }
}

/// A set, its values in Flow's order whatever Rust's is.
impl<T: Shaped + Ord> Shaped for BTreeSet<T> {
    const FORM: WireForm = WireForm::Set(form_of::<T>);

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.set(ty, self.iter())
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.set(ty)
    }
}

/// A dictionary, its entries in Flow's order of its keys whatever Rust's is.
impl<K: Shaped + Ord, V: Shaped> Shaped for BTreeMap<K, V> {
    const FORM: WireForm = WireForm::Dict(form_of::<K>, form_of::<V>);

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.dict(ty, self.iter())
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.dict(ty)
    }
}

/// A tuple of its parts' forms, in order.
macro_rules! tuple {
    ($($part:ident $index:tt),+) => {
        impl<$($part: Shaped),+> Shaped for ($($part,)+) {
            const FORM: WireForm =
                WireForm::Tuple(&[$(form_of::<$part>),+]);

            fn write_at(
                &self,
                out: &mut ValueWriter<'_, '_>,
                ty: &Type,
            ) -> Result<(), EncodeError> {
                out.tuple(ty, &[$(&self.$index),+])
            }

            fn read_at(
                input: &mut ValueReader<'_, '_, '_>,
                ty: &Type,
            ) -> Result<Self, DecodeError> {
                input.tuple(ty, |input, parts| Ok(($(parts.read::<$part>(input)?,)+)))
            }
        }
    };
}

tuple!(A 0, B 1);
tuple!(A 0, B 1, C 2);
tuple!(A 0, B 1, C 2, D 3);
tuple!(A 0, B 1, C 2, D 3, E 4);
tuple!(A 0, B 1, C 2, D 3, E 4, F 5);
tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6);
tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7);

/// `nanos` nanoseconds as exact decimal seconds.
fn of_nanoseconds(nanos: i128) -> Decimal {
    Decimal::new(flow_value::BigInt::from(nanos), -9)
        .expect("nine places after the point is in range")
}

/// `seconds` as whole nanoseconds, when it is a whole number of them
/// that an `i128` holds.
fn nanoseconds(seconds: &Decimal) -> Option<i128> {
    // 10^39 nanoseconds is past every `i128`, whatever the coefficient.
    let shift = u32::try_from(seconds.exponent().checked_add(9)?)
        .ok()
        .filter(|shift| *shift < 39)?;
    i128::try_from(seconds.coefficient() * flow_value::BigInt::from(10u8).pow(shift)).ok()
}

/// The `std::time::Duration` of `nanos` nanoseconds, when it is one.
fn std_duration(nanos: i128) -> Option<std::time::Duration> {
    let nanos = u128::try_from(nanos).ok()?;
    let seconds = u64::try_from(nanos / 1_000_000_000).ok()?;
    let subsecond = u32::try_from(nanos % 1_000_000_000).ok()?;
    Some(std::time::Duration::new(seconds, subsecond))
}

/// `duration.Duration`, as a length its Rust type can hold: one that is
/// negative or finer than a nanosecond is none.
impl Shaped for std::time::Duration {
    const FORM: WireForm = WireForm::Duration;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        let nanos = i128::try_from(self.as_nanos()).map_err(|_| out.refuse(ty))?;
        out.duration(ty, &Duration::from_seconds(of_nanoseconds(nanos)))
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        std_duration(nanoseconds(input.duration(ty)?.seconds()).ok_or_else(|| input.mismatch(ty))?)
            .ok_or_else(|| input.mismatch(ty))
    }
}

/// The exact `Instant` `time` is: its nanoseconds since the epoch,
/// before it negative; none past what an `i128` of nanoseconds holds.
#[expect(
    clippy::disallowed_types,
    reason = "a time a Tool takes or answers is converted here; no clock is read"
)]
pub fn instant_of(time: std::time::SystemTime) -> Option<Instant> {
    let nanos = match time.duration_since(std::time::UNIX_EPOCH) {
        Ok(after) => i128::try_from(after.as_nanos()).ok()?,
        Err(before) => -i128::try_from(before.duration().as_nanos()).ok()?,
    };
    Some(Instant::from_unix_seconds(of_nanoseconds(nanos)))
}

/// `time.Instant`, as an instant the platform's clock can hold.
#[expect(
    clippy::disallowed_types,
    reason = "a time a Tool takes or answers is converted here; no clock is read"
)]
impl Shaped for std::time::SystemTime {
    const FORM: WireForm = WireForm::Instant;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.instant(ty, &instant_of(*self).ok_or_else(|| out.refuse(ty))?)
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        let nanos = nanoseconds(input.instant(ty)?.unix_seconds());
        let time = nanos.and_then(|nanos| {
            let length = std_duration(nanos.checked_abs()?)?;
            if nanos < 0 {
                std::time::UNIX_EPOCH.checked_sub(length)
            } else {
                std::time::UNIX_EPOCH.checked_add(length)
            }
        });
        time.ok_or_else(|| input.mismatch(ty))
    }
}

/// Writes `text` at `ty`, the std type held to `held`.
fn write_held(
    out: &mut ValueWriter<'_, '_>,
    ty: &Type,
    held: StdForm,
    text: &str,
) -> Result<(), EncodeError> {
    if !matches!(form(out.catalog(), ty), Form::Newtype(_, Some(form)) if form == held) {
        return Err(out.refuse(ty));
    }
    out.newtype(ty, &text.to_owned())
}

/// Reads the text of a value of `ty`, the std type held to `held`.
fn read_held(
    input: &mut ValueReader<'_, '_, '_>,
    ty: &Type,
    held: StdForm,
) -> Result<String, DecodeError> {
    if !matches!(form(input.catalog(), ty), Form::Newtype(_, Some(form)) if form == held) {
        return Err(input.mismatch(ty));
    }
    input.newtype(ty)
}

/// `path.Path`: its normal text, its components joined by `/` whatever
/// the host's separator, so a path that is not UTF-8 is none.
impl Shaped for std::path::PathBuf {
    const FORM: WireForm = WireForm::Std {
        module: "path",
        name: "Path",
        args: &[],
    };

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        let text = self.to_str().ok_or_else(|| out.refuse(ty))?;
        let text = text.replace(std::path::MAIN_SEPARATOR, "/");
        write_held(out, ty, StdForm::Path, &flow_types::normal_path(&text))
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        read_held(input, ty, StdForm::Path).map(std::path::PathBuf::from)
    }
}

/// A std type held to a form of its own, as its normal text.
macro_rules! held {
    ($rust:ty, $module:literal, $name:literal, $form:ident) => {
        impl Shaped for $rust {
            const FORM: WireForm = WireForm::Std {
                module: $module,
                name: $name,
                args: &[],
            };

            fn write_at(
                &self,
                out: &mut ValueWriter<'_, '_>,
                ty: &Type,
            ) -> Result<(), EncodeError> {
                write_held(out, ty, StdForm::$form, &self.to_string())
            }

            fn read_at(
                input: &mut ValueReader<'_, '_, '_>,
                ty: &Type,
            ) -> Result<Self, DecodeError> {
                let text = read_held(input, ty, StdForm::$form)?;
                <$rust>::parse(&text).ok_or_else(|| input.mismatch(ty))
            }
        }
    };
}

held!(crate::Url, "url", "Url", Url);
held!(crate::MediaType, "media", "MediaType", MediaType);

/// The place-holder a declaration's type parameter numbered `INDEX` is
/// written as in its [`Shape`](super::Shape): it has no values.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Param<const INDEX: usize>(Infallible);

impl<const INDEX: usize> Shaped for Param<INDEX> {
    const FORM: WireForm = WireForm::Param(INDEX);

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        let _ = (out, ty);
        match self.0 {}
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        Err(input.mismatch(ty))
    }
}