Skip to main content

flow_abi/wire/
shaped.rs

1//! The Rust types that map to a Flow type without a message's codec of
2//! their own, and [`wire_impl!`](crate::wire_impl!), which gives a type
3//! defined elsewhere its [`Shape`] and its [`Shaped`] mapping from its
4//! field list.
5//!
6//! A value crosses as a value of the Flow type its form projects to,
7//! written and read part by part ([`crate::crossing`]). A native type that
8//! holds less than its Flow type, such as a `std::time::Duration`, which
9//! cannot be negative, has no Rust value for the Flow values it cannot
10//! hold.
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::convert::Infallible;
14
15use flow_value::{Decimal, Duration, Instant};
16
17use crate::catalog::StdForm;
18use crate::error::{DecodeError, EncodeError};
19use crate::form::{Form, form};
20
21use super::{Shaped, Type, ValueReader, ValueWriter, WireForm, form_of};
22
23/// A scalar: its form, and the writer and reader of its value.
24macro_rules! scalar {
25    ($rust:ty, $form:ident, $write:ident) => {
26        impl Shaped for $rust {
27            const FORM: WireForm = WireForm::$form;
28
29            fn write_at(
30                &self,
31                out: &mut ValueWriter<'_, '_>,
32                ty: &Type,
33            ) -> Result<(), EncodeError> {
34                out.$write(ty, self)
35            }
36
37            fn read_at(
38                input: &mut ValueReader<'_, '_, '_>,
39                ty: &Type,
40            ) -> Result<Self, DecodeError> {
41                input.$write(ty)
42            }
43        }
44    };
45}
46
47scalar!(Decimal, Decimal, decimal);
48scalar!(Duration, Duration, duration);
49
50impl Shaped for () {
51    const FORM: WireForm = WireForm::Unit;
52
53    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
54        out.unit(ty)
55    }
56
57    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
58        input.unit(ty)
59    }
60}
61
62/// `Never`, which has no values.
63impl Shaped for Infallible {
64    const FORM: WireForm = WireForm::Never;
65
66    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
67        let _ = (out, ty);
68        match *self {}
69    }
70
71    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
72        Err(input.mismatch(ty))
73    }
74}
75
76/// A set, its values in Flow's order whatever Rust's is.
77impl<T: Shaped + Ord> Shaped for BTreeSet<T> {
78    const FORM: WireForm = WireForm::Set(form_of::<T>);
79
80    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
81        out.set(ty, self.iter())
82    }
83
84    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
85        input.set(ty)
86    }
87}
88
89/// A dictionary, its entries in Flow's order of its keys whatever Rust's is.
90impl<K: Shaped + Ord, V: Shaped> Shaped for BTreeMap<K, V> {
91    const FORM: WireForm = WireForm::Dict(form_of::<K>, form_of::<V>);
92
93    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
94        out.dict(ty, self.iter())
95    }
96
97    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
98        input.dict(ty)
99    }
100}
101
102/// A tuple of its parts' forms, in order.
103macro_rules! tuple {
104    ($($part:ident $index:tt),+) => {
105        impl<$($part: Shaped),+> Shaped for ($($part,)+) {
106            const FORM: WireForm =
107                WireForm::Tuple(&[$(form_of::<$part>),+]);
108
109            fn write_at(
110                &self,
111                out: &mut ValueWriter<'_, '_>,
112                ty: &Type,
113            ) -> Result<(), EncodeError> {
114                out.tuple(ty, &[$(&self.$index),+])
115            }
116
117            fn read_at(
118                input: &mut ValueReader<'_, '_, '_>,
119                ty: &Type,
120            ) -> Result<Self, DecodeError> {
121                input.tuple(ty, |input, parts| Ok(($(parts.read::<$part>(input)?,)+)))
122            }
123        }
124    };
125}
126
127tuple!(A 0, B 1);
128tuple!(A 0, B 1, C 2);
129tuple!(A 0, B 1, C 2, D 3);
130tuple!(A 0, B 1, C 2, D 3, E 4);
131tuple!(A 0, B 1, C 2, D 3, E 4, F 5);
132tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6);
133tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7);
134
135/// `nanos` nanoseconds as exact decimal seconds.
136fn of_nanoseconds(nanos: i128) -> Decimal {
137    Decimal::new(flow_value::BigInt::from(nanos), -9)
138        .expect("nine places after the point is in range")
139}
140
141/// `seconds` as whole nanoseconds, when it is a whole number of them
142/// that an `i128` holds.
143fn nanoseconds(seconds: &Decimal) -> Option<i128> {
144    // 10^39 nanoseconds is past every `i128`, whatever the coefficient.
145    let shift = u32::try_from(seconds.exponent().checked_add(9)?)
146        .ok()
147        .filter(|shift| *shift < 39)?;
148    i128::try_from(seconds.coefficient() * flow_value::BigInt::from(10u8).pow(shift)).ok()
149}
150
151/// The `std::time::Duration` of `nanos` nanoseconds, when it is one.
152fn std_duration(nanos: i128) -> Option<std::time::Duration> {
153    let nanos = u128::try_from(nanos).ok()?;
154    let seconds = u64::try_from(nanos / 1_000_000_000).ok()?;
155    let subsecond = u32::try_from(nanos % 1_000_000_000).ok()?;
156    Some(std::time::Duration::new(seconds, subsecond))
157}
158
159/// `duration.Duration`, as a length its Rust type can hold: one that is
160/// negative or finer than a nanosecond is none.
161impl Shaped for std::time::Duration {
162    const FORM: WireForm = WireForm::Duration;
163
164    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
165        let nanos = i128::try_from(self.as_nanos()).map_err(|_| out.refuse(ty))?;
166        out.duration(ty, &Duration::from_seconds(of_nanoseconds(nanos)))
167    }
168
169    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
170        std_duration(nanoseconds(input.duration(ty)?.seconds()).ok_or_else(|| input.mismatch(ty))?)
171            .ok_or_else(|| input.mismatch(ty))
172    }
173}
174
175/// The exact `Instant` `time` is: its nanoseconds since the epoch,
176/// before it negative; none past what an `i128` of nanoseconds holds.
177#[expect(
178    clippy::disallowed_types,
179    reason = "a time a Tool takes or answers is converted here; no clock is read"
180)]
181pub fn instant_of(time: std::time::SystemTime) -> Option<Instant> {
182    let nanos = match time.duration_since(std::time::UNIX_EPOCH) {
183        Ok(after) => i128::try_from(after.as_nanos()).ok()?,
184        Err(before) => -i128::try_from(before.duration().as_nanos()).ok()?,
185    };
186    Some(Instant::from_unix_seconds(of_nanoseconds(nanos)))
187}
188
189/// `time.Instant`, as an instant the platform's clock can hold.
190#[expect(
191    clippy::disallowed_types,
192    reason = "a time a Tool takes or answers is converted here; no clock is read"
193)]
194impl Shaped for std::time::SystemTime {
195    const FORM: WireForm = WireForm::Instant;
196
197    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
198        out.instant(ty, &instant_of(*self).ok_or_else(|| out.refuse(ty))?)
199    }
200
201    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
202        let nanos = nanoseconds(input.instant(ty)?.unix_seconds());
203        let time = nanos.and_then(|nanos| {
204            let length = std_duration(nanos.checked_abs()?)?;
205            if nanos < 0 {
206                std::time::UNIX_EPOCH.checked_sub(length)
207            } else {
208                std::time::UNIX_EPOCH.checked_add(length)
209            }
210        });
211        time.ok_or_else(|| input.mismatch(ty))
212    }
213}
214
215/// Writes `text` at `ty`, the std type held to `held`.
216fn write_held(
217    out: &mut ValueWriter<'_, '_>,
218    ty: &Type,
219    held: StdForm,
220    text: &str,
221) -> Result<(), EncodeError> {
222    if !matches!(form(out.catalog(), ty), Form::Newtype(_, Some(form)) if form == held) {
223        return Err(out.refuse(ty));
224    }
225    out.newtype(ty, &text.to_owned())
226}
227
228/// Reads the text of a value of `ty`, the std type held to `held`.
229fn read_held(
230    input: &mut ValueReader<'_, '_, '_>,
231    ty: &Type,
232    held: StdForm,
233) -> Result<String, DecodeError> {
234    if !matches!(form(input.catalog(), ty), Form::Newtype(_, Some(form)) if form == held) {
235        return Err(input.mismatch(ty));
236    }
237    input.newtype(ty)
238}
239
240/// `path.Path`: its normal text, its components joined by `/` whatever
241/// the host's separator, so a path that is not UTF-8 is none.
242impl Shaped for std::path::PathBuf {
243    const FORM: WireForm = WireForm::Std {
244        module: "path",
245        name: "Path",
246        args: &[],
247    };
248
249    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
250        let text = self.to_str().ok_or_else(|| out.refuse(ty))?;
251        let text = text.replace(std::path::MAIN_SEPARATOR, "/");
252        write_held(out, ty, StdForm::Path, &flow_types::normal_path(&text))
253    }
254
255    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
256        read_held(input, ty, StdForm::Path).map(std::path::PathBuf::from)
257    }
258}
259
260/// A std type held to a form of its own, as its normal text.
261macro_rules! held {
262    ($rust:ty, $module:literal, $name:literal, $form:ident) => {
263        impl Shaped for $rust {
264            const FORM: WireForm = WireForm::Std {
265                module: $module,
266                name: $name,
267                args: &[],
268            };
269
270            fn write_at(
271                &self,
272                out: &mut ValueWriter<'_, '_>,
273                ty: &Type,
274            ) -> Result<(), EncodeError> {
275                write_held(out, ty, StdForm::$form, &self.to_string())
276            }
277
278            fn read_at(
279                input: &mut ValueReader<'_, '_, '_>,
280                ty: &Type,
281            ) -> Result<Self, DecodeError> {
282                let text = read_held(input, ty, StdForm::$form)?;
283                <$rust>::parse(&text).ok_or_else(|| input.mismatch(ty))
284            }
285        }
286    };
287}
288
289held!(crate::Url, "url", "Url", Url);
290held!(crate::MediaType, "media", "MediaType", MediaType);
291
292/// The place-holder a declaration's type parameter numbered `INDEX` is
293/// written as in its [`Shape`](super::Shape): it has no values.
294#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
295pub struct Param<const INDEX: usize>(Infallible);
296
297impl<const INDEX: usize> Shaped for Param<INDEX> {
298    const FORM: WireForm = WireForm::Param(INDEX);
299
300    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
301        let _ = (out, ty);
302        match self.0 {}
303    }
304
305    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
306        Err(input.mismatch(ty))
307    }
308}