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