Skip to main content

flow_abi/
crossing.rs

1//! A Rust value written and read at its Flow type directly: each
2//! [`Shaped`] mapping writes its parts into a [`ValueWriter`] and reads them
3//! from a [`ValueReader`], and the bytes are the value encoding's, checked
4//! by the same rules as the runtime's own values ([`crate::write_value`],
5//! [`crate::read_value`]), with no runtime value built between.
6//!
7//! Two rules need a value's place in Flow's order, which the Rust type's own
8//! order need not match: a set's elements and a dictionary's keys are
9//! written in ascending order and refused out of it. Only those parts are
10//! read as runtime values, to be compared.
11
12use std::borrow::Cow;
13use std::collections::{BTreeMap, BTreeSet};
14use std::sync::Arc;
15
16use flow_types::{EnumShape, RecordShape, Type};
17use flow_value::{Decimal, Duration, Instant, Int, Value, compare};
18
19use crate::binary::{ValueReader, ValueWriter, decimal_into, payload_step, read_decimal};
20use crate::bytes::{Reader, wide, write_bytes, write_int, write_text, write_uint};
21use crate::catalog::Catalog;
22use crate::decode::{Mode, decodable};
23use crate::error::{DecodeError, DecodeErrorKind, EncodeError, EncodeErrorKind, Place};
24use crate::form::{Form, Scalar, form};
25use crate::limits::Limits;
26use crate::wire::{Part, Shaped};
27
28/// Appends `value`'s encoding at `ty` in `catalog` to `out`.
29///
30/// # Errors
31///
32/// An [`EncodeError`] when `ty` is not the type `T`'s form projects to, or
33/// the value is out of a form its type holds it to; `out` then holds
34/// whatever was written before the error.
35pub fn write_shaped<T: Shaped>(
36    out: &mut Vec<u8>,
37    catalog: &Catalog,
38    ty: &Type,
39    value: &T,
40) -> Result<(), EncodeError> {
41    value.write_at(
42        &mut ValueWriter {
43            catalog,
44            out,
45            path: Place::default(),
46        },
47        ty,
48    )
49}
50
51/// Reads one `T` at `ty` in `catalog` from `reader`, in `mode` and within
52/// `limits`, leaving the reader just past it.
53///
54/// # Errors
55///
56/// A [`DecodeError`] when `ty` cannot be decoded in `mode`, the bytes are
57/// not a value of `ty` within `limits`, or the value is none of `T`'s.
58pub fn read_shaped<T: Shaped>(
59    reader: &mut Reader<'_>,
60    catalog: &Catalog,
61    ty: &Type,
62    mode: Mode,
63    limits: &Limits,
64) -> Result<T, DecodeError> {
65    decodable(catalog, ty, mode.settings())?;
66    T::read_at(
67        &mut ValueReader {
68            catalog,
69            limits,
70            path: Place::default(),
71            reader,
72            zero_width_left: limits.text_bytes,
73            level: 0,
74        },
75        ty,
76    )
77}
78
79/// The runtime's value of `value`, a value of `ty` in `catalog`: for a
80/// caller that holds runtime values, such as a run's history.
81///
82/// # Errors
83///
84/// As [`write_shaped`].
85pub fn shaped_value<T: Shaped>(
86    value: &T,
87    catalog: &Catalog,
88    ty: &Type,
89) -> Result<Value, EncodeError> {
90    let mut bytes = Vec::new();
91    write_shaped(&mut bytes, catalog, ty, value)?;
92    crate::decode_bytes(catalog, ty, &bytes, Mode::Rebuild, &Limits::UNBOUNDED)
93        .map_err(|error| EncodeError::new(&error.path, EncodeErrorKind::Mismatch, error.problem))
94}
95
96/// The `T` that `value`, a runtime value of `ty` in `catalog`, is.
97///
98/// # Errors
99///
100/// A [`DecodeError`] when `value` is no value of `ty`, or none of `T`'s.
101pub fn of_shaped_value<T: Shaped>(
102    value: &Value,
103    catalog: &Catalog,
104    ty: &Type,
105) -> Result<T, DecodeError> {
106    let mut bytes = Vec::new();
107    crate::write_value(&mut bytes, catalog, ty, value)
108        .map_err(|error| DecodeError::of(&error.path, DecodeErrorKind::Mismatch, error.problem))?;
109    let mut reader = Reader::new(&bytes);
110    read_shaped(&mut reader, catalog, ty, Mode::Rebuild, &Limits::UNBOUNDED)
111}
112
113impl<'c> ValueWriter<'c, '_> {
114    /// The catalog the types written at are in.
115    pub fn catalog(&self) -> &'c Catalog {
116        self.catalog
117    }
118
119    /// The refusal of a value written at `ty`, a type the Rust type does
120    /// not map to.
121    pub fn refuse(&self, ty: &Type) -> EncodeError {
122        self.mismatch(ty)
123    }
124
125    fn scalar(&mut self, ty: &Type, scalar: Scalar) -> Result<&mut Vec<u8>, EncodeError> {
126        if let Form::Scalar(found) = form(self.catalog, ty)
127            && found == scalar
128        {
129            Ok(self.out)
130        } else {
131            Err(self.mismatch(ty))
132        }
133    }
134
135    /// Writes `Unit` at `ty`.
136    ///
137    /// # Errors
138    ///
139    /// When `ty` is not `Unit`; so for every writer below and its type.
140    pub fn unit(&mut self, ty: &Type) -> Result<(), EncodeError> {
141        self.scalar(ty, Scalar::Unit).map(|_| ())
142    }
143
144    /// Writes a `Bool`.
145    ///
146    /// # Errors
147    ///
148    /// As [`ValueWriter::unit`].
149    #[expect(
150        clippy::fn_params_excessive_bools,
151        reason = "the flag is the value written, as a Bool is"
152    )]
153    pub fn bool(&mut self, ty: &Type, flag: bool) -> Result<(), EncodeError> {
154        self.scalar(ty, Scalar::Bool)?.push(u8::from(flag));
155        Ok(())
156    }
157
158    /// Writes an `Int`.
159    ///
160    /// # Errors
161    ///
162    /// As [`ValueWriter::unit`].
163    pub fn int(&mut self, ty: &Type, number: &Int) -> Result<(), EncodeError> {
164        write_int(self.scalar(ty, Scalar::Int)?, number.as_bigint());
165        Ok(())
166    }
167
168    /// Writes a `Decimal`.
169    ///
170    /// # Errors
171    ///
172    /// As [`ValueWriter::unit`].
173    pub fn decimal(&mut self, ty: &Type, number: &Decimal) -> Result<(), EncodeError> {
174        decimal_into(self.scalar(ty, Scalar::Decimal)?, number);
175        Ok(())
176    }
177
178    /// Writes a `Duration`.
179    ///
180    /// # Errors
181    ///
182    /// As [`ValueWriter::unit`].
183    pub fn duration(&mut self, ty: &Type, span: &Duration) -> Result<(), EncodeError> {
184        decimal_into(self.scalar(ty, Scalar::Duration)?, span.seconds());
185        Ok(())
186    }
187
188    /// Writes an `Instant`.
189    ///
190    /// # Errors
191    ///
192    /// As [`ValueWriter::unit`].
193    pub fn instant(&mut self, ty: &Type, at: &Instant) -> Result<(), EncodeError> {
194        decimal_into(self.scalar(ty, Scalar::Instant)?, at.unix_seconds());
195        Ok(())
196    }
197
198    /// Writes a `Text`.
199    ///
200    /// # Errors
201    ///
202    /// As [`ValueWriter::unit`].
203    pub fn text(&mut self, ty: &Type, text: &str) -> Result<(), EncodeError> {
204        if !matches!(form(self.catalog, ty), Form::Text) {
205            return Err(self.mismatch(ty));
206        }
207        write_text(self.out, text);
208        Ok(())
209    }
210
211    /// Writes `Bytes`.
212    ///
213    /// # Errors
214    ///
215    /// As [`ValueWriter::unit`].
216    pub fn bytes(&mut self, ty: &Type, bytes: &[u8]) -> Result<(), EncodeError> {
217        if !matches!(form(self.catalog, ty), Form::Bytes) {
218            return Err(self.mismatch(ty));
219        }
220        write_bytes(self.out, bytes);
221        Ok(())
222    }
223
224    /// Writes a host type's value, its token.
225    ///
226    /// # Errors
227    ///
228    /// As [`ValueWriter::unit`].
229    pub fn host(&mut self, ty: &Type, token: &str) -> Result<(), EncodeError> {
230        if !matches!(form(self.catalog, ty), Form::Host) {
231            return Err(self.mismatch(ty));
232        }
233        write_text(self.out, token);
234        Ok(())
235    }
236
237    /// Writes a list of `items`.
238    ///
239    /// # Errors
240    ///
241    /// When `ty` is no list, or an item is not of its element type.
242    pub fn list<'v, T: Shaped>(
243        &mut self,
244        ty: &Type,
245        items: impl ExactSizeIterator<Item = &'v T>,
246    ) -> Result<(), EncodeError> {
247        let catalog = self.catalog;
248        let Form::List(item) = form(catalog, ty) else {
249            return Err(self.mismatch(ty));
250        };
251        write_uint(self.out, wide(items.len()));
252        for (index, each) in items.enumerate() {
253            self.at(|path| path.index(index), |me| each.write_at(me, item))?;
254        }
255        Ok(())
256    }
257
258    /// Writes a set of `items`, in Flow's order of them.
259    ///
260    /// # Errors
261    ///
262    /// When `ty` is no set, an item is not of its element type, or two
263    /// items are one value.
264    pub fn set<'v, T: Shaped>(
265        &mut self,
266        ty: &Type,
267        items: impl ExactSizeIterator<Item = &'v T>,
268    ) -> Result<(), EncodeError> {
269        let catalog = self.catalog;
270        let Form::Set(item) = form(catalog, ty) else {
271            return Err(self.mismatch(ty));
272        };
273        self.ordered(
274            item,
275            None,
276            items.map(|each| -> (&dyn Part, Option<&dyn Part>) { (each, None) }),
277        )
278    }
279
280    /// Writes a dictionary of `entries`, in Flow's order of their keys.
281    ///
282    /// # Errors
283    ///
284    /// When `ty` is no dictionary, a key or a value is not of its type, or
285    /// two keys are one value.
286    pub fn dict<'v, K: Shaped, V: Shaped>(
287        &mut self,
288        ty: &Type,
289        entries: impl ExactSizeIterator<Item = (&'v K, &'v V)>,
290    ) -> Result<(), EncodeError> {
291        let catalog = self.catalog;
292        let Form::Dict(key, item) = form(catalog, ty) else {
293            return Err(self.mismatch(ty));
294        };
295        self.ordered(
296            key,
297            Some(item),
298            entries.map(|(each, held)| -> (&dyn Part, Option<&dyn Part>) { (each, Some(held)) }),
299        )
300    }
301
302    /// Writes the count of `entries` and each entry, its key of `key` and
303    /// its value of `item`, in ascending order of the keys.
304    fn ordered<'p>(
305        &mut self,
306        key: &Type,
307        item: Option<&Type>,
308        entries: impl ExactSizeIterator<Item = (&'p dyn Part, Option<&'p dyn Part>)>,
309    ) -> Result<(), EncodeError> {
310        let mut written = Vec::with_capacity(entries.len());
311        for (index, (each, held)) in entries.enumerate() {
312            let mut bytes = Vec::new();
313            let mut part = ValueWriter {
314                catalog: self.catalog,
315                out: &mut bytes,
316                path: self.path.clone(),
317            };
318            part.path.index(index);
319            part.at(|path| path.index(0), |me| each.write_part(me, key))?;
320            let ends = part.out.len();
321            if let (Some(item), Some(held)) = (item, held) {
322                part.at(|path| path.index(1), |me| held.write_part(me, item))?;
323            }
324            let order = crate::decode_bytes(
325                self.catalog,
326                key,
327                &bytes[..ends],
328                Mode::Rebuild,
329                &Limits::UNBOUNDED,
330            )
331            .map_err(|error| {
332                EncodeError::new(&self.path, EncodeErrorKind::Mismatch, error.problem)
333            })?;
334            written.push((order, bytes));
335        }
336        written.sort_by(|(a, _), (b, _)| compare(a, b).unwrap_or(std::cmp::Ordering::Equal));
337        if written
338            .windows(2)
339            .any(|pair| compare(&pair[0].0, &pair[1].0) != Ok(std::cmp::Ordering::Less))
340        {
341            return Err(EncodeError::new(
342                &self.path,
343                EncodeErrorKind::Mismatch,
344                "holds two keys that are one value",
345            ));
346        }
347        write_uint(self.out, wide(written.len()));
348        for (_, bytes) in written {
349            self.out.extend_from_slice(&bytes);
350        }
351        Ok(())
352    }
353
354    /// Writes a tuple of `parts`.
355    ///
356    /// # Errors
357    ///
358    /// When `ty` is no tuple of as many parts, or a part is not of its type.
359    pub fn tuple(&mut self, ty: &Type, parts: &[&dyn Part]) -> Result<(), EncodeError> {
360        let catalog = self.catalog;
361        let Form::Tuple(types) = form(catalog, ty) else {
362            return Err(self.mismatch(ty));
363        };
364        if types.len() != parts.len() {
365            return Err(self.mismatch(ty));
366        }
367        for (index, (part, each)) in types.iter().zip(parts).enumerate() {
368            self.at(|path| path.index(index), |me| each.write_part(me, part))?;
369        }
370        Ok(())
371    }
372
373    /// Writes a record of `fields`, in declaration order.
374    ///
375    /// # Errors
376    ///
377    /// When `ty` is no record of as many fields, or a field is not of its
378    /// type.
379    pub fn record(&mut self, ty: &Type, fields: &[&dyn Part]) -> Result<(), EncodeError> {
380        let catalog = self.catalog;
381        let Some(record) = form(catalog, ty).record() else {
382            return Err(self.mismatch(ty));
383        };
384        if record.fields.len() != fields.len() {
385            return Err(self.mismatch(ty));
386        }
387        for ((name, field), each) in record.shape.fields().zip(&record.fields).zip(fields) {
388            self.at(|path| path.field(name), |me| each.write_part(me, field))?;
389        }
390        Ok(())
391    }
392
393    /// Writes the value of the constructor at `index` of the enum `ty`,
394    /// `Option` and `Result` included, with `payload`.
395    ///
396    /// # Errors
397    ///
398    /// When `ty` is no enum with that constructor taking as many parts, or
399    /// a part is not of its type.
400    pub fn variant(
401        &mut self,
402        ty: &Type,
403        index: usize,
404        payload: &[&dyn Part],
405    ) -> Result<(), EncodeError> {
406        let catalog = self.catalog;
407        let Some(shape) = form(catalog, ty).enumeration() else {
408            return Err(self.mismatch(ty));
409        };
410        let (Some(types), Some(ctor)) = (shape.parts(index), shape.shape.constructor(index)) else {
411            return Err(self.mismatch(ty));
412        };
413        if types.len() != payload.len() {
414            return Err(self.mismatch(ty));
415        }
416        write_uint(self.out, wide(index));
417        self.at(
418            |path| path.constructor(ctor.name()),
419            |me| {
420                for (at, (part, each)) in types.iter().zip(payload).enumerate() {
421                    me.at(
422                        |path| payload_step(path, ctor.payload(), at),
423                        |me| each.write_part(me, part),
424                    )?;
425                }
426                Ok(())
427            },
428        )
429    }
430
431    /// Writes a value of the newtype `ty`, its base's `base`, held to the
432    /// form `ty` has, if any.
433    ///
434    /// # Errors
435    ///
436    /// When `ty` is no newtype, `base` is not of its base, or is out of its
437    /// form.
438    pub fn newtype(&mut self, ty: &Type, base: &dyn Part) -> Result<(), EncodeError> {
439        let catalog = self.catalog;
440        let Form::Newtype(base_ty, held) = form(catalog, ty) else {
441            return Err(self.mismatch(ty));
442        };
443        let starts = self.out.len();
444        base.write_part(self, &base_ty)?;
445        let Some(held) = held else {
446            return Ok(());
447        };
448        let text = Reader::new(&self.out[starts..])
449            .text(&Limits::LANGUAGE)
450            .map_err(|error| {
451                EncodeError::new(&self.path, EncodeErrorKind::Mismatch, error.problem)
452            })?;
453        if let Some(problem) = held.refusal(text) {
454            self.out.truncate(starts);
455            return Err(EncodeError::new(
456                &self.path,
457                EncodeErrorKind::Mismatch,
458                problem,
459            ));
460        }
461        Ok(())
462    }
463
464    /// Writes `bytes`, which hold one value of `ty`.
465    ///
466    /// # Errors
467    ///
468    /// When they do not: they are checked as a decoder checks them.
469    pub fn encoded(&mut self, ty: &Type, bytes: &[u8]) -> Result<(), EncodeError> {
470        crate::decode_bytes(self.catalog, ty, bytes, Mode::Rebuild, &Limits::LANGUAGE).map_err(
471            |error| EncodeError::new(&self.path, EncodeErrorKind::Mismatch, error.problem),
472        )?;
473        self.out.extend_from_slice(bytes);
474        Ok(())
475    }
476}
477
478/// The parts of an aggregate a [`ValueReader`] reads, one at a time, in
479/// order.
480#[derive(Debug)]
481pub struct Fields {
482    types: Vec<Type>,
483    step: Step,
484    at: usize,
485}
486
487/// How the path steps onto an aggregate's part.
488#[derive(Debug)]
489enum Step {
490    Index,
491    Field(Arc<RecordShape>),
492    Payload(Arc<EnumShape>, usize),
493}
494
495impl Fields {
496    /// Reads the next part as a `T`.
497    ///
498    /// # Errors
499    ///
500    /// When every part is read, or the part is not one of `T`'s.
501    ///
502    /// # Panics
503    ///
504    /// Never: a record has a name for each field, and an enum the
505    /// constructor it was opened at.
506    pub fn read<T: Shaped>(
507        &mut self,
508        input: &mut ValueReader<'_, '_, '_>,
509    ) -> Result<T, DecodeError> {
510        let Some(ty) = self.types.get(self.at) else {
511            return Err(input.refuse(
512                DecodeErrorKind::Mismatch,
513                "has fewer parts than the Rust type that reads it",
514            ));
515        };
516        match &self.step {
517            Step::Index => input.path.index(self.at),
518            Step::Field(shape) => input
519                .path
520                .field(shape.field(self.at).expect("a name per field")),
521            Step::Payload(shape, index) => {
522                let ctor = shape.constructor(*index).expect("found when opened");
523                payload_step(&mut input.path, ctor.payload(), self.at);
524            }
525        }
526        let part = T::read_at(input, ty)?;
527        input.path.pop();
528        self.at += 1;
529        Ok(part)
530    }
531}
532
533impl<'b> ValueReader<'_, '_, 'b> {
534    /// The catalog the types read at are in.
535    pub fn catalog(&self) -> &Catalog {
536        self.catalog
537    }
538
539    /// The refusal of a value read at `ty`, a type the Rust type does not
540    /// map to, or a value of it that is none of the Rust type's.
541    pub fn mismatch(&self, ty: &Type) -> DecodeError {
542        self.refuse(
543            DecodeErrorKind::Mismatch,
544            format!(
545                "is a value of {}, which is none of the Rust type's that reads it",
546                self.catalog.name(ty)
547            ),
548        )
549    }
550
551    fn scalar(&mut self, ty: &Type, scalar: Scalar) -> Result<(), DecodeError> {
552        if let Form::Scalar(found) = form(self.catalog, ty)
553            && found == scalar
554        {
555            Ok(())
556        } else {
557            Err(self.mismatch(ty))
558        }
559    }
560
561    /// Reads `Unit` at `ty`.
562    ///
563    /// # Errors
564    ///
565    /// When `ty` is not `Unit`; so for every reader below and its type, and
566    /// for bytes that are not a value of it within the limits.
567    pub fn unit(&mut self, ty: &Type) -> Result<(), DecodeError> {
568        self.scalar(ty, Scalar::Unit)
569    }
570
571    /// Reads a `Bool`.
572    ///
573    /// # Errors
574    ///
575    /// As [`ValueReader::unit`].
576    pub fn bool(&mut self, ty: &Type) -> Result<bool, DecodeError> {
577        self.scalar(ty, Scalar::Bool)?;
578        self.reader.bool().map_err(|error| self.here(error))
579    }
580
581    /// Reads an `Int`.
582    ///
583    /// # Errors
584    ///
585    /// As [`ValueReader::unit`].
586    pub fn int(&mut self, ty: &Type) -> Result<Int, DecodeError> {
587        self.scalar(ty, Scalar::Int)?;
588        self.reader
589            .int(self.limits)
590            .map(Int::from)
591            .map_err(|error| self.here(error))
592    }
593
594    fn exact(&mut self, ty: &Type, scalar: Scalar) -> Result<Decimal, DecodeError> {
595        self.scalar(ty, scalar)?;
596        read_decimal(self.reader, self.limits).map_err(|error| self.here(error))
597    }
598
599    /// Reads a `Decimal`.
600    ///
601    /// # Errors
602    ///
603    /// As [`ValueReader::unit`].
604    pub fn decimal(&mut self, ty: &Type) -> Result<Decimal, DecodeError> {
605        self.exact(ty, Scalar::Decimal)
606    }
607
608    /// Reads a `Duration`.
609    ///
610    /// # Errors
611    ///
612    /// As [`ValueReader::unit`].
613    pub fn duration(&mut self, ty: &Type) -> Result<Duration, DecodeError> {
614        self.exact(ty, Scalar::Duration).map(Duration::from_seconds)
615    }
616
617    /// Reads an `Instant`.
618    ///
619    /// # Errors
620    ///
621    /// As [`ValueReader::unit`].
622    pub fn instant(&mut self, ty: &Type) -> Result<Instant, DecodeError> {
623        self.exact(ty, Scalar::Instant)
624            .map(Instant::from_unix_seconds)
625    }
626
627    /// Reads a `Text`.
628    ///
629    /// # Errors
630    ///
631    /// As [`ValueReader::unit`].
632    pub fn text(&mut self, ty: &Type) -> Result<&'b str, DecodeError> {
633        if !matches!(form(self.catalog, ty), Form::Text) {
634            return Err(self.mismatch(ty));
635        }
636        self.reader
637            .text(self.limits)
638            .map_err(|error| self.here(error))
639    }
640
641    /// Reads `Bytes`.
642    ///
643    /// # Errors
644    ///
645    /// As [`ValueReader::unit`].
646    pub fn bytes(&mut self, ty: &Type) -> Result<&'b [u8], DecodeError> {
647        if !matches!(form(self.catalog, ty), Form::Bytes) {
648            return Err(self.mismatch(ty));
649        }
650        self.reader
651            .bytes(self.limits)
652            .map_err(|error| self.here(error))
653    }
654
655    /// Reads a host type's value, its token.
656    ///
657    /// # Errors
658    ///
659    /// As [`ValueReader::unit`].
660    pub fn host(&mut self, ty: &Type) -> Result<&'b str, DecodeError> {
661        if !matches!(form(self.catalog, ty), Form::Host) {
662            return Err(self.mismatch(ty));
663        }
664        self.reader
665            .text(self.limits)
666            .map_err(|error| self.here(error))
667    }
668
669    /// Reads an aggregate one level deeper, as `read` does.
670    fn within<T>(
671        &mut self,
672        read: impl FnOnce(&mut Self) -> Result<T, DecodeError>,
673    ) -> Result<T, DecodeError> {
674        let outer = self.level;
675        self.level = self.enter(outer)?;
676        let read = read(self);
677        self.level = outer;
678        read
679    }
680
681    /// Reads a list.
682    ///
683    /// # Errors
684    ///
685    /// When `ty` is no list, or the bytes are not one of `T`s.
686    pub fn list<T: Shaped>(&mut self, ty: &Type) -> Result<Vec<T>, DecodeError> {
687        let catalog = self.catalog;
688        let Form::List(item) = form(catalog, ty) else {
689            return Err(self.mismatch(ty));
690        };
691        self.within(|me| {
692            let count = me.count(&[item])?;
693            let mut items = Vec::with_capacity(me.backed(count));
694            for index in 0..count {
695                me.path.index(index);
696                items.push(T::read_at(me, item)?);
697                me.path.pop();
698            }
699            Ok(items)
700        })
701    }
702
703    /// The runtime value of the part read since byte `starts`, a value of
704    /// `ty`, for its place in Flow's order.
705    fn order(&self, ty: &Type, starts: usize) -> Result<Value, DecodeError> {
706        let mut reader = Reader::new(self.reader.since(starts));
707        ValueReader {
708            catalog: self.catalog,
709            limits: self.limits,
710            path: self.path.clone(),
711            reader: &mut reader,
712            zero_width_left: self.limits.text_bytes,
713            level: self.level,
714        }
715        .value(ty, self.level)
716    }
717
718    /// Reads a set, its elements in ascending order.
719    ///
720    /// # Errors
721    ///
722    /// When `ty` is no set, the bytes are not one of `T`s, or its elements
723    /// are out of order or repeat.
724    pub fn set<T: Shaped + Ord>(&mut self, ty: &Type) -> Result<BTreeSet<T>, DecodeError> {
725        let catalog = self.catalog;
726        let Form::Set(item) = form(catalog, ty) else {
727            return Err(self.mismatch(ty));
728        };
729        self.within(|me| {
730            let count = me.count(&[item])?;
731            let mut items = BTreeSet::new();
732            let mut previous = None;
733            for index in 0..count {
734                me.path.index(index);
735                let starts = me.reader.position();
736                items.insert(T::read_at(me, item)?);
737                let order = me.order(item, starts)?;
738                me.path.pop();
739                if let Some(before) = &previous {
740                    me.after("element", index, before, &order)?;
741                }
742                previous = Some(order);
743            }
744            Ok(items)
745        })
746    }
747
748    /// Reads a dictionary, its entries in ascending order of their keys.
749    ///
750    /// # Errors
751    ///
752    /// When `ty` is no dictionary, the bytes are not one of `K`s and `V`s,
753    /// or its keys are out of order or repeat.
754    pub fn dict<K: Shaped + Ord, V: Shaped>(
755        &mut self,
756        ty: &Type,
757    ) -> Result<BTreeMap<K, V>, DecodeError> {
758        let catalog = self.catalog;
759        let Form::Dict(key, item) = form(catalog, ty) else {
760            return Err(self.mismatch(ty));
761        };
762        self.within(|me| {
763            let count = me.count(&[key, item])?;
764            let mut entries = BTreeMap::new();
765            let mut previous = None;
766            for index in 0..count {
767                me.path.index(index);
768                me.path.index(0);
769                let starts = me.reader.position();
770                let each = K::read_at(me, key)?;
771                let order = me.order(key, starts)?;
772                me.path.pop();
773                me.path.index(1);
774                let held = V::read_at(me, item)?;
775                me.path.pop();
776                me.path.pop();
777                if let Some(before) = &previous {
778                    me.after("key", index, before, &order)?;
779                }
780                previous = Some(order);
781                entries.insert(each, held);
782            }
783            Ok(entries)
784        })
785    }
786
787    /// Reads the parts of an aggregate of `types` as `read` does, then
788    /// refuses any part it left unread.
789    fn parts<T>(
790        &mut self,
791        ty: &Type,
792        mut fields: Fields,
793        read: impl FnOnce(&mut Self, &mut Fields) -> Result<T, DecodeError>,
794    ) -> Result<T, DecodeError> {
795        let value = read(self, &mut fields)?;
796        if fields.at == fields.types.len() {
797            Ok(value)
798        } else {
799            Err(self.mismatch(ty))
800        }
801    }
802
803    /// Reads a tuple, its parts by `read`.
804    ///
805    /// # Errors
806    ///
807    /// When `ty` is no tuple, or `read` refuses or leaves a part unread.
808    pub fn tuple<T>(
809        &mut self,
810        ty: &Type,
811        read: impl FnOnce(&mut Self, &mut Fields) -> Result<T, DecodeError>,
812    ) -> Result<T, DecodeError> {
813        let catalog = self.catalog;
814        let Form::Tuple(types) = form(catalog, ty) else {
815            return Err(self.mismatch(ty));
816        };
817        let fields = Fields {
818            types: types.to_vec(),
819            step: Step::Index,
820            at: 0,
821        };
822        self.within(|me| me.parts(ty, fields, read))
823    }
824
825    /// Reads a record, its fields by `read` in declaration order.
826    ///
827    /// # Errors
828    ///
829    /// When `ty` is no record, or `read` refuses or leaves a field unread.
830    pub fn record<T>(
831        &mut self,
832        ty: &Type,
833        read: impl FnOnce(&mut Self, &mut Fields) -> Result<T, DecodeError>,
834    ) -> Result<T, DecodeError> {
835        let catalog = self.catalog;
836        let Some(record) = form(catalog, ty).record() else {
837            return Err(self.mismatch(ty));
838        };
839        let fields = Fields {
840            types: record.fields,
841            step: Step::Field(Arc::clone(record.shape)),
842            at: 0,
843        };
844        self.within(|me| me.parts(ty, fields, read))
845    }
846
847    /// Reads a value of the enum `ty`, `Option` and `Result` included:
848    /// `read` is given its constructor's index and reads its payload.
849    ///
850    /// # Errors
851    ///
852    /// When `ty` is no enum, the bytes name a constructor it does not have,
853    /// or `read` refuses or leaves a part unread.
854    pub fn variant<T>(
855        &mut self,
856        ty: &Type,
857        read: impl FnOnce(&mut Self, usize, &mut Fields) -> Result<T, DecodeError>,
858    ) -> Result<T, DecodeError> {
859        let catalog = self.catalog;
860        let Some(shape) = form(catalog, ty).enumeration() else {
861            return Err(self.mismatch(ty));
862        };
863        let index = self.reader.count().map_err(|error| self.here(error))?;
864        let (Some(types), Some(ctor)) = (shape.parts(index), shape.shape.constructor(index)) else {
865            return Err(self.refuse(
866                DecodeErrorKind::Mismatch,
867                format!(
868                    "names constructor {index}, which {} does not have",
869                    catalog.name(ty)
870                ),
871            ));
872        };
873        let fields = Fields {
874            types: types.into_iter().map(Cow::into_owned).collect(),
875            step: Step::Payload(Arc::clone(shape.shape), index),
876            at: 0,
877        };
878        self.within(|me| {
879            me.path.constructor(ctor.name());
880            let value = me.parts(ty, fields, |me, fields| read(me, index, fields))?;
881            me.path.pop();
882            Ok(value)
883        })
884    }
885
886    /// Reads a value of the newtype `ty` as its base's `T`, held to the form
887    /// `ty` has, if any.
888    ///
889    /// # Errors
890    ///
891    /// When `ty` is no newtype, the bytes are not a `T` of its base, or the
892    /// value is out of its form.
893    pub fn newtype<T: Shaped>(&mut self, ty: &Type) -> Result<T, DecodeError> {
894        let catalog = self.catalog;
895        let Form::Newtype(base, held) = form(catalog, ty) else {
896            return Err(self.mismatch(ty));
897        };
898        let starts = self.reader.position();
899        let value = T::read_at(self, &base)?;
900        if let Some(held) = held {
901            let text = Reader::new(self.reader.since(starts))
902                .text(self.limits)
903                .map_err(|error| self.here(error))?;
904            if let Some(problem) = held.refusal(text) {
905                return Err(self.refuse(DecodeErrorKind::Mismatch, problem));
906            }
907        }
908        Ok(value)
909    }
910
911    /// Reads one value of `ty`, checked as [`crate::read_value`] checks it,
912    /// and gives its bytes.
913    ///
914    /// # Errors
915    ///
916    /// When the bytes are not a value of `ty` within the limits.
917    pub fn encoded(&mut self, ty: &Type) -> Result<&'b [u8], DecodeError> {
918        let starts = self.reader.position();
919        self.value(ty, self.level)?;
920        Ok(self.reader.since(starts))
921    }
922}