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};
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)
}
}
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))
}
}
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)
}
}
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)
}
}
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);
fn of_nanoseconds(nanos: i128) -> Decimal {
Decimal::new(flow_value::BigInt::from(nanos), -9)
.expect("nine places after the point is in range")
}
fn nanoseconds(seconds: &Decimal) -> Option<i128> {
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()
}
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))
}
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))
}
}
#[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)))
}
#[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))
}
}
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())
}
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)
}
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)
}
}
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);
#[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))
}
}