crux_cli/codegen/serde_generate/
format.rs

1// Copyright (c) Facebook, Inc. and its affiliates
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Module defining the Abstract Syntax Tree (AST) of Serde formats.
5//!
6//! Node of the AST are made of the following types:
7//! * `ContainerFormat`: the format of a container (struct or enum),
8//! * `Format`: the format of an unnamed value,
9//! * `Named<Format>`: the format of a field in a struct,
10//! * `VariantFormat`: the format of a variant in a enum,
11//! * `Named<VariantFormat>`: the format of a variant in a enum, together with its name,
12//! * `Variable<Format>`: a variable holding an initially unknown value format,
13//! * `Variable<VariantFormat>`: a variable holding an initially unknown variant format.
14
15#![allow(dead_code)]
16
17use error::{Error, Result};
18use serde::{
19    de, ser,
20    ser::{SerializeMap, SerializeStruct},
21    Deserialize, Serialize,
22};
23use std::{
24    cell::{Ref, RefCell, RefMut},
25    collections::{btree_map::Entry, BTreeMap},
26    rc::Rc,
27};
28
29use super::error;
30
31/// Serde-based serialization format for anonymous "value" types.
32#[derive(Serialize, Deserialize, Debug, Eq, Clone, PartialEq, Hash)]
33#[serde(rename_all = "UPPERCASE")]
34pub enum Format {
35    /// A format whose value is initially unknown. Used internally for tracing. Not (de)serializable.
36    Variable(#[serde(with = "not_implemented")] Variable<Format>),
37    /// The name of a container.
38    TypeName(String),
39
40    // The formats of primitive types
41    Unit,
42    Bool,
43    I8,
44    I16,
45    I32,
46    I64,
47    I128,
48    U8,
49    U16,
50    U32,
51    U64,
52    U128,
53    F32,
54    F64,
55    Char,
56    Str,
57    Bytes,
58
59    /// The format of `Option<T>`.
60    Option(Box<Format>),
61    /// A sequence, e.g. the format of `Vec<Foo>`.
62    Seq(Box<Format>),
63    /// A map, e.g. the format of `BTreeMap<K, V>`.
64    #[serde(rename_all = "UPPERCASE")]
65    Map {
66        key: Box<Format>,
67        value: Box<Format>,
68    },
69
70    /// A tuple, e.g. the format of `(Foo, Bar)`.
71    Tuple(Vec<Format>),
72    /// Alias for `(Foo, ... Foo)`.
73    /// E.g. the format of `[Foo; N]`.
74    #[serde(rename_all = "UPPERCASE")]
75    TupleArray {
76        content: Box<Format>,
77        size: usize,
78    },
79}
80
81/// Serde-based serialization format for named "container" types.
82/// In Rust, those are enums and structs.
83#[derive(Serialize, Deserialize, Debug, Eq, Clone, PartialEq, Hash)]
84#[serde(rename_all = "UPPERCASE")]
85pub enum ContainerFormat {
86    /// An empty struct, e.g. `struct A`.
87    UnitStruct,
88    /// A struct with a single unnamed parameter, e.g. `struct A(u16)`
89    NewTypeStruct(Box<Format>),
90    /// A struct with several unnamed parameters, e.g. `struct A(u16, u32)`
91    TupleStruct(Vec<Format>),
92    /// A struct with named parameters, e.g. `struct A { a: Foo }`.
93    Struct(Vec<Named<Format>>),
94    /// An enum, that is, an enumeration of variants.
95    /// Each variant has a unique name and index within the enum.
96    Enum(BTreeMap<usize, Named<VariantFormat>>),
97}
98
99#[derive(Debug, Clone, Default, Eq, PartialEq, Hash)]
100/// A named value.
101/// Used for named parameters or variants.
102pub struct Named<T> {
103    pub name: String,
104    pub value: T,
105}
106
107#[derive(Debug, Clone, Default, Eq, PartialEq)]
108/// A mutable holder for an initially unknown value.
109pub struct Variable<T>(Rc<RefCell<Option<T>>>);
110
111impl<T: std::hash::Hash> std::hash::Hash for Variable<T> {
112    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
113        self.0.borrow().hash(state);
114    }
115}
116
117#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq, Hash)]
118#[serde(rename_all = "UPPERCASE")]
119/// Description of a variant in an enum.
120pub enum VariantFormat {
121    /// A variant whose format is initially unknown. Used internally for tracing. Not (de)serializable.
122    Variable(#[serde(with = "not_implemented")] Variable<VariantFormat>),
123    /// A variant without parameters, e.g. `A` in `enum X { A }`
124    Unit,
125    /// A variant with a single unnamed parameter, e.g. `A` in `enum X { A(u16) }`
126    NewType(Box<Format>),
127    /// A struct with several unnamed parameters, e.g. `A` in `enum X { A(u16, u32) }`
128    Tuple(Vec<Format>),
129    /// A struct with named parameters, e.g. `A` in `enum X { A { a: Foo } }`
130    Struct(Vec<Named<Format>>),
131}
132
133/// Common methods for nodes in the AST of formats.
134pub trait FormatHolder {
135    /// Visit all the formats in `self` in a depth-first way.
136    /// Variables are not supported and will cause an error.
137    fn visit<'a>(&'a self, f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()>;
138
139    /// Mutably visit all the formats in `self` in a depth-first way.
140    /// * Replace variables (if any) with their known values then apply the
141    ///   visiting function `f`.
142    /// * Return an error if any variable has still an unknown value (thus cannot be removed).
143    fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()>;
144
145    /// Update variables and add missing enum variants so that the terms match.
146    /// This is a special case of [term unification](https://en.wikipedia.org/wiki/Unification_(computer_science)):
147    /// * Variables occurring in `other` must be "fresh" and distinct
148    ///   from each other. By "fresh", we mean that they do not occur in `self`
149    ///   and have no known value yet.
150    /// * If needed, enums in `self` will be extended with new variants taken from `other`.
151    /// * Although the parameter `other` is consumed (i.e. taken by value), all
152    ///   variables occurring either in `self` or `other` are correctly updated.
153    fn unify(&mut self, other: Self) -> Result<()>;
154
155    /// Finalize the formats within `self` by removing variables and making sure
156    /// that all eligible tuples are compressed into a `TupleArray`. Return an error
157    /// if any variable has an unknown value.
158    fn normalize(&mut self) -> Result<()> {
159        self.visit_mut(&mut |format: &mut Format| {
160            let normalized = match format {
161                Format::Tuple(formats) => {
162                    let size = formats.len();
163                    if size <= 1 {
164                        return Ok(());
165                    }
166                    let format0 = &formats[0];
167                    for format in formats.iter().skip(1) {
168                        if format != format0 {
169                            return Ok(());
170                        }
171                    }
172                    Format::TupleArray {
173                        content: Box::new(std::mem::take(&mut formats[0])),
174                        size,
175                    }
176                }
177                _ => {
178                    return Ok(());
179                }
180            };
181            *format = normalized;
182            Ok(())
183        })
184    }
185
186    /// Attempt to remove known variables within `self`. Silently abort
187    /// if some variables have unknown values.
188    fn reduce(&mut self) {
189        self.visit_mut(&mut |_| Ok(())).unwrap_or(());
190    }
191
192    /// Whether this format is a variable with no known value yet.
193    fn is_unknown(&self) -> bool;
194}
195
196fn unification_error<T1, T2>(v1: T1, v2: T2) -> Error
197where
198    T1: std::fmt::Debug,
199    T2: std::fmt::Debug,
200{
201    Error::Incompatible(format!("{v1:?}"), format!("{v2:?}"))
202}
203
204impl FormatHolder for VariantFormat {
205    fn visit<'a>(&'a self, f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()> {
206        match self {
207            Self::Variable(variable) => variable.visit(f)?,
208            Self::Unit => (),
209            Self::NewType(format) => format.visit(f)?,
210            Self::Tuple(formats) => {
211                for format in formats {
212                    format.visit(f)?;
213                }
214            }
215            Self::Struct(named_formats) => {
216                for format in named_formats {
217                    format.visit(f)?;
218                }
219            }
220        }
221        Ok(())
222    }
223
224    fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()> {
225        match self {
226            Self::Variable(variable) => {
227                variable.visit_mut(f)?;
228                // At this point, `variable` is known and points to variable-free content.
229                // Remove the variable.
230                *self = std::mem::take(variable)
231                    .into_inner()
232                    .expect("variable is known");
233            }
234            Self::Unit => (),
235            Self::NewType(format) => {
236                format.visit_mut(f)?;
237            }
238            Self::Tuple(formats) => {
239                for format in formats {
240                    format.visit_mut(f)?;
241                }
242            }
243            Self::Struct(named_formats) => {
244                for format in named_formats {
245                    format.visit_mut(f)?;
246                }
247            }
248        }
249        Ok(())
250    }
251
252    fn unify(&mut self, format: VariantFormat) -> Result<()> {
253        match (self, format) {
254            (format1, Self::Variable(variable2)) => {
255                if let Some(format2) = &mut *variable2.borrow_mut() {
256                    format1.unify(std::mem::take(format2))?;
257                }
258                *variable2.borrow_mut() = Some(format1.clone());
259            }
260            (Self::Variable(variable1), format2) => {
261                let inner_variable = match &mut *variable1.borrow_mut() {
262                    value1 @ None => {
263                        *value1 = Some(format2);
264                        None
265                    }
266                    Some(format1) => {
267                        format1.unify(format2)?;
268                        match format1 {
269                            Self::Variable(variable) => Some(variable.clone()),
270                            _ => None,
271                        }
272                    }
273                };
274                // Reduce multiple indirections to a single one.
275                if let Some(variable) = inner_variable {
276                    *variable1 = variable;
277                }
278            }
279
280            (Self::Unit, Self::Unit) => (),
281
282            (Self::NewType(format1), Self::NewType(format2)) => {
283                format1.as_mut().unify(*format2)?;
284            }
285
286            (Self::Tuple(formats1), Self::Tuple(formats2)) if formats1.len() == formats2.len() => {
287                for (format1, format2) in formats1.iter_mut().zip(formats2.into_iter()) {
288                    format1.unify(format2)?;
289                }
290            }
291
292            (Self::Struct(named_formats1), Self::Struct(named_formats2))
293                if named_formats1.len() == named_formats2.len() =>
294            {
295                for (format1, format2) in named_formats1.iter_mut().zip(named_formats2.into_iter())
296                {
297                    format1.unify(format2)?;
298                }
299            }
300
301            (format1, format2) => {
302                return Err(unification_error(format1, format2));
303            }
304        }
305        Ok(())
306    }
307
308    fn is_unknown(&self) -> bool {
309        if let Self::Variable(v) = self {
310            return v.is_unknown();
311        }
312        false
313    }
314}
315
316impl<T> FormatHolder for Named<T>
317where
318    T: FormatHolder + std::fmt::Debug,
319{
320    fn visit<'a>(&'a self, f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()> {
321        self.value.visit(f)
322    }
323
324    fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()> {
325        self.value.visit_mut(f)
326    }
327
328    fn unify(&mut self, other: Named<T>) -> Result<()> {
329        if self.name != other.name {
330            return Err(unification_error(&*self, &other));
331        }
332        self.value.unify(other.value)
333    }
334
335    fn is_unknown(&self) -> bool {
336        false
337    }
338}
339
340impl<T> Variable<T> {
341    pub(crate) fn new(content: Option<T>) -> Self {
342        Self(Rc::new(RefCell::new(content)))
343    }
344
345    pub fn borrow(&self) -> Ref<Option<T>> {
346        self.0.as_ref().borrow()
347    }
348
349    pub fn borrow_mut(&self) -> RefMut<Option<T>> {
350        self.0.as_ref().borrow_mut()
351    }
352}
353
354impl<T> Variable<T>
355where
356    T: Clone,
357{
358    fn into_inner(self) -> Option<T> {
359        match Rc::try_unwrap(self.0) {
360            Ok(cell) => cell.into_inner(),
361            Err(rc) => rc.borrow().clone(),
362        }
363    }
364}
365
366mod not_implemented {
367    pub fn serialize<T, S>(_: &T, _serializer: S) -> Result<S::Ok, S::Error>
368    where
369        S: serde::ser::Serializer,
370    {
371        use serde::ser::Error;
372        Err(S::Error::custom("Cannot serialize variables"))
373    }
374
375    pub fn deserialize<'de, T, D>(_deserializer: D) -> Result<T, D::Error>
376    where
377        D: serde::de::Deserializer<'de>,
378    {
379        use serde::de::Error;
380        Err(D::Error::custom("Cannot deserialize variables"))
381    }
382}
383
384impl<T> FormatHolder for Variable<T>
385where
386    T: FormatHolder + std::fmt::Debug + Clone,
387{
388    fn visit<'a>(&'a self, _f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()> {
389        Err(Error::NotSupported(
390            "Cannot immutability visit formats with variables",
391        ))
392    }
393
394    fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()> {
395        match &mut *self.borrow_mut() {
396            None => Err(Error::UnknownFormat),
397            Some(value) => value.visit_mut(f),
398        }
399    }
400
401    fn unify(&mut self, _other: Variable<T>) -> Result<()> {
402        // Omitting this method because a correct implementation would require
403        // additional assumptions on T (in order to create new variables of type `T`).
404        Err(Error::NotSupported("Cannot unify variables directly"))
405    }
406
407    fn is_unknown(&self) -> bool {
408        match self.borrow().as_ref() {
409            None => true,
410            Some(format) => format.is_unknown(),
411        }
412    }
413}
414
415impl FormatHolder for ContainerFormat {
416    fn visit<'a>(&'a self, f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()> {
417        match self {
418            Self::UnitStruct => (),
419            Self::NewTypeStruct(format) => format.visit(f)?,
420            Self::TupleStruct(formats) => {
421                for format in formats {
422                    format.visit(f)?;
423                }
424            }
425            Self::Struct(named_formats) => {
426                for format in named_formats {
427                    format.visit(f)?;
428                }
429            }
430            Self::Enum(variants) => {
431                for variant in variants {
432                    variant.1.visit(f)?;
433                }
434            }
435        }
436        Ok(())
437    }
438
439    fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()> {
440        match self {
441            Self::UnitStruct => (),
442            Self::NewTypeStruct(format) => format.visit_mut(f)?,
443            Self::TupleStruct(formats) => {
444                for format in formats {
445                    format.visit_mut(f)?;
446                }
447            }
448            Self::Struct(named_formats) => {
449                for format in named_formats {
450                    format.visit_mut(f)?;
451                }
452            }
453            Self::Enum(variants) => {
454                for variant in variants {
455                    variant.1.visit_mut(f)?;
456                }
457            }
458        }
459        Ok(())
460    }
461
462    fn unify(&mut self, format: ContainerFormat) -> Result<()> {
463        match (self, format) {
464            (Self::UnitStruct, Self::UnitStruct) => (),
465
466            (Self::NewTypeStruct(format1), Self::NewTypeStruct(format2)) => {
467                format1.as_mut().unify(*format2)?;
468            }
469
470            (Self::TupleStruct(formats1), Self::TupleStruct(formats2))
471                if formats1.len() == formats2.len() =>
472            {
473                for (format1, format2) in formats1.iter_mut().zip(formats2.into_iter()) {
474                    format1.unify(format2)?;
475                }
476            }
477
478            (Self::Struct(named_formats1), Self::Struct(named_formats2))
479                if named_formats1.len() == named_formats2.len() =>
480            {
481                for (format1, format2) in named_formats1.iter_mut().zip(named_formats2.into_iter())
482                {
483                    format1.unify(format2)?;
484                }
485            }
486
487            (Self::Enum(variants1), Self::Enum(variants2)) => {
488                for (index2, variant2) in variants2 {
489                    match variants1.entry(index2) {
490                        Entry::Vacant(e) => {
491                            // Note that we do not check for name collisions.
492                            e.insert(variant2);
493                        }
494                        Entry::Occupied(mut e) => {
495                            e.get_mut().unify(variant2)?;
496                        }
497                    }
498                }
499            }
500
501            (format1, format2) => {
502                return Err(unification_error(format1, format2));
503            }
504        }
505        Ok(())
506    }
507
508    fn is_unknown(&self) -> bool {
509        false
510    }
511}
512
513impl FormatHolder for Format {
514    fn visit<'a>(&'a self, f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()> {
515        match self {
516            Self::Variable(variable) => variable.visit(f)?,
517            Self::TypeName(_)
518            | Self::Unit
519            | Self::Bool
520            | Self::I8
521            | Self::I16
522            | Self::I32
523            | Self::I64
524            | Self::I128
525            | Self::U8
526            | Self::U16
527            | Self::U32
528            | Self::U64
529            | Self::U128
530            | Self::F32
531            | Self::F64
532            | Self::Char
533            | Self::Str
534            | Self::Bytes => (),
535
536            Self::Option(format)
537            | Self::Seq(format)
538            | Self::TupleArray {
539                content: format, ..
540            } => {
541                format.visit(f)?;
542            }
543
544            Self::Map { key, value } => {
545                key.visit(f)?;
546                value.visit(f)?;
547            }
548
549            Self::Tuple(formats) => {
550                for format in formats {
551                    format.visit(f)?;
552                }
553            }
554        }
555        f(self)
556    }
557
558    fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()> {
559        match self {
560            Self::Variable(variable) => {
561                variable.visit_mut(f)?;
562                // At this point, `variable` is known and points to variable-free content.
563                // Remove the variable.
564                *self = std::mem::take(variable)
565                    .into_inner()
566                    .expect("variable is known");
567            }
568            Self::TypeName(_)
569            | Self::Unit
570            | Self::Bool
571            | Self::I8
572            | Self::I16
573            | Self::I32
574            | Self::I64
575            | Self::I128
576            | Self::U8
577            | Self::U16
578            | Self::U32
579            | Self::U64
580            | Self::U128
581            | Self::F32
582            | Self::F64
583            | Self::Char
584            | Self::Str
585            | Self::Bytes => (),
586
587            Self::Option(format)
588            | Self::Seq(format)
589            | Self::TupleArray {
590                content: format, ..
591            } => {
592                format.visit_mut(f)?;
593            }
594
595            Self::Map { key, value } => {
596                key.visit_mut(f)?;
597                value.visit_mut(f)?;
598            }
599
600            Self::Tuple(formats) => {
601                for format in formats {
602                    format.visit_mut(f)?;
603                }
604            }
605        }
606        f(self)
607    }
608
609    /// Unify the newly "traced" value `format` into the current format.
610    /// Note that there should be no `TupleArray`s at this point.
611    fn unify(&mut self, format: Format) -> Result<()> {
612        match (self, format) {
613            (format1, Self::Variable(variable2)) => {
614                if let Some(format2) = &mut *variable2.borrow_mut() {
615                    format1.unify(std::mem::take(format2))?;
616                }
617                *variable2.borrow_mut() = Some(format1.clone());
618            }
619            (Self::Variable(variable1), format2) => {
620                let inner_variable = match &mut *variable1.borrow_mut() {
621                    value1 @ None => {
622                        *value1 = Some(format2);
623                        None
624                    }
625                    Some(format1) => {
626                        format1.unify(format2)?;
627                        match format1 {
628                            Self::Variable(variable) => Some(variable.clone()),
629                            _ => None,
630                        }
631                    }
632                };
633                // Reduce multiple indirections to a single one.
634                if let Some(variable) = inner_variable {
635                    *variable1 = variable;
636                }
637            }
638
639            (Self::Unit, Self::Unit)
640            | (Self::Bool, Self::Bool)
641            | (Self::I8, Self::I8)
642            | (Self::I16, Self::I16)
643            | (Self::I32, Self::I32)
644            | (Self::I64, Self::I64)
645            | (Self::I128, Self::I128)
646            | (Self::U8, Self::U8)
647            | (Self::U16, Self::U16)
648            | (Self::U32, Self::U32)
649            | (Self::U64, Self::U64)
650            | (Self::U128, Self::U128)
651            | (Self::F32, Self::F32)
652            | (Self::F64, Self::F64)
653            | (Self::Char, Self::Char)
654            | (Self::Str, Self::Str)
655            | (Self::Bytes, Self::Bytes) => (),
656
657            (Self::TypeName(name1), Self::TypeName(name2)) if *name1 == name2 => (),
658
659            (Self::Option(format1), Self::Option(format2))
660            | (Self::Seq(format1), Self::Seq(format2)) => {
661                format1.as_mut().unify(*format2)?;
662            }
663
664            (Self::Tuple(formats1), Self::Tuple(formats2)) if formats1.len() == formats2.len() => {
665                for (format1, format2) in formats1.iter_mut().zip(formats2.into_iter()) {
666                    format1.unify(format2)?;
667                }
668            }
669
670            (
671                Self::Map {
672                    key: key1,
673                    value: value1,
674                },
675                Self::Map {
676                    key: key2,
677                    value: value2,
678                },
679            ) => {
680                key1.as_mut().unify(*key2)?;
681                value1.as_mut().unify(*value2)?;
682            }
683
684            (format1, format2) => {
685                return Err(unification_error(format1, format2));
686            }
687        }
688        Ok(())
689    }
690
691    fn is_unknown(&self) -> bool {
692        if let Self::Variable(v) = self {
693            return v.is_unknown();
694        }
695        false
696    }
697}
698
699/// Helper trait to update formats in maps.
700pub(crate) trait ContainerFormatEntry {
701    fn unify(self, format: ContainerFormat) -> Result<()>;
702}
703
704impl<K> ContainerFormatEntry for Entry<'_, K, ContainerFormat>
705where
706    K: std::cmp::Ord,
707{
708    fn unify(self, format: ContainerFormat) -> Result<()> {
709        match self {
710            Entry::Vacant(e) => {
711                e.insert(format);
712                Ok(())
713            }
714            Entry::Occupied(e) => e.into_mut().unify(format),
715        }
716    }
717}
718
719impl Format {
720    /// Return a format made of a fresh variable with no known value.
721    pub fn unknown() -> Self {
722        Self::Variable(Variable::new(None))
723    }
724}
725
726impl VariantFormat {
727    /// Return a format made of a fresh variable with no known value.
728    pub fn unknown() -> Self {
729        Self::Variable(Variable::new(None))
730    }
731}
732
733impl Default for Format {
734    fn default() -> Self {
735        Self::unknown()
736    }
737}
738
739impl Default for VariantFormat {
740    fn default() -> Self {
741        Self::unknown()
742    }
743}
744
745// For better rendering in human readable formats, we wish to serialize
746// `Named { key: x, value: y }` as a map `{ x: y }`.
747impl<T> Serialize for Named<T>
748where
749    T: Serialize,
750{
751    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
752    where
753        S: ser::Serializer,
754    {
755        if serializer.is_human_readable() {
756            let mut map = serializer.serialize_map(Some(1))?;
757            map.serialize_entry(&self.name, &self.value)?;
758            map.end()
759        } else {
760            let mut inner = serializer.serialize_struct("Named", 2)?;
761            inner.serialize_field("name", &self.name)?;
762            inner.serialize_field("value", &self.value)?;
763            inner.end()
764        }
765    }
766}
767
768struct NamedVisitor<T> {
769    marker: std::marker::PhantomData<T>,
770}
771
772impl<T> NamedVisitor<T> {
773    fn new() -> Self {
774        Self {
775            marker: std::marker::PhantomData,
776        }
777    }
778}
779
780impl<'de, T> de::Visitor<'de> for NamedVisitor<T>
781where
782    T: Deserialize<'de>,
783{
784    type Value = Named<T>;
785
786    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
787        formatter.write_str("a single entry map")
788    }
789
790    fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
791    where
792        M: de::MapAccess<'de>,
793    {
794        let named_value = match access.next_entry::<String, T>()? {
795            Some((name, value)) => Named { name, value },
796            _ => {
797                return Err(de::Error::custom("Missing entry"));
798            }
799        };
800        if access.next_entry::<String, T>()?.is_some() {
801            return Err(de::Error::custom("Too many entries"));
802        }
803        Ok(named_value)
804    }
805}
806
807/// For deserialization of non-human readable `Named` values, we keep it simple and use derive macros.
808#[derive(Deserialize)]
809#[serde(rename = "Named")]
810struct NamedInternal<T> {
811    name: String,
812    value: T,
813}
814
815impl<'de, T> Deserialize<'de> for Named<T>
816where
817    T: Deserialize<'de>,
818{
819    fn deserialize<D>(deserializer: D) -> Result<Named<T>, D::Error>
820    where
821        D: de::Deserializer<'de>,
822    {
823        if deserializer.is_human_readable() {
824            deserializer.deserialize_map(NamedVisitor::new())
825        } else {
826            let NamedInternal { name, value } = NamedInternal::deserialize(deserializer)?;
827            Ok(Self { name, value })
828        }
829    }
830}