1use 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
23macro_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
62impl 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
76impl<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
89impl<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
102macro_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
135fn 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
141fn nanoseconds(seconds: &Decimal) -> Option<i128> {
144 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
151fn 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
159impl 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#[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#[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
215fn 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
228fn 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
240impl 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
260macro_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#[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}