Skip to main content

flow_abi/
binary.rs

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