Skip to main content

flow_abi/
encode.rs

1//! Encoding a value at its type (`abi.md`, *The value encoding*), and the
2//! canonical text and hash taken over it.
3
4use std::borrow::Cow;
5use std::fmt;
6use std::sync::Arc;
7
8use flow_types::{OptionCtor, Payload};
9use flow_value::{Decimal, TaskId, Value, Variant};
10use sha2::{Digest as _, Sha256};
11
12use crate::build::{self, Walk};
13use crate::bytes::wide;
14use crate::catalog::{Catalog, StdForm};
15use crate::error::{EncodeError, EncodeErrorKind, Place, Step};
16use crate::form::{Form, form, part_types, reborrow};
17use crate::json::Json;
18use flow_types::{Body, Type};
19
20/// Returns `value`, of type `ty`, as JSON.
21///
22/// The encoding carries no type tags: the type decides it.
23///
24/// # Errors
25///
26/// A value that does not have the type, and a type with no encoding, are
27/// [`EncodeError`]s; a checked program reaches neither.
28pub fn encode(catalog: &Catalog, ty: &Type, value: &Value) -> Result<Json, EncodeError> {
29    Encoder::new(catalog, None, None).value(ty, value)
30}
31
32/// Returns `value`, of type `ty`, as [`encode`] writes it, except that a
33/// task is the id of the call it is parked on, which `tasks` gives for the
34/// task and the type of its result: how a viewer writes a value that holds
35/// tasks.
36///
37/// # Errors
38///
39/// As [`encode`], and when `tasks` names no call for a task.
40pub fn encode_naming_tasks(
41    catalog: &Catalog,
42    ty: &Type,
43    value: &Value,
44    tasks: &mut dyn FnMut(TaskId, &Type) -> Option<String>,
45) -> Result<Json, EncodeError> {
46    Encoder::new(catalog, Some(tasks), None).value(ty, value)
47}
48
49/// Returns `value`, of type `ty`, as [`encode`] writes it, except that
50/// bytes holding valid UTF-8 are written as that text: the form a person
51/// reads, which no decoder takes back.
52///
53/// # Errors
54///
55/// As [`encode`].
56pub fn encode_for_reading(
57    catalog: &Catalog,
58    ty: &Type,
59    value: &Value,
60) -> Result<Json, EncodeError> {
61    let mut encoder = Encoder::new(catalog, None, None);
62    encoder.reading = true;
63    encoder.value(ty, value)
64}
65
66/// Returns the canonical text of `value`, of type `ty`: the one text every
67/// equal value's JSON form shares, which `json.encode` and a run's output
68/// write (`abi.md`, *The canonical text*). History stores values in the
69/// binary encoding, not in this text.
70///
71/// # Errors
72///
73/// As [`encode`].
74pub fn canonical(catalog: &Catalog, ty: &Type, value: &Value) -> Result<String, EncodeError> {
75    Ok(encode(catalog, ty, value)?.canonical())
76}
77
78/// Returns the canonical text of `value`, of type `ty`, when it takes at
79/// most `max_bytes` bytes, and `None` otherwise.
80///
81/// The text is measured as the value is encoded, and encoding stops soon
82/// after it passes `max_bytes`: a value whose text would be far longer, such
83/// as a list holding one long text many times over, costs no more than the
84/// bound and the one part that crossed it.
85///
86/// # Errors
87///
88/// As [`encode`], for the part of `value` encoded before it stopped.
89pub fn canonical_within(
90    catalog: &Catalog,
91    ty: &Type,
92    value: &Value,
93    max_bytes: usize,
94) -> Result<Option<String>, EncodeError> {
95    let mut encoder = Encoder::new(catalog, None, Some(max_bytes));
96    match encoder.value(ty, value) {
97        Ok(json) => {
98            let text = json.canonical();
99            debug_assert_eq!(
100                encoder.room.map(|room| room + text.len()),
101                Some(max_bytes),
102                "measured exactly"
103            );
104            Ok(Some(text))
105        }
106        Err(_) if encoder.over => Ok(None),
107        Err(error) => Err(error),
108    }
109}
110
111/// A SHA-256 hash, written `sha256:` followed by lowercase hex.
112#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
113pub struct Digest(pub [u8; 32]);
114
115impl Digest {
116    /// The hash of `bytes`.
117    pub fn of(bytes: &[u8]) -> Digest {
118        Digest(Sha256::digest(bytes).into())
119    }
120
121    /// The hash as lowercase hex, without the `sha256:` prefix.
122    pub fn hex(&self) -> String {
123        use fmt::Write as _;
124        self.0
125            .iter()
126            .fold(String::with_capacity(64), |mut text, byte| {
127                let _ = write!(text, "{byte:02x}");
128                text
129            })
130    }
131}
132
133impl fmt::Display for Digest {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        write!(f, "sha256:{}", self.hex())
136    }
137}
138
139/// Whether two declarations are one: the same shape, or equal ones.
140fn same<T: PartialEq>(a: &Arc<T>, b: &Arc<T>) -> bool {
141    Arc::ptr_eq(a, b) || a == b
142}
143
144/// How a checkpoint names a task: by the id of its call, given the task and
145/// the type of its result.
146type Tasks<'c> = &'c mut dyn FnMut(TaskId, &Type) -> Option<String>;
147
148struct Encoder<'c> {
149    catalog: &'c Catalog,
150    path: Place,
151    /// How a checkpoint names a task; `None` outside one.
152    tasks: Option<Tasks<'c>>,
153    /// How many more bytes the canonical text may take; `None` for no
154    /// bound.
155    room: Option<usize>,
156    /// Whether encoding stopped because the text passed its bound.
157    over: bool,
158    /// Whether bytes holding valid UTF-8 are written as that text.
159    reading: bool,
160}
161
162impl<'c> Encoder<'c> {
163    fn new(catalog: &'c Catalog, tasks: Option<Tasks<'c>>, room: Option<usize>) -> Self {
164        Encoder {
165            catalog,
166            path: Place::default(),
167            tasks,
168            room,
169            over: false,
170            reading: false,
171        }
172    }
173
174    /// Counts `bytes` more of canonical text, or stops encoding when they
175    /// do not fit.
176    fn spend(&mut self, bytes: u128) -> Result<(), EncodeError> {
177        let Some(room) = &mut self.room else {
178            return Ok(());
179        };
180        match usize::try_from(bytes) {
181            Ok(bytes) if bytes <= *room => {
182                *room -= bytes;
183                Ok(())
184            }
185            _ => {
186                self.over = true;
187                Err(EncodeError::new(
188                    &self.path,
189                    EncodeErrorKind::TooLarge,
190                    "has a text longer than its bound",
191                ))
192            }
193        }
194    }
195
196    /// `text` as a JSON string.
197    fn string(&mut self, text: &str) -> Result<Json, EncodeError> {
198        self.spend(quoted_len(text))?;
199        Ok(Json::String(text.to_owned()))
200    }
201
202    /// `number` as a JSON number.
203    fn number(&mut self, number: Decimal) -> Result<Json, EncodeError> {
204        self.spend(number.text_len())?;
205        Ok(Json::Number(number))
206    }
207
208    /// The `[`, `]` and commas of an array of `items` elements, or the `{`,
209    /// `}` and commas of an object of `items` members.
210    fn brackets(&mut self, items: usize) -> Result<(), EncodeError> {
211        self.spend(2 + u128::from(wide(items.saturating_sub(1))))
212    }
213
214    /// How many of `count` parts can fit what is left of the bound: each
215    /// part's text is at least one byte, so a bounded encoding never
216    /// reserves room for more parts than it has bytes left.
217    fn room_for(&self, count: usize) -> usize {
218        self.room.map_or(count, |room| count.min(room))
219    }
220
221    /// Opens the aggregate `join` makes of `parts`.
222    fn open<'a>(&self, join: Join<'a>, parts: Parts<'a>) -> Begun<'a> {
223        let count = match &parts {
224            Parts::Items(_, value) => value.parts().len(),
225            Parts::Pairs(.., value) => value.parts().len() / 2,
226            Parts::Each(parts, _) => parts.len(),
227            Parts::Pair(_) => 2,
228            Parts::Members(..) | Parts::Fields(..) | Parts::One(..) | Parts::Payload(..) => 1,
229            Parts::Done => 0,
230        };
231        build::Frame::open(join, parts, self.room_for(count), 0)
232    }
233
234    /// The key of an object member and the `:` after it.
235    fn key(&mut self, name: &str) -> Result<(), EncodeError> {
236        self.spend(quoted_len(name) + 1)
237    }
238    fn mismatch(&self, ty: &Type) -> EncodeError {
239        EncodeError::new(
240            &self.path,
241            EncodeErrorKind::Mismatch,
242            format!("is not a value of {}", self.catalog.name(ty)),
243        )
244    }
245
246    /// Encodes `value`, of `ty`. The aggregates it is inside wait on a
247    /// stack on the heap, so the native stack does not grow with the value's
248    /// depth.
249    fn value(&mut self, ty: &Type, value: &Value) -> Result<Json, EncodeError> {
250        let root = self.begin(&Cow::Borrowed(ty), value)?;
251        build::build(self, root)
252    }
253
254    /// Begins encoding `value`, of `ty`: one that holds no other value is
255    /// done at once, and an aggregate is opened with the parts it holds.
256    fn begin<'a>(
257        &mut self,
258        ty: &Cow<'a, Type>,
259        value: &'a Value,
260    ) -> Result<Begun<'a>, EncodeError> {
261        let json = match (&**ty, value) {
262            (Type::Int, Value::Int(number)) => self.number(Decimal::from(number))?,
263            (Type::Decimal, Value::Decimal(number)) => self.number(number.clone())?,
264            (Type::Bool, Value::Bool(flag)) => self.boolean(*flag)?,
265            (Type::Text, Value::Text(text)) => self.string(text.as_str())?,
266            (Type::Bytes, Value::Bytes(bytes)) => {
267                match self.reading.then(|| bytes.to_text()).flatten() {
268                    Some(text) => self.string(text.as_str())?,
269                    None => self.string(&bytes.to_base64())?,
270                }
271            }
272            (Type::Duration, Value::Duration(span)) => self.string(&span.to_string())?,
273            (Type::Instant, Value::Instant(at)) => self.string(&at.to_string())?,
274            (Type::Unit, Value::Unit) => {
275                self.brackets(0)?;
276                Json::Array(Vec::new())
277            }
278            (Type::Json, Value::Variant(variant))
279                if same(variant.shape(), &self.catalog.json().shape) =>
280            {
281                return self.raw(variant);
282            }
283            (Type::List(_), Value::List(_)) | (Type::Set(_), Value::Set(_)) => {
284                let item = part_types(ty).swap_remove(0);
285                return Ok(self.open(Join::Brackets, Parts::Items(item, value)));
286            }
287            (Type::Dict(key, _), Value::Dict(entries)) => {
288                self.brackets(entries.len())?;
289                let text = *self.catalog.erase(key) == Type::Text;
290                let [key, item]: [Cow<'a, Type>; 2] = part_types(ty)
291                    .try_into()
292                    .expect("a key type and a value type");
293                return Ok(if text {
294                    self.open(
295                        Join::Object(Vec::with_capacity(self.room_for(entries.len())), None),
296                        Parts::Members(reborrow(ty), item, value, 0),
297                    )
298                } else {
299                    self.open(Join::Array, Parts::Pairs(key, item, value))
300                });
301            }
302            (Type::Option(_), Value::Variant(variant))
303                if same(variant.shape(), &self.catalog.option().shape) =>
304            {
305                // A value of std's `Option` is `None` or `Some` of one value.
306                let Some(inner) = variant.payload().first() else {
307                    return Ok(Begun::Done(self.string(OptionCtor::None.name())?));
308                };
309                let some = OptionCtor::Some.name();
310                self.brackets(1)?;
311                self.key(some)?;
312                let item = part_types(ty).swap_remove(0);
313                let parts = Parts::One(Step::Constructor(some.to_owned()), item, inner);
314                return Ok(self.open(Join::Member(some), parts));
315            }
316            (Type::Tuple(parts), Value::Tuple(tuple)) if parts.len() == tuple.parts().len() => {
317                let parts = Parts::Each(part_types(ty), tuple.parts());
318                return Ok(self.open(Join::Brackets, parts));
319            }
320            (Type::Named(..), _) => return self.named(ty, value),
321            (Type::Task(result), Value::Task(task)) if self.tasks.is_some() => {
322                let tasks = self.tasks.as_mut().expect("checked by the guard");
323                let Some(call) = tasks(*task, result) else {
324                    return Err(EncodeError::new(
325                        &self.path,
326                        EncodeErrorKind::Mismatch,
327                        "is a task that is not parked on its only call",
328                    ));
329                };
330                self.string(&call)?
331            }
332            (Type::NotData | Type::Function { .. } | Type::Param(_) | Type::Task(_), _) => {
333                return Err(self.no_encoding());
334            }
335            _ => return Err(self.mismatch(ty)),
336        };
337        Ok(Begun::Done(json))
338    }
339
340    /// Begins a `json.Value` as the JSON value it stands for.
341    fn raw<'a>(&mut self, variant: &'a Variant) -> Result<Begun<'a>, EncodeError> {
342        // Each constructor of `json.Value` carries a payload of its own kind,
343        // so the payload names the constructor.
344        let json = match variant.payload() {
345            [] => {
346                self.spend(4)?;
347                Json::Null
348            }
349            [Value::Bool(value)] => self.boolean(*value)?,
350            [Value::Decimal(value)] => self.number(value.clone())?,
351            [Value::Text(value)] => self.string(value.as_str())?,
352            [list @ Value::List(_)] => {
353                return Ok(self.open(Join::Brackets, Parts::Items(Cow::Borrowed(&JSON), list)));
354            }
355            [value @ Value::Dict(_)] => {
356                return self.begin(&Cow::Owned(Type::dict(Type::Text, Type::Json)), value);
357            }
358            _ => return Err(self.mismatch(&Type::Json)),
359        };
360        Ok(Begun::Done(json))
361    }
362
363    /// Begins a value of a declared record, enum, newtype or host type.
364    fn named<'a>(&mut self, ty: &Type, value: &'a Value) -> Result<Begun<'a>, EncodeError> {
365        let Type::Named(decl, args) = ty else {
366            unreachable!("a declared type")
367        };
368        if let Form::Newtype(base, held) = form(self.catalog, ty) {
369            if let Some(problem) = StdForm::out_of(held, value) {
370                return Err(EncodeError::new(
371                    &self.path,
372                    EncodeErrorKind::Mismatch,
373                    problem,
374                ));
375            }
376            return self.begin(&Cow::Owned(base), value);
377        }
378        match (&self.catalog.decl(*decl).body, value) {
379            (Body::Record(shape, fields), Value::Record(record)) if same(record.shape(), shape) => {
380                let fields: Vec<_> = record
381                    .shape()
382                    .fields()
383                    .zip(fields.iter().map(|field| Cow::Owned(field.subst(args))))
384                    .zip(record.fields())
385                    .collect();
386                let members = Vec::with_capacity(fields.len());
387                Ok(self.open(Join::Fields(members, None), Parts::Fields(fields, 0)))
388            }
389            (Body::Enum(shape, ctors), Value::Variant(variant)) if same(variant.shape(), shape) => {
390                let parts = ctors[variant.index()]
391                    .iter()
392                    .map(|part| Cow::Owned(part.subst(args)))
393                    .collect();
394                self.variant(variant, parts)
395            }
396            (Body::NonData, _) => Err(self.no_encoding()),
397            (Body::Host, Value::Host(token)) => Ok(Begun::Done(self.string(token.as_str())?)),
398            _ => Err(self.mismatch(ty)),
399        }
400    }
401
402    fn no_encoding(&self) -> EncodeError {
403        EncodeError::new(
404            &self.path,
405            EncodeErrorKind::NoEncoding,
406            "has a type with no encoding",
407        )
408    }
409
410    /// Begins an enum value: its constructor's name, alone or keying its
411    /// payload of the types `parts`.
412    fn variant<'a>(
413        &mut self,
414        variant: &'a Variant,
415        mut parts: Vec<Cow<'a, Type>>,
416    ) -> Result<Begun<'a>, EncodeError> {
417        let ctor = variant.constructor();
418        let name = ctor.name();
419        let payload = match ctor.payload() {
420            Payload::None => return Ok(Begun::Done(self.string(name)?)),
421            Payload::Positional(1) => {
422                let ty = parts.pop().expect("one part");
423                Parts::One(
424                    Step::Constructor(name.to_owned()),
425                    ty,
426                    &variant.payload()[0],
427                )
428            }
429            Payload::Positional(_) => Parts::Payload(
430                name,
431                Box::new(Parts::Each(parts, variant.payload())),
432                Join::Brackets,
433            ),
434            Payload::Named(names) => {
435                let fields: Vec<_> = names
436                    .iter()
437                    .map(|name| &**name)
438                    .zip(parts)
439                    .zip(variant.payload())
440                    .collect();
441                let members = Vec::with_capacity(fields.len());
442                Parts::Payload(
443                    name,
444                    Box::new(Parts::Fields(fields, 0)),
445                    Join::Fields(members, None),
446                )
447            }
448        };
449        Ok(self.open(Join::Variant(name), payload))
450    }
451
452    /// `flag` as a JSON boolean.
453    #[expect(
454        clippy::fn_params_excessive_bools,
455        reason = "the flag is the value written, not a choice of how to write it"
456    )]
457    fn boolean(&mut self, flag: bool) -> Result<Json, EncodeError> {
458        self.spend(if flag { 4 } else { 5 })?;
459        Ok(Json::Bool(flag))
460    }
461}
462
463impl Encoder<'_> {
464    /// Moves the part of `frame` made last into the object it is a member
465    /// of, under its key.
466    fn settle(&mut self, frame: &mut Frame<'_>) -> Result<(), EncodeError> {
467        let (members, name) = match &mut frame.make {
468            Join::Object(members, last) => match last.take() {
469                Some(name) => (members, name),
470                None => return Ok(()),
471            },
472            Join::Fields(members, last) => match last.take() {
473                Some(name) => {
474                    self.key(name)?;
475                    (members, name)
476                }
477                None => return Ok(()),
478            },
479            Join::Array | Join::Brackets | Join::Member(_) | Join::Variant(_) => return Ok(()),
480        };
481        let value = frame.values.pop().expect("the member just made");
482        members.push((name.to_owned(), value));
483        Ok(())
484    }
485
486    /// Begins the next field of `frame`, a record's or a named payload's,
487    /// that is written, and steps the path onto it.
488    fn next_field<'a>(&mut self, frame: &mut Frame<'a>) -> Result<Option<Begun<'a>>, EncodeError> {
489        let Parts::Fields(fields, index) = &mut frame.parts else {
490            unreachable!("a frame of fields")
491        };
492        loop {
493            let Some(((name, ty), value)) = fields.get_mut(*index) else {
494                return Ok(None);
495            };
496            *index += 1;
497            let (name, value): (&'a str, &'a Value) = (*name, *value);
498            let ty = std::mem::replace(ty, Cow::Borrowed(&JSON));
499            let payload = match (&*self.catalog.erase(&ty), value) {
500                (Type::Option(item), Value::Variant(variant))
501                    if same(variant.shape(), &self.catalog.option().shape) =>
502                {
503                    Some(
504                        variant
505                            .payload()
506                            .first()
507                            .map(|inner| (Cow::Owned((**item).clone()), inner)),
508                    )
509                }
510                _ => None,
511            };
512            // An `Option` field holding `None` is left out, and one holding
513            // `Some` is written as its payload.
514            let Some((ty, value)) = payload.unwrap_or(Some((ty, value))) else {
515                continue;
516            };
517            if let Join::Fields(_, last) = &mut frame.make {
518                *last = Some(name);
519            }
520            self.path.field(name);
521            return self.begin(&ty, value).map(Some);
522        }
523    }
524}
525
526/// `json.Value`, the type of each element of a JSON array.
527static JSON: Type = Type::Json;
528
529/// A value whose encoding has begun.
530type Begun<'a> = build::Begun<Parts<'a>, Join<'a>, Json>;
531
532/// An aggregate being encoded.
533type Frame<'a> = build::Frame<Parts<'a>, Join<'a>, Json>;
534
535/// Where the parts of an aggregate being encoded come from.
536enum Parts<'a> {
537    /// The elements of this list or set, all of this type, each at its
538    /// index.
539    Items(Cow<'a, Type>, &'a Value),
540    /// Parts each of its own type, each at its index.
541    Each(Vec<Cow<'a, Type>>, &'a [Value]),
542    /// A dictionary of this type whose keys are text, its values of this
543    /// type, each under its key: the entries of this dictionary, from the
544    /// one at this index.
545    Members(Cow<'a, Type>, Cow<'a, Type>, &'a Value, usize),
546    /// A dictionary's entries of these key and value types, each a pair at
547    /// its index: the entries of this dictionary.
548    Pairs(Cow<'a, Type>, Cow<'a, Type>, &'a Value),
549    /// One value of this type at this step, until it is taken.
550    One(Step, Cow<'a, Type>, &'a Value),
551    /// A key and a value, of these types, in turn.
552    Pair([(Cow<'a, Type>, &'a Value); 2]),
553    /// Named fields, each of its type, from the next one's.
554    Fields(Vec<((&'a str, Cow<'a, Type>), &'a Value)>, usize),
555    /// A constructor's payload of several parts, made by this join, until
556    /// it is taken.
557    Payload(&'a str, Box<Parts<'a>>, Join<'a>),
558    /// Nothing more.
559    Done,
560}
561
562/// What an aggregate's encoded parts make.
563enum Join<'a> {
564    /// An array of them, its brackets counted before they were.
565    Array,
566    /// An array of them, its brackets counted after.
567    Brackets,
568    /// An object of these members and one more under the key of the last
569    /// part begun, once it is made; each key counted before its value.
570    Object(Vec<(String, Json)>, Option<&'a str>),
571    /// An object of these members and one more under the field name of the
572    /// last part begun, once it is made; each name counted after its value.
573    Fields(Vec<(String, Json)>, Option<&'a str>),
574    /// An object of one member, the part, under this key, counted before.
575    Member(&'a str),
576    /// An object of one member, the part, under this constructor's name,
577    /// counted after.
578    Variant(&'a str),
579}
580
581impl<'a> Walk<Parts<'a>, Join<'a>, Json> for Encoder<'_> {
582    type Error = EncodeError;
583
584    fn path(&mut self) -> &mut Place {
585        &mut self.path
586    }
587
588    fn next(&mut self, frame: &mut Frame<'a>) -> Result<Option<Begun<'a>>, EncodeError> {
589        self.settle(frame)?;
590        match &mut frame.parts {
591            Parts::Items(ty, items) => {
592                let at = frame.values.len();
593                let Some(item) = items.part(at) else {
594                    return Ok(None);
595                };
596                self.path.index(at);
597                self.begin(ty, item).map(Some)
598            }
599            Parts::Each(parts, values) => {
600                let at = frame.values.len();
601                let Some((ty, value)) = parts.get(at).zip(values.get(at)) else {
602                    return Ok(None);
603                };
604                self.path.index(at);
605                self.begin(ty, value).map(Some)
606            }
607            Parts::Members(dict, item, entries, index) => {
608                let at = 2 * *index;
609                let Some((name, entry)) = entries.part(at).zip(entries.part(at + 1)) else {
610                    return Ok(None);
611                };
612                *index += 1;
613                let Value::Text(name) = name else {
614                    return Err(self.mismatch(dict));
615                };
616                let name = name.as_str();
617                self.key(name)?;
618                if let Join::Object(_, last) = &mut frame.make {
619                    *last = Some(name);
620                }
621                self.path.key(name);
622                self.begin(item, entry).map(Some)
623            }
624            Parts::Pairs(key, item, entries) => {
625                let at = 2 * frame.values.len();
626                let Some((name, entry)) = entries.part(at).zip(entries.part(at + 1)) else {
627                    return Ok(None);
628                };
629                self.path.index(frame.values.len());
630                self.brackets(2)?;
631                let pair = [(reborrow(key), name), (reborrow(item), entry)];
632                Ok(Some(self.open(Join::Array, Parts::Pair(pair))))
633            }
634            Parts::One(..) => {
635                let Parts::One(step, ty, value) = std::mem::replace(&mut frame.parts, Parts::Done)
636                else {
637                    unreachable!("matched above")
638                };
639                self.path.push(step);
640                self.begin(&ty, value).map(Some)
641            }
642            Parts::Pair(pair) => {
643                let index = frame.values.len();
644                let Some((ty, value)) = pair.get(index) else {
645                    return Ok(None);
646                };
647                self.path.index(index);
648                self.begin(ty, value).map(Some)
649            }
650            Parts::Fields(..) => self.next_field(frame),
651            Parts::Payload(..) => {
652                let Parts::Payload(name, parts, join) =
653                    std::mem::replace(&mut frame.parts, Parts::Done)
654                else {
655                    unreachable!("matched above")
656                };
657                self.path.constructor(name);
658                Ok(Some(self.open(join, *parts)))
659            }
660            Parts::Done => Ok(None),
661        }
662    }
663
664    fn steps(_: &Frame<'a>) -> usize {
665        1
666    }
667
668    fn finish(&mut self, mut frame: Frame<'a>) -> Result<Json, EncodeError> {
669        self.settle(&mut frame)?;
670        let values = frame.values;
671        Ok(match frame.make {
672            Join::Array => Json::Array(values),
673            Join::Brackets => {
674                self.brackets(values.len())?;
675                Json::Array(values)
676            }
677            Join::Object(members, _) => Json::Object(members),
678            Join::Fields(members, _) => {
679                self.brackets(members.len())?;
680                Json::Object(members)
681            }
682            Join::Member(key) => Json::Object(vec![(key.to_owned(), one(values))]),
683            Join::Variant(name) => {
684                self.brackets(1)?;
685                self.key(name)?;
686                Json::Object(vec![(name.to_owned(), one(values))])
687            }
688        })
689    }
690}
691
692/// The one value of a frame of one part.
693fn one(values: Vec<Json>) -> Json {
694    values.into_iter().next().expect("one part")
695}
696
697/// How many bytes `text` takes as a canonical JSON string, quotes included
698/// (`abi.md`, *The canonical form*).
699fn quoted_len(text: &str) -> u128 {
700    let escaped: usize = text
701        .chars()
702        .map(|code_point| match code_point {
703            '"' | '\\' | '\u{8}' | '\u{c}' | '\n' | '\r' | '\t' => 2,
704            '\u{0}'..='\u{1f}' => 6,
705            other => other.len_utf8(),
706        })
707        .sum();
708    u128::from(wide(escaped)) + 2
709}