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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
//! A Rust value written and read at its Flow type directly: each
//! [`Shaped`] mapping writes its parts into a [`ValueWriter`] and reads them
//! from a [`ValueReader`], and the bytes are the value encoding's, checked
//! by the same rules as the runtime's own values ([`crate::write_value`],
//! [`crate::read_value`]), with no runtime value built between.
//!
//! Two rules need a value's place in Flow's order, which the Rust type's own
//! order need not match: a set's elements and a dictionary's keys are
//! written in ascending order and refused out of it. Only those parts are
//! read as runtime values, to be compared.

use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

use flow_types::{EnumShape, RecordShape, Type};
use flow_value::{Decimal, Duration, Instant, Int, Value, compare};

use crate::binary::{ValueReader, ValueWriter, decimal_into, payload_step, read_decimal};
use crate::bytes::{Reader, wide, write_bytes, write_int, write_text, write_uint};
use crate::catalog::Catalog;
use crate::decode::{Mode, decodable};
use crate::error::{DecodeError, DecodeErrorKind, EncodeError, EncodeErrorKind, Place};
use crate::form::{Form, Scalar, form};
use crate::limits::Limits;
use crate::wire::{Part, Shaped};

/// Appends `value`'s encoding at `ty` in `catalog` to `out`.
///
/// # Errors
///
/// An [`EncodeError`] when `ty` is not the type `T`'s form projects to, or
/// the value is out of a form its type holds it to; `out` then holds
/// whatever was written before the error.
pub fn write_shaped<T: Shaped>(
    out: &mut Vec<u8>,
    catalog: &Catalog,
    ty: &Type,
    value: &T,
) -> Result<(), EncodeError> {
    value.write_at(
        &mut ValueWriter {
            catalog,
            out,
            path: Place::default(),
        },
        ty,
    )
}

/// Reads one `T` at `ty` in `catalog` from `reader`, in `mode` and within
/// `limits`, leaving the reader just past it.
///
/// # Errors
///
/// A [`DecodeError`] when `ty` cannot be decoded in `mode`, the bytes are
/// not a value of `ty` within `limits`, or the value is none of `T`'s.
pub fn read_shaped<T: Shaped>(
    reader: &mut Reader<'_>,
    catalog: &Catalog,
    ty: &Type,
    mode: Mode,
    limits: &Limits,
) -> Result<T, DecodeError> {
    decodable(catalog, ty, mode.settings())?;
    T::read_at(
        &mut ValueReader {
            catalog,
            limits,
            path: Place::default(),
            reader,
            zero_width_left: limits.text_bytes,
            level: 0,
        },
        ty,
    )
}

/// The runtime's value of `value`, a value of `ty` in `catalog`: for a
/// caller that holds runtime values, such as a run's history.
///
/// # Errors
///
/// As [`write_shaped`].
pub fn shaped_value<T: Shaped>(
    value: &T,
    catalog: &Catalog,
    ty: &Type,
) -> Result<Value, EncodeError> {
    let mut bytes = Vec::new();
    write_shaped(&mut bytes, catalog, ty, value)?;
    crate::decode_bytes(catalog, ty, &bytes, Mode::Rebuild, &Limits::UNBOUNDED)
        .map_err(|error| EncodeError::new(&error.path, EncodeErrorKind::Mismatch, error.problem))
}

/// The `T` that `value`, a runtime value of `ty` in `catalog`, is.
///
/// # Errors
///
/// A [`DecodeError`] when `value` is no value of `ty`, or none of `T`'s.
pub fn of_shaped_value<T: Shaped>(
    value: &Value,
    catalog: &Catalog,
    ty: &Type,
) -> Result<T, DecodeError> {
    let mut bytes = Vec::new();
    crate::write_value(&mut bytes, catalog, ty, value)
        .map_err(|error| DecodeError::of(&error.path, DecodeErrorKind::Mismatch, error.problem))?;
    let mut reader = Reader::new(&bytes);
    read_shaped(&mut reader, catalog, ty, Mode::Rebuild, &Limits::UNBOUNDED)
}

impl<'c> ValueWriter<'c, '_> {
    /// The catalog the types written at are in.
    pub fn catalog(&self) -> &'c Catalog {
        self.catalog
    }

    /// The refusal of a value written at `ty`, a type the Rust type does
    /// not map to.
    pub fn refuse(&self, ty: &Type) -> EncodeError {
        self.mismatch(ty)
    }

    fn scalar(&mut self, ty: &Type, scalar: Scalar) -> Result<&mut Vec<u8>, EncodeError> {
        if let Form::Scalar(found) = form(self.catalog, ty)
            && found == scalar
        {
            Ok(self.out)
        } else {
            Err(self.mismatch(ty))
        }
    }

    /// Writes `Unit` at `ty`.
    ///
    /// # Errors
    ///
    /// When `ty` is not `Unit`; so for every writer below and its type.
    pub fn unit(&mut self, ty: &Type) -> Result<(), EncodeError> {
        self.scalar(ty, Scalar::Unit).map(|_| ())
    }

    /// Writes a `Bool`.
    ///
    /// # Errors
    ///
    /// As [`ValueWriter::unit`].
    #[expect(
        clippy::fn_params_excessive_bools,
        reason = "the flag is the value written, as a Bool is"
    )]
    pub fn bool(&mut self, ty: &Type, flag: bool) -> Result<(), EncodeError> {
        self.scalar(ty, Scalar::Bool)?.push(u8::from(flag));
        Ok(())
    }

    /// Writes an `Int`.
    ///
    /// # Errors
    ///
    /// As [`ValueWriter::unit`].
    pub fn int(&mut self, ty: &Type, number: &Int) -> Result<(), EncodeError> {
        write_int(self.scalar(ty, Scalar::Int)?, number.as_bigint());
        Ok(())
    }

    /// Writes a `Decimal`.
    ///
    /// # Errors
    ///
    /// As [`ValueWriter::unit`].
    pub fn decimal(&mut self, ty: &Type, number: &Decimal) -> Result<(), EncodeError> {
        decimal_into(self.scalar(ty, Scalar::Decimal)?, number);
        Ok(())
    }

    /// Writes a `Duration`.
    ///
    /// # Errors
    ///
    /// As [`ValueWriter::unit`].
    pub fn duration(&mut self, ty: &Type, span: &Duration) -> Result<(), EncodeError> {
        decimal_into(self.scalar(ty, Scalar::Duration)?, span.seconds());
        Ok(())
    }

    /// Writes an `Instant`.
    ///
    /// # Errors
    ///
    /// As [`ValueWriter::unit`].
    pub fn instant(&mut self, ty: &Type, at: &Instant) -> Result<(), EncodeError> {
        decimal_into(self.scalar(ty, Scalar::Instant)?, at.unix_seconds());
        Ok(())
    }

    /// Writes a `Text`.
    ///
    /// # Errors
    ///
    /// As [`ValueWriter::unit`].
    pub fn text(&mut self, ty: &Type, text: &str) -> Result<(), EncodeError> {
        if !matches!(form(self.catalog, ty), Form::Text) {
            return Err(self.mismatch(ty));
        }
        write_text(self.out, text);
        Ok(())
    }

    /// Writes `Bytes`.
    ///
    /// # Errors
    ///
    /// As [`ValueWriter::unit`].
    pub fn bytes(&mut self, ty: &Type, bytes: &[u8]) -> Result<(), EncodeError> {
        if !matches!(form(self.catalog, ty), Form::Bytes) {
            return Err(self.mismatch(ty));
        }
        write_bytes(self.out, bytes);
        Ok(())
    }

    /// Writes a host type's value, its token.
    ///
    /// # Errors
    ///
    /// As [`ValueWriter::unit`].
    pub fn host(&mut self, ty: &Type, token: &str) -> Result<(), EncodeError> {
        if !matches!(form(self.catalog, ty), Form::Host) {
            return Err(self.mismatch(ty));
        }
        write_text(self.out, token);
        Ok(())
    }

    /// Writes a list of `items`.
    ///
    /// # Errors
    ///
    /// When `ty` is no list, or an item is not of its element type.
    pub fn list<'v, T: Shaped>(
        &mut self,
        ty: &Type,
        items: impl ExactSizeIterator<Item = &'v T>,
    ) -> Result<(), EncodeError> {
        let catalog = self.catalog;
        let Form::List(item) = form(catalog, ty) else {
            return Err(self.mismatch(ty));
        };
        write_uint(self.out, wide(items.len()));
        for (index, each) in items.enumerate() {
            self.at(|path| path.index(index), |me| each.write_at(me, item))?;
        }
        Ok(())
    }

    /// Writes a set of `items`, in Flow's order of them.
    ///
    /// # Errors
    ///
    /// When `ty` is no set, an item is not of its element type, or two
    /// items are one value.
    pub fn set<'v, T: Shaped>(
        &mut self,
        ty: &Type,
        items: impl ExactSizeIterator<Item = &'v T>,
    ) -> Result<(), EncodeError> {
        let catalog = self.catalog;
        let Form::Set(item) = form(catalog, ty) else {
            return Err(self.mismatch(ty));
        };
        self.ordered(
            item,
            None,
            items.map(|each| -> (&dyn Part, Option<&dyn Part>) { (each, None) }),
        )
    }

    /// Writes a dictionary of `entries`, in Flow's order of their keys.
    ///
    /// # Errors
    ///
    /// When `ty` is no dictionary, a key or a value is not of its type, or
    /// two keys are one value.
    pub fn dict<'v, K: Shaped, V: Shaped>(
        &mut self,
        ty: &Type,
        entries: impl ExactSizeIterator<Item = (&'v K, &'v V)>,
    ) -> Result<(), EncodeError> {
        let catalog = self.catalog;
        let Form::Dict(key, item) = form(catalog, ty) else {
            return Err(self.mismatch(ty));
        };
        self.ordered(
            key,
            Some(item),
            entries.map(|(each, held)| -> (&dyn Part, Option<&dyn Part>) { (each, Some(held)) }),
        )
    }

    /// Writes the count of `entries` and each entry, its key of `key` and
    /// its value of `item`, in ascending order of the keys.
    fn ordered<'p>(
        &mut self,
        key: &Type,
        item: Option<&Type>,
        entries: impl ExactSizeIterator<Item = (&'p dyn Part, Option<&'p dyn Part>)>,
    ) -> Result<(), EncodeError> {
        let mut written = Vec::with_capacity(entries.len());
        for (index, (each, held)) in entries.enumerate() {
            let mut bytes = Vec::new();
            let mut part = ValueWriter {
                catalog: self.catalog,
                out: &mut bytes,
                path: self.path.clone(),
            };
            part.path.index(index);
            part.at(|path| path.index(0), |me| each.write_part(me, key))?;
            let ends = part.out.len();
            if let (Some(item), Some(held)) = (item, held) {
                part.at(|path| path.index(1), |me| held.write_part(me, item))?;
            }
            let order = crate::decode_bytes(
                self.catalog,
                key,
                &bytes[..ends],
                Mode::Rebuild,
                &Limits::UNBOUNDED,
            )
            .map_err(|error| {
                EncodeError::new(&self.path, EncodeErrorKind::Mismatch, error.problem)
            })?;
            written.push((order, bytes));
        }
        written.sort_by(|(a, _), (b, _)| compare(a, b).unwrap_or(std::cmp::Ordering::Equal));
        if written
            .windows(2)
            .any(|pair| compare(&pair[0].0, &pair[1].0) != Ok(std::cmp::Ordering::Less))
        {
            return Err(EncodeError::new(
                &self.path,
                EncodeErrorKind::Mismatch,
                "holds two keys that are one value",
            ));
        }
        write_uint(self.out, wide(written.len()));
        for (_, bytes) in written {
            self.out.extend_from_slice(&bytes);
        }
        Ok(())
    }

    /// Writes a tuple of `parts`.
    ///
    /// # Errors
    ///
    /// When `ty` is no tuple of as many parts, or a part is not of its type.
    pub fn tuple(&mut self, ty: &Type, parts: &[&dyn Part]) -> Result<(), EncodeError> {
        let catalog = self.catalog;
        let Form::Tuple(types) = form(catalog, ty) else {
            return Err(self.mismatch(ty));
        };
        if types.len() != parts.len() {
            return Err(self.mismatch(ty));
        }
        for (index, (part, each)) in types.iter().zip(parts).enumerate() {
            self.at(|path| path.index(index), |me| each.write_part(me, part))?;
        }
        Ok(())
    }

    /// Writes a record of `fields`, in declaration order.
    ///
    /// # Errors
    ///
    /// When `ty` is no record of as many fields, or a field is not of its
    /// type.
    pub fn record(&mut self, ty: &Type, fields: &[&dyn Part]) -> Result<(), EncodeError> {
        let catalog = self.catalog;
        let Some(record) = form(catalog, ty).record() else {
            return Err(self.mismatch(ty));
        };
        if record.fields.len() != fields.len() {
            return Err(self.mismatch(ty));
        }
        for ((name, field), each) in record.shape.fields().zip(&record.fields).zip(fields) {
            self.at(|path| path.field(name), |me| each.write_part(me, field))?;
        }
        Ok(())
    }

    /// Writes the value of the constructor at `index` of the enum `ty`,
    /// `Option` and `Result` included, with `payload`.
    ///
    /// # Errors
    ///
    /// When `ty` is no enum with that constructor taking as many parts, or
    /// a part is not of its type.
    pub fn variant(
        &mut self,
        ty: &Type,
        index: usize,
        payload: &[&dyn Part],
    ) -> Result<(), EncodeError> {
        let catalog = self.catalog;
        let Some(shape) = form(catalog, ty).enumeration() else {
            return Err(self.mismatch(ty));
        };
        let (Some(types), Some(ctor)) = (shape.parts(index), shape.shape.constructor(index)) else {
            return Err(self.mismatch(ty));
        };
        if types.len() != payload.len() {
            return Err(self.mismatch(ty));
        }
        write_uint(self.out, wide(index));
        self.at(
            |path| path.constructor(ctor.name()),
            |me| {
                for (at, (part, each)) in types.iter().zip(payload).enumerate() {
                    me.at(
                        |path| payload_step(path, ctor.payload(), at),
                        |me| each.write_part(me, part),
                    )?;
                }
                Ok(())
            },
        )
    }

    /// Writes a value of the newtype `ty`, its base's `base`, held to the
    /// form `ty` has, if any.
    ///
    /// # Errors
    ///
    /// When `ty` is no newtype, `base` is not of its base, or is out of its
    /// form.
    pub fn newtype(&mut self, ty: &Type, base: &dyn Part) -> Result<(), EncodeError> {
        let catalog = self.catalog;
        let Form::Newtype(base_ty, held) = form(catalog, ty) else {
            return Err(self.mismatch(ty));
        };
        let starts = self.out.len();
        base.write_part(self, &base_ty)?;
        let Some(held) = held else {
            return Ok(());
        };
        let text = Reader::new(&self.out[starts..])
            .text(&Limits::LANGUAGE)
            .map_err(|error| {
                EncodeError::new(&self.path, EncodeErrorKind::Mismatch, error.problem)
            })?;
        if let Some(problem) = held.refusal(text) {
            self.out.truncate(starts);
            return Err(EncodeError::new(
                &self.path,
                EncodeErrorKind::Mismatch,
                problem,
            ));
        }
        Ok(())
    }

    /// Writes `bytes`, which hold one value of `ty`.
    ///
    /// # Errors
    ///
    /// When they do not: they are checked as a decoder checks them.
    pub fn encoded(&mut self, ty: &Type, bytes: &[u8]) -> Result<(), EncodeError> {
        crate::decode_bytes(self.catalog, ty, bytes, Mode::Rebuild, &Limits::LANGUAGE).map_err(
            |error| EncodeError::new(&self.path, EncodeErrorKind::Mismatch, error.problem),
        )?;
        self.out.extend_from_slice(bytes);
        Ok(())
    }
}

/// The parts of an aggregate a [`ValueReader`] reads, one at a time, in
/// order.
#[derive(Debug)]
pub struct Fields {
    types: Vec<Type>,
    step: Step,
    at: usize,
}

/// How the path steps onto an aggregate's part.
#[derive(Debug)]
enum Step {
    Index,
    Field(Arc<RecordShape>),
    Payload(Arc<EnumShape>, usize),
}

impl Fields {
    /// Reads the next part as a `T`.
    ///
    /// # Errors
    ///
    /// When every part is read, or the part is not one of `T`'s.
    ///
    /// # Panics
    ///
    /// Never: a record has a name for each field, and an enum the
    /// constructor it was opened at.
    pub fn read<T: Shaped>(
        &mut self,
        input: &mut ValueReader<'_, '_, '_>,
    ) -> Result<T, DecodeError> {
        let Some(ty) = self.types.get(self.at) else {
            return Err(input.refuse(
                DecodeErrorKind::Mismatch,
                "has fewer parts than the Rust type that reads it",
            ));
        };
        match &self.step {
            Step::Index => input.path.index(self.at),
            Step::Field(shape) => input
                .path
                .field(shape.field(self.at).expect("a name per field")),
            Step::Payload(shape, index) => {
                let ctor = shape.constructor(*index).expect("found when opened");
                payload_step(&mut input.path, ctor.payload(), self.at);
            }
        }
        let part = T::read_at(input, ty)?;
        input.path.pop();
        self.at += 1;
        Ok(part)
    }
}

impl<'b> ValueReader<'_, '_, 'b> {
    /// The catalog the types read at are in.
    pub fn catalog(&self) -> &Catalog {
        self.catalog
    }

    /// The refusal of a value read at `ty`, a type the Rust type does not
    /// map to, or a value of it that is none of the Rust type's.
    pub fn mismatch(&self, ty: &Type) -> DecodeError {
        self.refuse(
            DecodeErrorKind::Mismatch,
            format!(
                "is a value of {}, which is none of the Rust type's that reads it",
                self.catalog.name(ty)
            ),
        )
    }

    fn scalar(&mut self, ty: &Type, scalar: Scalar) -> Result<(), DecodeError> {
        if let Form::Scalar(found) = form(self.catalog, ty)
            && found == scalar
        {
            Ok(())
        } else {
            Err(self.mismatch(ty))
        }
    }

    /// Reads `Unit` at `ty`.
    ///
    /// # Errors
    ///
    /// When `ty` is not `Unit`; so for every reader below and its type, and
    /// for bytes that are not a value of it within the limits.
    pub fn unit(&mut self, ty: &Type) -> Result<(), DecodeError> {
        self.scalar(ty, Scalar::Unit)
    }

    /// Reads a `Bool`.
    ///
    /// # Errors
    ///
    /// As [`ValueReader::unit`].
    pub fn bool(&mut self, ty: &Type) -> Result<bool, DecodeError> {
        self.scalar(ty, Scalar::Bool)?;
        self.reader.bool().map_err(|error| self.here(error))
    }

    /// Reads an `Int`.
    ///
    /// # Errors
    ///
    /// As [`ValueReader::unit`].
    pub fn int(&mut self, ty: &Type) -> Result<Int, DecodeError> {
        self.scalar(ty, Scalar::Int)?;
        self.reader
            .int(self.limits)
            .map(Int::from)
            .map_err(|error| self.here(error))
    }

    fn exact(&mut self, ty: &Type, scalar: Scalar) -> Result<Decimal, DecodeError> {
        self.scalar(ty, scalar)?;
        read_decimal(self.reader, self.limits).map_err(|error| self.here(error))
    }

    /// Reads a `Decimal`.
    ///
    /// # Errors
    ///
    /// As [`ValueReader::unit`].
    pub fn decimal(&mut self, ty: &Type) -> Result<Decimal, DecodeError> {
        self.exact(ty, Scalar::Decimal)
    }

    /// Reads a `Duration`.
    ///
    /// # Errors
    ///
    /// As [`ValueReader::unit`].
    pub fn duration(&mut self, ty: &Type) -> Result<Duration, DecodeError> {
        self.exact(ty, Scalar::Duration).map(Duration::from_seconds)
    }

    /// Reads an `Instant`.
    ///
    /// # Errors
    ///
    /// As [`ValueReader::unit`].
    pub fn instant(&mut self, ty: &Type) -> Result<Instant, DecodeError> {
        self.exact(ty, Scalar::Instant)
            .map(Instant::from_unix_seconds)
    }

    /// Reads a `Text`.
    ///
    /// # Errors
    ///
    /// As [`ValueReader::unit`].
    pub fn text(&mut self, ty: &Type) -> Result<&'b str, DecodeError> {
        if !matches!(form(self.catalog, ty), Form::Text) {
            return Err(self.mismatch(ty));
        }
        self.reader
            .text(self.limits)
            .map_err(|error| self.here(error))
    }

    /// Reads `Bytes`.
    ///
    /// # Errors
    ///
    /// As [`ValueReader::unit`].
    pub fn bytes(&mut self, ty: &Type) -> Result<&'b [u8], DecodeError> {
        if !matches!(form(self.catalog, ty), Form::Bytes) {
            return Err(self.mismatch(ty));
        }
        self.reader
            .bytes(self.limits)
            .map_err(|error| self.here(error))
    }

    /// Reads a host type's value, its token.
    ///
    /// # Errors
    ///
    /// As [`ValueReader::unit`].
    pub fn host(&mut self, ty: &Type) -> Result<&'b str, DecodeError> {
        if !matches!(form(self.catalog, ty), Form::Host) {
            return Err(self.mismatch(ty));
        }
        self.reader
            .text(self.limits)
            .map_err(|error| self.here(error))
    }

    /// Reads an aggregate one level deeper, as `read` does.
    fn within<T>(
        &mut self,
        read: impl FnOnce(&mut Self) -> Result<T, DecodeError>,
    ) -> Result<T, DecodeError> {
        let outer = self.level;
        self.level = self.enter(outer)?;
        let read = read(self);
        self.level = outer;
        read
    }

    /// Reads a list.
    ///
    /// # Errors
    ///
    /// When `ty` is no list, or the bytes are not one of `T`s.
    pub fn list<T: Shaped>(&mut self, ty: &Type) -> Result<Vec<T>, DecodeError> {
        let catalog = self.catalog;
        let Form::List(item) = form(catalog, ty) else {
            return Err(self.mismatch(ty));
        };
        self.within(|me| {
            let count = me.count(&[item])?;
            let mut items = Vec::with_capacity(me.backed(count));
            for index in 0..count {
                me.path.index(index);
                items.push(T::read_at(me, item)?);
                me.path.pop();
            }
            Ok(items)
        })
    }

    /// The runtime value of the part read since byte `starts`, a value of
    /// `ty`, for its place in Flow's order.
    fn order(&self, ty: &Type, starts: usize) -> Result<Value, DecodeError> {
        let mut reader = Reader::new(self.reader.since(starts));
        ValueReader {
            catalog: self.catalog,
            limits: self.limits,
            path: self.path.clone(),
            reader: &mut reader,
            zero_width_left: self.limits.text_bytes,
            level: self.level,
        }
        .value(ty, self.level)
    }

    /// Reads a set, its elements in ascending order.
    ///
    /// # Errors
    ///
    /// When `ty` is no set, the bytes are not one of `T`s, or its elements
    /// are out of order or repeat.
    pub fn set<T: Shaped + Ord>(&mut self, ty: &Type) -> Result<BTreeSet<T>, DecodeError> {
        let catalog = self.catalog;
        let Form::Set(item) = form(catalog, ty) else {
            return Err(self.mismatch(ty));
        };
        self.within(|me| {
            let count = me.count(&[item])?;
            let mut items = BTreeSet::new();
            let mut previous = None;
            for index in 0..count {
                me.path.index(index);
                let starts = me.reader.position();
                items.insert(T::read_at(me, item)?);
                let order = me.order(item, starts)?;
                me.path.pop();
                if let Some(before) = &previous {
                    me.after("element", index, before, &order)?;
                }
                previous = Some(order);
            }
            Ok(items)
        })
    }

    /// Reads a dictionary, its entries in ascending order of their keys.
    ///
    /// # Errors
    ///
    /// When `ty` is no dictionary, the bytes are not one of `K`s and `V`s,
    /// or its keys are out of order or repeat.
    pub fn dict<K: Shaped + Ord, V: Shaped>(
        &mut self,
        ty: &Type,
    ) -> Result<BTreeMap<K, V>, DecodeError> {
        let catalog = self.catalog;
        let Form::Dict(key, item) = form(catalog, ty) else {
            return Err(self.mismatch(ty));
        };
        self.within(|me| {
            let count = me.count(&[key, item])?;
            let mut entries = BTreeMap::new();
            let mut previous = None;
            for index in 0..count {
                me.path.index(index);
                me.path.index(0);
                let starts = me.reader.position();
                let each = K::read_at(me, key)?;
                let order = me.order(key, starts)?;
                me.path.pop();
                me.path.index(1);
                let held = V::read_at(me, item)?;
                me.path.pop();
                me.path.pop();
                if let Some(before) = &previous {
                    me.after("key", index, before, &order)?;
                }
                previous = Some(order);
                entries.insert(each, held);
            }
            Ok(entries)
        })
    }

    /// Reads the parts of an aggregate of `types` as `read` does, then
    /// refuses any part it left unread.
    fn parts<T>(
        &mut self,
        ty: &Type,
        mut fields: Fields,
        read: impl FnOnce(&mut Self, &mut Fields) -> Result<T, DecodeError>,
    ) -> Result<T, DecodeError> {
        let value = read(self, &mut fields)?;
        if fields.at == fields.types.len() {
            Ok(value)
        } else {
            Err(self.mismatch(ty))
        }
    }

    /// Reads a tuple, its parts by `read`.
    ///
    /// # Errors
    ///
    /// When `ty` is no tuple, or `read` refuses or leaves a part unread.
    pub fn tuple<T>(
        &mut self,
        ty: &Type,
        read: impl FnOnce(&mut Self, &mut Fields) -> Result<T, DecodeError>,
    ) -> Result<T, DecodeError> {
        let catalog = self.catalog;
        let Form::Tuple(types) = form(catalog, ty) else {
            return Err(self.mismatch(ty));
        };
        let fields = Fields {
            types: types.to_vec(),
            step: Step::Index,
            at: 0,
        };
        self.within(|me| me.parts(ty, fields, read))
    }

    /// Reads a record, its fields by `read` in declaration order.
    ///
    /// # Errors
    ///
    /// When `ty` is no record, or `read` refuses or leaves a field unread.
    pub fn record<T>(
        &mut self,
        ty: &Type,
        read: impl FnOnce(&mut Self, &mut Fields) -> Result<T, DecodeError>,
    ) -> Result<T, DecodeError> {
        let catalog = self.catalog;
        let Some(record) = form(catalog, ty).record() else {
            return Err(self.mismatch(ty));
        };
        let fields = Fields {
            types: record.fields,
            step: Step::Field(Arc::clone(record.shape)),
            at: 0,
        };
        self.within(|me| me.parts(ty, fields, read))
    }

    /// Reads a value of the enum `ty`, `Option` and `Result` included:
    /// `read` is given its constructor's index and reads its payload.
    ///
    /// # Errors
    ///
    /// When `ty` is no enum, the bytes name a constructor it does not have,
    /// or `read` refuses or leaves a part unread.
    pub fn variant<T>(
        &mut self,
        ty: &Type,
        read: impl FnOnce(&mut Self, usize, &mut Fields) -> Result<T, DecodeError>,
    ) -> Result<T, DecodeError> {
        let catalog = self.catalog;
        let Some(shape) = form(catalog, ty).enumeration() else {
            return Err(self.mismatch(ty));
        };
        let index = self.reader.count().map_err(|error| self.here(error))?;
        let (Some(types), Some(ctor)) = (shape.parts(index), shape.shape.constructor(index)) else {
            return Err(self.refuse(
                DecodeErrorKind::Mismatch,
                format!(
                    "names constructor {index}, which {} does not have",
                    catalog.name(ty)
                ),
            ));
        };
        let fields = Fields {
            types: types.into_iter().map(Cow::into_owned).collect(),
            step: Step::Payload(Arc::clone(shape.shape), index),
            at: 0,
        };
        self.within(|me| {
            me.path.constructor(ctor.name());
            let value = me.parts(ty, fields, |me, fields| read(me, index, fields))?;
            me.path.pop();
            Ok(value)
        })
    }

    /// Reads a value of the newtype `ty` as its base's `T`, held to the form
    /// `ty` has, if any.
    ///
    /// # Errors
    ///
    /// When `ty` is no newtype, the bytes are not a `T` of its base, or the
    /// value is out of its form.
    pub fn newtype<T: Shaped>(&mut self, ty: &Type) -> Result<T, DecodeError> {
        let catalog = self.catalog;
        let Form::Newtype(base, held) = form(catalog, ty) else {
            return Err(self.mismatch(ty));
        };
        let starts = self.reader.position();
        let value = T::read_at(self, &base)?;
        if let Some(held) = held {
            let text = Reader::new(self.reader.since(starts))
                .text(self.limits)
                .map_err(|error| self.here(error))?;
            if let Some(problem) = held.refusal(text) {
                return Err(self.refuse(DecodeErrorKind::Mismatch, problem));
            }
        }
        Ok(value)
    }

    /// Reads one value of `ty`, checked as [`crate::read_value`] checks it,
    /// and gives its bytes.
    ///
    /// # Errors
    ///
    /// When the bytes are not a value of `ty` within the limits.
    pub fn encoded(&mut self, ty: &Type) -> Result<&'b [u8], DecodeError> {
        let starts = self.reader.position();
        self.value(ty, self.level)?;
        Ok(self.reader.since(starts))
    }
}