1use 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
33pub 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
48pub 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
68pub 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
114fn same<T: PartialEq>(a: &Arc<T>, b: &Arc<T>) -> bool {
116 Arc::ptr_eq(a, b) || a == b
117}
118
119#[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 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 #[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 #[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 #[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 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
287type Writing<'a> = Begun<Writes<'a>, Make, ()>;
289
290struct 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 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 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
365pub(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
374pub 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
408pub 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
437pub 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
461pub fn write_instant(out: &mut Vec<u8>, at: &Instant) {
463 decimal_into(out, at.unix_seconds());
464}
465
466pub 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#[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 pub(crate) zero_width_left: usize,
515 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 pub(crate) fn here(&self, mut error: DecodeError) -> DecodeError {
526 error.path = self.path.clone();
527 error
528 }
529
530 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 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 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 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 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 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 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 pub(crate) fn backed(&self, count: usize) -> usize {
702 count.min(self.reader.remaining())
703 }
704
705 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 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
777enum Parts<'t> {
780 Items(Cow<'t, Type>, usize),
782 Each(Vec<Cow<'t, Type>>),
784 Entries(Cow<'t, Type>, Cow<'t, Type>, usize),
786 One(Cow<'t, Type>),
788}
789
790fn 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#[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
848fn part_steps(parts: &Parts<'_>, done: usize) -> usize {
851 match parts {
852 Parts::One(_) => 0,
853 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
899fn 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}