Skip to main content

core/fmt/
builders.rs

1#![allow(unused_imports)]
2
3use crate::cell::Cell;
4use crate::fmt::{self, Debug, Formatter};
5
6#[ferrocene::prevalidated]
7struct PadAdapter<'buf, 'state> {
8    buf: &'buf mut (dyn fmt::Write + 'buf),
9    state: &'state mut PadAdapterState,
10}
11
12#[ferrocene::prevalidated]
13struct PadAdapterState {
14    on_newline: bool,
15}
16
17impl Default for PadAdapterState {
18    #[ferrocene::prevalidated]
19    fn default() -> Self {
20        PadAdapterState { on_newline: true }
21    }
22}
23
24impl<'buf, 'state> PadAdapter<'buf, 'state> {
25    #[ferrocene::prevalidated]
26    fn wrap<'slot, 'fmt: 'buf + 'slot>(
27        fmt: &'fmt mut fmt::Formatter<'_>,
28        slot: &'slot mut Option<Self>,
29        state: &'state mut PadAdapterState,
30    ) -> fmt::Formatter<'slot> {
31        fmt.wrap_buf(move |buf| slot.insert(PadAdapter { buf, state }))
32    }
33}
34
35impl fmt::Write for PadAdapter<'_, '_> {
36    #[ferrocene::prevalidated]
37    fn write_str(&mut self, s: &str) -> fmt::Result {
38        for s in s.split_inclusive('\n') {
39            if self.state.on_newline {
40                self.buf.write_str("    ")?;
41            }
42
43            self.state.on_newline = s.ends_with('\n');
44            self.buf.write_str(s)?;
45        }
46
47        Ok(())
48    }
49
50    #[ferrocene::prevalidated]
51    fn write_char(&mut self, c: char) -> fmt::Result {
52        if self.state.on_newline {
53            self.buf.write_str("    ")?;
54        }
55        self.state.on_newline = c == '\n';
56        self.buf.write_char(c)
57    }
58}
59
60/// Wraps an `FnOnce` formatting closure in a type that implements [`fmt::Debug`] by calling the
61/// closure, allowing the `*_with` builder methods to forward to their `&dyn fmt::Debug`
62/// counterparts.
63///
64/// By doing this, the builder logic is monomorphized only once and not for every closure type
65/// (see #149745).
66///
67/// Formatting a `DebugOnce` consumes the closure, so attempting to format it more than once
68/// panics. This never happens because the debug builders format each value exactly once.
69struct DebugOnce<F>(Cell<Option<F>>);
70
71impl<F> fmt::Debug for DebugOnce<F>
72where
73    F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
74{
75    #[ferrocene::prevalidated]
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        match self.0.take() {
78            Some(value_fmt) => value_fmt(f),
79            #[ferrocene::annotation("Cannot be covered since it is not reachable from public API.")]
80            None => panic!("formatting closure called more than once"),
81        }
82    }
83}
84
85/// A struct to help with [`fmt::Debug`](Debug) implementations.
86///
87/// This is useful when you wish to output a formatted struct as a part of your
88/// [`Debug::fmt`] implementation.
89///
90/// This can be constructed by the [`Formatter::debug_struct`] method.
91///
92/// # Examples
93///
94/// ```
95/// use std::fmt;
96///
97/// struct Foo {
98///     bar: i32,
99///     baz: String,
100/// }
101///
102/// impl fmt::Debug for Foo {
103///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
104///         fmt.debug_struct("Foo")
105///            .field("bar", &self.bar)
106///            .field("baz", &self.baz)
107///            .finish()
108///     }
109/// }
110///
111/// assert_eq!(
112///     format!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() }),
113///     r#"Foo { bar: 10, baz: "Hello World" }"#,
114/// );
115/// ```
116#[must_use = "must eventually call `finish()` on Debug builders"]
117#[allow(missing_debug_implementations)]
118#[stable(feature = "debug_builders", since = "1.2.0")]
119#[rustc_diagnostic_item = "DebugStruct"]
120#[ferrocene::prevalidated]
121pub struct DebugStruct<'a, 'b: 'a> {
122    fmt: &'a mut fmt::Formatter<'b>,
123    result: fmt::Result,
124    has_fields: bool,
125}
126
127#[ferrocene::prevalidated]
128pub(super) fn debug_struct_new<'a, 'b>(
129    fmt: &'a mut fmt::Formatter<'b>,
130    name: &str,
131) -> DebugStruct<'a, 'b> {
132    let result = fmt.write_str(name);
133    DebugStruct { fmt, result, has_fields: false }
134}
135
136impl<'a, 'b: 'a> DebugStruct<'a, 'b> {
137    /// Adds a new field to the generated struct output.
138    ///
139    /// # Examples
140    ///
141    /// ```
142    /// use std::fmt;
143    ///
144    /// struct Bar {
145    ///     bar: i32,
146    ///     another: String,
147    /// }
148    ///
149    /// impl fmt::Debug for Bar {
150    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
151    ///         fmt.debug_struct("Bar")
152    ///            .field("bar", &self.bar) // We add `bar` field.
153    ///            .field("another", &self.another) // We add `another` field.
154    ///            // We even add a field which doesn't exist (because why not?).
155    ///            .field("nonexistent_field", &1)
156    ///            .finish() // We're good to go!
157    ///     }
158    /// }
159    ///
160    /// assert_eq!(
161    ///     format!("{:?}", Bar { bar: 10, another: "Hello World".to_string() }),
162    ///     r#"Bar { bar: 10, another: "Hello World", nonexistent_field: 1 }"#,
163    /// );
164    /// ```
165    #[stable(feature = "debug_builders", since = "1.2.0")]
166    #[ferrocene::prevalidated]
167    pub fn field(&mut self, name: &str, value: &dyn fmt::Debug) -> &mut Self {
168        self.result = self.result.and_then(|_| {
169            if self.is_pretty() {
170                if !self.has_fields {
171                    self.fmt.write_str(" {\n")?;
172                }
173                let mut slot = None;
174                let mut state = Default::default();
175                let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
176                writer.write_str(name)?;
177                writer.write_str(": ")?;
178                value.fmt(&mut writer)?;
179                writer.write_str(",\n")
180            } else {
181                let prefix = if self.has_fields { ", " } else { " { " };
182                self.fmt.write_str(prefix)?;
183                self.fmt.write_str(name)?;
184                self.fmt.write_str(": ")?;
185                value.fmt(self.fmt)
186            }
187        });
188
189        self.has_fields = true;
190        self
191    }
192
193    /// Adds a new field to the generated struct output.
194    ///
195    /// This method is equivalent to [`DebugStruct::field`], but formats the
196    /// value using a provided closure rather than by calling [`Debug::fmt`].
197    ///
198    /// # Examples
199    ///
200    /// ```
201    /// use std::fmt;
202    ///
203    /// struct Bar {
204    ///     bar: i32,
205    ///     another: String,
206    /// }
207    ///
208    /// impl fmt::Debug for Bar {
209    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
210    ///         fmt.debug_struct("Bar")
211    ///            // Print `bar` as a hex value
212    ///            .field_with("bar", |fmt| write!(fmt, "{:#010x}", &self.bar))
213    ///            .field("another", &self.another)
214    ///            .finish()
215    ///     }
216    /// }
217    ///
218    /// assert_eq!(
219    ///     format!("{:?}", Bar { bar: 10, another: "Hello World".to_string() }),
220    ///     r#"Bar { bar: 0x0000000a, another: "Hello World" }"#,
221    /// );
222    /// ```
223    #[ferrocene::prevalidated]
224    #[stable(feature = "debug_closure_helpers", since = "1.101.0")]
225    pub fn field_with(
226        &mut self,
227        name: &str,
228        value_fmt: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
229    ) -> &mut Self {
230        self.field(name, &DebugOnce(Cell::new(Some(value_fmt))))
231    }
232
233    /// Marks the struct as non-exhaustive, indicating to the reader that there are some other
234    /// fields that are not shown in the debug representation.
235    ///
236    /// # Examples
237    ///
238    /// ```
239    /// use std::fmt;
240    ///
241    /// struct Bar {
242    ///     bar: i32,
243    ///     hidden: f32,
244    /// }
245    ///
246    /// impl fmt::Debug for Bar {
247    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
248    ///         fmt.debug_struct("Bar")
249    ///            .field("bar", &self.bar)
250    ///            .finish_non_exhaustive() // Show that some other field(s) exist.
251    ///     }
252    /// }
253    ///
254    /// assert_eq!(
255    ///     format!("{:?}", Bar { bar: 10, hidden: 1.0 }),
256    ///     "Bar { bar: 10, .. }",
257    /// );
258    /// ```
259    #[stable(feature = "debug_non_exhaustive", since = "1.53.0")]
260    #[ferrocene::prevalidated]
261    pub fn finish_non_exhaustive(&mut self) -> fmt::Result {
262        self.result = self.result.and_then(|_| {
263            if self.has_fields {
264                if self.is_pretty() {
265                    let mut slot = None;
266                    let mut state = Default::default();
267                    let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
268                    writer.write_str("..\n")?;
269                    self.fmt.write_str("}")
270                } else {
271                    self.fmt.write_str(", .. }")
272                }
273            } else {
274                self.fmt.write_str(" { .. }")
275            }
276        });
277        self.result
278    }
279
280    /// Finishes output and returns any error encountered.
281    ///
282    /// # Examples
283    ///
284    /// ```
285    /// use std::fmt;
286    ///
287    /// struct Bar {
288    ///     bar: i32,
289    ///     baz: String,
290    /// }
291    ///
292    /// impl fmt::Debug for Bar {
293    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
294    ///         fmt.debug_struct("Bar")
295    ///            .field("bar", &self.bar)
296    ///            .field("baz", &self.baz)
297    ///            .finish() // You need to call it to "finish" the
298    ///                      // struct formatting.
299    ///     }
300    /// }
301    ///
302    /// assert_eq!(
303    ///     format!("{:?}", Bar { bar: 10, baz: "Hello World".to_string() }),
304    ///     r#"Bar { bar: 10, baz: "Hello World" }"#,
305    /// );
306    /// ```
307    #[stable(feature = "debug_builders", since = "1.2.0")]
308    #[ferrocene::prevalidated]
309    pub fn finish(&mut self) -> fmt::Result {
310        if self.has_fields {
311            self.result = self.result.and_then(|_| {
312                if self.is_pretty() { self.fmt.write_str("}") } else { self.fmt.write_str(" }") }
313            });
314        }
315        self.result
316    }
317
318    #[ferrocene::prevalidated]
319    fn is_pretty(&self) -> bool {
320        self.fmt.alternate()
321    }
322}
323
324/// A struct to help with [`fmt::Debug`](Debug) implementations.
325///
326/// This is useful when you wish to output a formatted tuple as a part of your
327/// [`Debug::fmt`] implementation.
328///
329/// This can be constructed by the [`Formatter::debug_tuple`] method.
330///
331/// # Examples
332///
333/// ```
334/// use std::fmt;
335///
336/// struct Foo(i32, String);
337///
338/// impl fmt::Debug for Foo {
339///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
340///         fmt.debug_tuple("Foo")
341///            .field(&self.0)
342///            .field(&self.1)
343///            .finish()
344///     }
345/// }
346///
347/// assert_eq!(
348///     format!("{:?}", Foo(10, "Hello World".to_string())),
349///     r#"Foo(10, "Hello World")"#,
350/// );
351/// ```
352#[must_use = "must eventually call `finish()` on Debug builders"]
353#[allow(missing_debug_implementations)]
354#[stable(feature = "debug_builders", since = "1.2.0")]
355#[ferrocene::prevalidated]
356pub struct DebugTuple<'a, 'b: 'a> {
357    fmt: &'a mut fmt::Formatter<'b>,
358    result: fmt::Result,
359    fields: usize,
360    empty_name: bool,
361}
362
363#[ferrocene::prevalidated]
364pub(super) fn debug_tuple_new<'a, 'b>(
365    fmt: &'a mut fmt::Formatter<'b>,
366    name: &str,
367) -> DebugTuple<'a, 'b> {
368    let result = fmt.write_str(name);
369    DebugTuple { fmt, result, fields: 0, empty_name: name.is_empty() }
370}
371
372impl<'a, 'b: 'a> DebugTuple<'a, 'b> {
373    /// Adds a new field to the generated tuple struct output.
374    ///
375    /// # Examples
376    ///
377    /// ```
378    /// use std::fmt;
379    ///
380    /// struct Foo(i32, String);
381    ///
382    /// impl fmt::Debug for Foo {
383    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
384    ///         fmt.debug_tuple("Foo")
385    ///            .field(&self.0) // We add the first field.
386    ///            .field(&self.1) // We add the second field.
387    ///            .finish() // We're good to go!
388    ///     }
389    /// }
390    ///
391    /// assert_eq!(
392    ///     format!("{:?}", Foo(10, "Hello World".to_string())),
393    ///     r#"Foo(10, "Hello World")"#,
394    /// );
395    /// ```
396    #[stable(feature = "debug_builders", since = "1.2.0")]
397    #[ferrocene::prevalidated]
398    pub fn field(&mut self, value: &dyn fmt::Debug) -> &mut Self {
399        self.result = self.result.and_then(|_| {
400            if self.is_pretty() {
401                if self.fields == 0 {
402                    self.fmt.write_str("(\n")?;
403                }
404                let mut slot = None;
405                let mut state = Default::default();
406                let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
407                value.fmt(&mut writer)?;
408                writer.write_str(",\n")
409            } else {
410                let prefix = if self.fields == 0 { "(" } else { ", " };
411                self.fmt.write_str(prefix)?;
412                value.fmt(self.fmt)
413            }
414        });
415
416        self.fields += 1;
417        self
418    }
419
420    /// Adds a new field to the generated tuple struct output.
421    ///
422    /// This method is equivalent to [`DebugTuple::field`], but formats the
423    /// value using a provided closure rather than by calling [`Debug::fmt`].
424    ///
425    /// # Examples
426    ///
427    /// ```
428    /// use std::fmt;
429    ///
430    /// struct Foo(i32, String);
431    ///
432    /// impl fmt::Debug for Foo {
433    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
434    ///         fmt.debug_tuple("Foo")
435    ///             // Print the first field as a hex value
436    ///             .field_with(|fmt| write!(fmt, "{:#010x}", &self.0))
437    ///             .field(&self.1)
438    ///             .finish()
439    ///     }
440    /// }
441    ///
442    /// assert_eq!(
443    ///     format!("{:?}", Foo(10, "Hello World".to_string())),
444    ///     r#"Foo(0x0000000a, "Hello World")"#,
445    /// );
446    /// ```
447    #[ferrocene::prevalidated]
448    #[stable(feature = "debug_closure_helpers", since = "1.101.0")]
449    pub fn field_with(
450        &mut self,
451        value_fmt: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
452    ) -> &mut Self {
453        self.field(&DebugOnce(Cell::new(Some(value_fmt))))
454    }
455
456    /// Marks the tuple struct as non-exhaustive, indicating to the reader that there are some
457    /// other fields that are not shown in the debug representation.
458    ///
459    /// # Examples
460    ///
461    /// ```
462    /// use std::fmt;
463    ///
464    /// struct Foo(i32, String);
465    ///
466    /// impl fmt::Debug for Foo {
467    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
468    ///         fmt.debug_tuple("Foo")
469    ///            .field(&self.0)
470    ///            .finish_non_exhaustive() // Show that some other field(s) exist.
471    ///     }
472    /// }
473    ///
474    /// assert_eq!(
475    ///     format!("{:?}", Foo(10, "secret!".to_owned())),
476    ///     "Foo(10, ..)",
477    /// );
478    /// ```
479    #[stable(feature = "debug_more_non_exhaustive", since = "1.83.0")]
480    #[ferrocene::prevalidated]
481    pub fn finish_non_exhaustive(&mut self) -> fmt::Result {
482        self.result = self.result.and_then(|_| {
483            if self.fields > 0 {
484                if self.is_pretty() {
485                    let mut slot = None;
486                    let mut state = Default::default();
487                    let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
488                    writer.write_str("..\n")?;
489                    self.fmt.write_str(")")
490                } else {
491                    self.fmt.write_str(", ..)")
492                }
493            } else {
494                self.fmt.write_str("(..)")
495            }
496        });
497        self.result
498    }
499
500    /// Finishes output and returns any error encountered.
501    ///
502    /// # Examples
503    ///
504    /// ```
505    /// use std::fmt;
506    ///
507    /// struct Foo(i32, String);
508    ///
509    /// impl fmt::Debug for Foo {
510    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
511    ///         fmt.debug_tuple("Foo")
512    ///            .field(&self.0)
513    ///            .field(&self.1)
514    ///            .finish() // You need to call it to "finish" the
515    ///                      // tuple formatting.
516    ///     }
517    /// }
518    ///
519    /// assert_eq!(
520    ///     format!("{:?}", Foo(10, "Hello World".to_string())),
521    ///     r#"Foo(10, "Hello World")"#,
522    /// );
523    /// ```
524    #[stable(feature = "debug_builders", since = "1.2.0")]
525    #[ferrocene::prevalidated]
526    pub fn finish(&mut self) -> fmt::Result {
527        if self.fields > 0 {
528            self.result = self.result.and_then(|_| {
529                if self.fields == 1 && self.empty_name && !self.is_pretty() {
530                    self.fmt.write_str(",")?;
531                }
532                self.fmt.write_str(")")
533            });
534        }
535        self.result
536    }
537
538    #[ferrocene::prevalidated]
539    fn is_pretty(&self) -> bool {
540        self.fmt.alternate()
541    }
542}
543
544/// A helper used to print list-like items with no special formatting.
545#[ferrocene::prevalidated]
546struct DebugInner<'a, 'b: 'a> {
547    fmt: &'a mut fmt::Formatter<'b>,
548    result: fmt::Result,
549    has_fields: bool,
550}
551
552impl<'a, 'b: 'a> DebugInner<'a, 'b> {
553    #[ferrocene::prevalidated]
554    fn entry(&mut self, entry: &dyn fmt::Debug) {
555        self.result = self.result.and_then(|_| {
556            if self.is_pretty() {
557                if !self.has_fields {
558                    self.fmt.write_str("\n")?;
559                }
560                let mut slot = None;
561                let mut state = Default::default();
562                let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
563                entry.fmt(&mut writer)?;
564                writer.write_str(",\n")
565            } else {
566                if self.has_fields {
567                    self.fmt.write_str(", ")?
568                }
569                entry.fmt(self.fmt)
570            }
571        });
572
573        self.has_fields = true;
574    }
575
576    #[ferrocene::prevalidated]
577    fn entry_with(&mut self, entry_fmt: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) {
578        self.entry(&DebugOnce(Cell::new(Some(entry_fmt))));
579    }
580
581    #[ferrocene::prevalidated]
582    fn is_pretty(&self) -> bool {
583        self.fmt.alternate()
584    }
585}
586
587/// A struct to help with [`fmt::Debug`](Debug) implementations.
588///
589/// This is useful when you wish to output a formatted set of items as a part
590/// of your [`Debug::fmt`] implementation.
591///
592/// This can be constructed by the [`Formatter::debug_set`] method.
593///
594/// # Examples
595///
596/// ```
597/// use std::fmt;
598///
599/// struct Foo(Vec<i32>);
600///
601/// impl fmt::Debug for Foo {
602///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
603///         fmt.debug_set().entries(self.0.iter()).finish()
604///     }
605/// }
606///
607/// assert_eq!(
608///     format!("{:?}", Foo(vec![10, 11])),
609///     "{10, 11}",
610/// );
611/// ```
612#[must_use = "must eventually call `finish()` on Debug builders"]
613#[allow(missing_debug_implementations)]
614#[stable(feature = "debug_builders", since = "1.2.0")]
615#[ferrocene::prevalidated]
616pub struct DebugSet<'a, 'b: 'a> {
617    inner: DebugInner<'a, 'b>,
618}
619
620#[ferrocene::prevalidated]
621pub(super) fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugSet<'a, 'b> {
622    let result = fmt.write_str("{");
623    DebugSet { inner: DebugInner { fmt, result, has_fields: false } }
624}
625
626impl<'a, 'b: 'a> DebugSet<'a, 'b> {
627    /// Adds a new entry to the set output.
628    ///
629    /// # Examples
630    ///
631    /// ```
632    /// use std::fmt;
633    ///
634    /// struct Foo(Vec<i32>, Vec<u32>);
635    ///
636    /// impl fmt::Debug for Foo {
637    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
638    ///         fmt.debug_set()
639    ///            .entry(&self.0) // Adds the first "entry".
640    ///            .entry(&self.1) // Adds the second "entry".
641    ///            .finish()
642    ///     }
643    /// }
644    ///
645    /// assert_eq!(
646    ///     format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
647    ///     "{[10, 11], [12, 13]}",
648    /// );
649    /// ```
650    #[stable(feature = "debug_builders", since = "1.2.0")]
651    #[ferrocene::prevalidated]
652    pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut Self {
653        self.inner.entry(entry);
654        self
655    }
656
657    /// Adds a new entry to the set output.
658    ///
659    /// This method is equivalent to [`DebugSet::entry`], but formats the
660    /// entry using a provided closure rather than by calling [`Debug::fmt`].
661    ///
662    /// # Examples
663    ///
664    /// ```
665    /// use std::fmt;
666    ///
667    /// struct Foo(Vec<i32>, Vec<u32>);
668    ///
669    /// impl fmt::Debug for Foo {
670    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
671    ///         fmt.debug_set()
672    ///            .entry(&self.0)
673    ///            // Print the second member as a set
674    ///            .entry_with(|fmt| fmt.debug_set().entries(&self.1).finish())
675    ///            .finish()
676    ///     }
677    /// }
678    ///
679    /// assert_eq!(
680    ///     format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
681    ///     "{[10, 11], {12, 13}}",
682    /// );
683    /// ```
684    #[ferrocene::prevalidated]
685    #[stable(feature = "debug_closure_helpers", since = "1.101.0")]
686    pub fn entry_with(
687        &mut self,
688        entry_fmt: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
689    ) -> &mut Self {
690        self.inner.entry_with(entry_fmt);
691        self
692    }
693
694    /// Adds the contents of an iterator of entries to the set output.
695    ///
696    /// # Examples
697    ///
698    /// ```
699    /// use std::fmt;
700    ///
701    /// struct Foo(Vec<i32>, Vec<u32>);
702    ///
703    /// impl fmt::Debug for Foo {
704    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
705    ///         fmt.debug_set()
706    ///            .entries(self.0.iter()) // Adds the first "entry".
707    ///            .entries(self.1.iter()) // Adds the second "entry".
708    ///            .finish()
709    ///     }
710    /// }
711    ///
712    /// assert_eq!(
713    ///     format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
714    ///     "{10, 11, 12, 13}",
715    /// );
716    /// ```
717    #[stable(feature = "debug_builders", since = "1.2.0")]
718    #[ferrocene::prevalidated]
719    pub fn entries<D, I>(&mut self, entries: I) -> &mut Self
720    where
721        D: fmt::Debug,
722        I: IntoIterator<Item = D>,
723    {
724        for entry in entries {
725            self.entry(&entry);
726        }
727        self
728    }
729
730    /// Marks the set as non-exhaustive, indicating to the reader that there are some other
731    /// elements that are not shown in the debug representation.
732    ///
733    /// # Examples
734    ///
735    /// ```
736    /// use std::fmt;
737    ///
738    /// struct Foo(Vec<i32>);
739    ///
740    /// impl fmt::Debug for Foo {
741    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
742    ///         // Print at most two elements, abbreviate the rest
743    ///         let mut f = fmt.debug_set();
744    ///         let mut f = f.entries(self.0.iter().take(2));
745    ///         if self.0.len() > 2 {
746    ///             f.finish_non_exhaustive()
747    ///         } else {
748    ///             f.finish()
749    ///         }
750    ///     }
751    /// }
752    ///
753    /// assert_eq!(
754    ///     format!("{:?}", Foo(vec![1, 2, 3, 4])),
755    ///     "{1, 2, ..}",
756    /// );
757    /// ```
758    #[stable(feature = "debug_more_non_exhaustive", since = "1.83.0")]
759    #[ferrocene::prevalidated]
760    pub fn finish_non_exhaustive(&mut self) -> fmt::Result {
761        self.inner.result = self.inner.result.and_then(|_| {
762            if self.inner.has_fields {
763                if self.inner.is_pretty() {
764                    let mut slot = None;
765                    let mut state = Default::default();
766                    let mut writer = PadAdapter::wrap(self.inner.fmt, &mut slot, &mut state);
767                    writer.write_str("..\n")?;
768                    self.inner.fmt.write_str("}")
769                } else {
770                    self.inner.fmt.write_str(", ..}")
771                }
772            } else {
773                self.inner.fmt.write_str("..}")
774            }
775        });
776        self.inner.result
777    }
778
779    /// Finishes output and returns any error encountered.
780    ///
781    /// # Examples
782    ///
783    /// ```
784    /// use std::fmt;
785    ///
786    /// struct Foo(Vec<i32>);
787    ///
788    /// impl fmt::Debug for Foo {
789    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
790    ///         fmt.debug_set()
791    ///            .entries(self.0.iter())
792    ///            .finish() // Ends the set formatting.
793    ///     }
794    /// }
795    ///
796    /// assert_eq!(
797    ///     format!("{:?}", Foo(vec![10, 11])),
798    ///     "{10, 11}",
799    /// );
800    /// ```
801    #[stable(feature = "debug_builders", since = "1.2.0")]
802    #[ferrocene::prevalidated]
803    pub fn finish(&mut self) -> fmt::Result {
804        self.inner.result = self.inner.result.and_then(|_| self.inner.fmt.write_str("}"));
805        self.inner.result
806    }
807}
808
809/// A struct to help with [`fmt::Debug`](Debug) implementations.
810///
811/// This is useful when you wish to output a formatted list of items as a part
812/// of your [`Debug::fmt`] implementation.
813///
814/// This can be constructed by the [`Formatter::debug_list`] method.
815///
816/// # Examples
817///
818/// ```
819/// use std::fmt;
820///
821/// struct Foo(Vec<i32>);
822///
823/// impl fmt::Debug for Foo {
824///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
825///         fmt.debug_list().entries(self.0.iter()).finish()
826///     }
827/// }
828///
829/// assert_eq!(
830///     format!("{:?}", Foo(vec![10, 11])),
831///     "[10, 11]",
832/// );
833/// ```
834#[must_use = "must eventually call `finish()` on Debug builders"]
835#[allow(missing_debug_implementations)]
836#[stable(feature = "debug_builders", since = "1.2.0")]
837#[ferrocene::prevalidated]
838pub struct DebugList<'a, 'b: 'a> {
839    inner: DebugInner<'a, 'b>,
840}
841
842#[ferrocene::prevalidated]
843pub(super) fn debug_list_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugList<'a, 'b> {
844    let result = fmt.write_str("[");
845    DebugList { inner: DebugInner { fmt, result, has_fields: false } }
846}
847
848impl<'a, 'b: 'a> DebugList<'a, 'b> {
849    /// Adds a new entry to the list output.
850    ///
851    /// # Examples
852    ///
853    /// ```
854    /// use std::fmt;
855    ///
856    /// struct Foo(Vec<i32>, Vec<u32>);
857    ///
858    /// impl fmt::Debug for Foo {
859    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
860    ///         fmt.debug_list()
861    ///            .entry(&self.0) // We add the first "entry".
862    ///            .entry(&self.1) // We add the second "entry".
863    ///            .finish()
864    ///     }
865    /// }
866    ///
867    /// assert_eq!(
868    ///     format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
869    ///     "[[10, 11], [12, 13]]",
870    /// );
871    /// ```
872    #[stable(feature = "debug_builders", since = "1.2.0")]
873    #[ferrocene::prevalidated]
874    pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut Self {
875        self.inner.entry(entry);
876        self
877    }
878
879    /// Adds a new entry to the list output.
880    ///
881    /// This method is equivalent to [`DebugList::entry`], but formats the
882    /// entry using a provided closure rather than by calling [`Debug::fmt`].
883    ///
884    /// # Examples
885    ///
886    /// ```
887    /// use std::fmt;
888    ///
889    /// struct Foo(Vec<i32>, Vec<u32>);
890    ///
891    /// impl fmt::Debug for Foo {
892    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
893    ///         fmt.debug_list()
894    ///            .entry(&self.0)
895    ///            // Print the second member as a set
896    ///            .entry_with(|fmt| fmt.debug_set().entries(&self.1).finish())
897    ///            .finish()
898    ///     }
899    /// }
900    ///
901    /// assert_eq!(
902    ///     format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
903    ///     "[[10, 11], {12, 13}]",
904    /// );
905    /// ```
906    #[ferrocene::prevalidated]
907    #[stable(feature = "debug_closure_helpers", since = "1.101.0")]
908    pub fn entry_with(
909        &mut self,
910        entry_fmt: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
911    ) -> &mut Self {
912        self.inner.entry_with(entry_fmt);
913        self
914    }
915
916    /// Adds the contents of an iterator of entries to the list output.
917    ///
918    /// # Examples
919    ///
920    /// ```
921    /// use std::fmt;
922    ///
923    /// struct Foo(Vec<i32>, Vec<u32>);
924    ///
925    /// impl fmt::Debug for Foo {
926    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
927    ///         fmt.debug_list()
928    ///            .entries(self.0.iter())
929    ///            .entries(self.1.iter())
930    ///            .finish()
931    ///     }
932    /// }
933    ///
934    /// assert_eq!(
935    ///     format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
936    ///     "[10, 11, 12, 13]",
937    /// );
938    /// ```
939    #[stable(feature = "debug_builders", since = "1.2.0")]
940    #[ferrocene::prevalidated]
941    pub fn entries<D, I>(&mut self, entries: I) -> &mut Self
942    where
943        D: fmt::Debug,
944        I: IntoIterator<Item = D>,
945    {
946        for entry in entries {
947            self.entry(&entry);
948        }
949        self
950    }
951
952    /// Marks the list as non-exhaustive, indicating to the reader that there are some other
953    /// elements that are not shown in the debug representation.
954    ///
955    /// # Examples
956    ///
957    /// ```
958    /// use std::fmt;
959    ///
960    /// struct Foo(Vec<i32>);
961    ///
962    /// impl fmt::Debug for Foo {
963    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
964    ///         // Print at most two elements, abbreviate the rest
965    ///         let mut f = fmt.debug_list();
966    ///         let mut f = f.entries(self.0.iter().take(2));
967    ///         if self.0.len() > 2 {
968    ///             f.finish_non_exhaustive()
969    ///         } else {
970    ///             f.finish()
971    ///         }
972    ///     }
973    /// }
974    ///
975    /// assert_eq!(
976    ///     format!("{:?}", Foo(vec![1, 2, 3, 4])),
977    ///     "[1, 2, ..]",
978    /// );
979    /// ```
980    #[stable(feature = "debug_more_non_exhaustive", since = "1.83.0")]
981    #[ferrocene::prevalidated]
982    pub fn finish_non_exhaustive(&mut self) -> fmt::Result {
983        self.inner.result.and_then(|_| {
984            if self.inner.has_fields {
985                if self.inner.is_pretty() {
986                    let mut slot = None;
987                    let mut state = Default::default();
988                    let mut writer = PadAdapter::wrap(self.inner.fmt, &mut slot, &mut state);
989                    writer.write_str("..\n")?;
990                    self.inner.fmt.write_str("]")
991                } else {
992                    self.inner.fmt.write_str(", ..]")
993                }
994            } else {
995                self.inner.fmt.write_str("..]")
996            }
997        })
998    }
999
1000    /// Finishes output and returns any error encountered.
1001    ///
1002    /// # Examples
1003    ///
1004    /// ```
1005    /// use std::fmt;
1006    ///
1007    /// struct Foo(Vec<i32>);
1008    ///
1009    /// impl fmt::Debug for Foo {
1010    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1011    ///         fmt.debug_list()
1012    ///            .entries(self.0.iter())
1013    ///            .finish() // Ends the list formatting.
1014    ///     }
1015    /// }
1016    ///
1017    /// assert_eq!(
1018    ///     format!("{:?}", Foo(vec![10, 11])),
1019    ///     "[10, 11]",
1020    /// );
1021    /// ```
1022    #[stable(feature = "debug_builders", since = "1.2.0")]
1023    #[ferrocene::prevalidated]
1024    pub fn finish(&mut self) -> fmt::Result {
1025        self.inner.result = self.inner.result.and_then(|_| self.inner.fmt.write_str("]"));
1026        self.inner.result
1027    }
1028}
1029
1030/// A struct to help with [`fmt::Debug`](Debug) implementations.
1031///
1032/// This is useful when you wish to output a formatted map as a part of your
1033/// [`Debug::fmt`] implementation.
1034///
1035/// This can be constructed by the [`Formatter::debug_map`] method.
1036///
1037/// # Examples
1038///
1039/// ```
1040/// use std::fmt;
1041///
1042/// struct Foo(Vec<(String, i32)>);
1043///
1044/// impl fmt::Debug for Foo {
1045///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1046///         fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1047///     }
1048/// }
1049///
1050/// assert_eq!(
1051///     format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1052///     r#"{"A": 10, "B": 11}"#,
1053/// );
1054/// ```
1055#[must_use = "must eventually call `finish()` on Debug builders"]
1056#[allow(missing_debug_implementations)]
1057#[stable(feature = "debug_builders", since = "1.2.0")]
1058#[ferrocene::prevalidated]
1059pub struct DebugMap<'a, 'b: 'a> {
1060    fmt: &'a mut fmt::Formatter<'b>,
1061    result: fmt::Result,
1062    has_fields: bool,
1063    has_key: bool,
1064    // The state of newlines is tracked between keys and values
1065    state: PadAdapterState,
1066}
1067
1068#[ferrocene::prevalidated]
1069pub(super) fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugMap<'a, 'b> {
1070    let result = fmt.write_str("{");
1071    DebugMap { fmt, result, has_fields: false, has_key: false, state: Default::default() }
1072}
1073
1074impl<'a, 'b: 'a> DebugMap<'a, 'b> {
1075    /// Adds a new entry to the map output.
1076    ///
1077    /// # Examples
1078    ///
1079    /// ```
1080    /// use std::fmt;
1081    ///
1082    /// struct Foo(Vec<(String, i32)>);
1083    ///
1084    /// impl fmt::Debug for Foo {
1085    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1086    ///         fmt.debug_map()
1087    ///            .entry(&"whole", &self.0) // We add the "whole" entry.
1088    ///            .finish()
1089    ///     }
1090    /// }
1091    ///
1092    /// assert_eq!(
1093    ///     format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1094    ///     r#"{"whole": [("A", 10), ("B", 11)]}"#,
1095    /// );
1096    /// ```
1097    #[stable(feature = "debug_builders", since = "1.2.0")]
1098    #[ferrocene::prevalidated]
1099    pub fn entry(&mut self, key: &dyn fmt::Debug, value: &dyn fmt::Debug) -> &mut Self {
1100        self.key(key).value(value)
1101    }
1102
1103    /// Adds the key part of a new entry to the map output.
1104    ///
1105    /// This method, together with `value`, is an alternative to `entry` that
1106    /// can be used when the complete entry isn't known upfront. Prefer the `entry`
1107    /// method when it's possible to use.
1108    ///
1109    /// # Panics
1110    ///
1111    /// `key` or `key_with` must be called before `value` or `value_with`, and each
1112    /// `key` call must be followed by a corresponding `value` call. Otherwise this
1113    /// method will panic.
1114    ///
1115    /// # Examples
1116    ///
1117    /// ```
1118    /// use std::fmt;
1119    ///
1120    /// struct Foo(Vec<(String, i32)>);
1121    ///
1122    /// impl fmt::Debug for Foo {
1123    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1124    ///         fmt.debug_map()
1125    ///            .key(&"whole").value(&self.0) // We add the "whole" entry.
1126    ///            .finish()
1127    ///     }
1128    /// }
1129    ///
1130    /// assert_eq!(
1131    ///     format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1132    ///     r#"{"whole": [("A", 10), ("B", 11)]}"#,
1133    /// );
1134    /// ```
1135    #[stable(feature = "debug_map_key_value", since = "1.42.0")]
1136    #[ferrocene::prevalidated]
1137    pub fn key(&mut self, key: &dyn fmt::Debug) -> &mut Self {
1138        self.result = self.result.and_then(|_| {
1139            assert!(
1140                !self.has_key,
1141                "attempted to begin a new map entry \
1142                                    without completing the previous one"
1143            );
1144
1145            if self.is_pretty() {
1146                if !self.has_fields {
1147                    self.fmt.write_str("\n")?;
1148                }
1149                let mut slot = None;
1150                self.state = Default::default();
1151                let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut self.state);
1152                key.fmt(&mut writer)?;
1153                writer.write_str(": ")?;
1154            } else {
1155                if self.has_fields {
1156                    self.fmt.write_str(", ")?
1157                }
1158                key.fmt(self.fmt)?;
1159                self.fmt.write_str(": ")?;
1160            }
1161
1162            self.has_key = true;
1163            Ok(())
1164        });
1165
1166        self
1167    }
1168
1169    /// Adds the key part of a new entry to the map output.
1170    ///
1171    /// This method is equivalent to [`DebugMap::key`], but formats the
1172    /// key using a provided closure rather than by calling [`Debug::fmt`].
1173    ///
1174    /// # Panics
1175    ///
1176    /// `key` or `key_with` must be called before `value` or `value_with`, and each
1177    /// `key` call must be followed by a corresponding `value` call. Otherwise this
1178    /// method will panic.
1179    ///
1180    /// # Examples
1181    ///
1182    /// ```
1183    /// use std::fmt;
1184    ///
1185    /// struct Foo(Vec<(String, i32)>);
1186    ///
1187    /// impl fmt::Debug for Foo {
1188    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1189    ///         let mut map = fmt.debug_map();
1190    ///         for (k, v) in &self.0 {
1191    ///             // Append "entry" to each key
1192    ///             map.key_with(|fmt| write!(fmt, "entry {k}"));
1193    ///             // Write values as hex
1194    ///             map.value_with(|fmt| write!(fmt, "{v:#010x}"));
1195    ///         }
1196    ///         map.finish()
1197    ///     }
1198    /// }
1199    ///
1200    /// assert_eq!(
1201    ///     format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1202    ///     r#"{entry A: 0x0000000a, entry B: 0x0000000b}"#,
1203    /// );
1204    /// ```
1205    #[ferrocene::prevalidated]
1206    #[stable(feature = "debug_closure_helpers", since = "1.101.0")]
1207    pub fn key_with(
1208        &mut self,
1209        key_fmt: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1210    ) -> &mut Self {
1211        self.key(&DebugOnce(Cell::new(Some(key_fmt))))
1212    }
1213
1214    /// Adds the value part of a new entry to the map output.
1215    ///
1216    /// This method, together with `key`, is an alternative to `entry` that
1217    /// can be used when the complete entry isn't known upfront. Prefer the `entry`
1218    /// method when it's possible to use.
1219    ///
1220    /// # Panics
1221    ///
1222    /// `key` or `key_with` must be called before `value` or `value_with`, and each
1223    /// `key` call must be followed by a corresponding `value` call. Otherwise this
1224    /// method will panic.
1225    ///
1226    /// # Examples
1227    ///
1228    /// ```
1229    /// use std::fmt;
1230    ///
1231    /// struct Foo(Vec<(String, i32)>);
1232    ///
1233    /// impl fmt::Debug for Foo {
1234    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1235    ///         fmt.debug_map()
1236    ///            .key(&"whole").value(&self.0) // We add the "whole" entry.
1237    ///            .finish()
1238    ///     }
1239    /// }
1240    ///
1241    /// assert_eq!(
1242    ///     format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1243    ///     r#"{"whole": [("A", 10), ("B", 11)]}"#,
1244    /// );
1245    /// ```
1246    #[stable(feature = "debug_map_key_value", since = "1.42.0")]
1247    #[ferrocene::prevalidated]
1248    pub fn value(&mut self, value: &dyn fmt::Debug) -> &mut Self {
1249        self.result = self.result.and_then(|_| {
1250            assert!(self.has_key, "attempted to format a map value before its key");
1251
1252            if self.is_pretty() {
1253                let mut slot = None;
1254                let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut self.state);
1255                value.fmt(&mut writer)?;
1256                writer.write_str(",\n")?;
1257            } else {
1258                value.fmt(self.fmt)?;
1259            }
1260
1261            self.has_key = false;
1262            Ok(())
1263        });
1264
1265        self.has_fields = true;
1266        self
1267    }
1268
1269    /// Adds the value part of a new entry to the map output.
1270    ///
1271    /// This method is equivalent to [`DebugMap::value`], but formats the
1272    /// value using a provided closure rather than by calling [`Debug::fmt`].
1273    ///
1274    /// # Panics
1275    ///
1276    /// `key` or `key_with` must be called before `value` or `value_with`, and each
1277    /// `key` call must be followed by a corresponding `value` call. Otherwise this
1278    /// method will panic.
1279    ///
1280    /// # Examples
1281    ///
1282    /// ```
1283    /// use std::fmt;
1284    ///
1285    /// struct Foo(Vec<(String, i32)>);
1286    ///
1287    /// impl fmt::Debug for Foo {
1288    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1289    ///         let mut map = fmt.debug_map();
1290    ///         for (k, v) in &self.0 {
1291    ///             // Append "entry" to each key
1292    ///             map.key_with(|fmt| write!(fmt, "entry {k}"));
1293    ///             // Write values as hex
1294    ///             map.value_with(|fmt| write!(fmt, "{v:#010x}"));
1295    ///         }
1296    ///         map.finish()
1297    ///     }
1298    /// }
1299    ///
1300    /// assert_eq!(
1301    ///     format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1302    ///     r#"{entry A: 0x0000000a, entry B: 0x0000000b}"#,
1303    /// );
1304    /// ```
1305    #[ferrocene::prevalidated]
1306    #[stable(feature = "debug_closure_helpers", since = "1.101.0")]
1307    pub fn value_with(
1308        &mut self,
1309        value_fmt: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1310    ) -> &mut Self {
1311        self.value(&DebugOnce(Cell::new(Some(value_fmt))))
1312    }
1313
1314    /// Adds the contents of an iterator of entries to the map output.
1315    ///
1316    /// # Examples
1317    ///
1318    /// ```
1319    /// use std::fmt;
1320    ///
1321    /// struct Foo(Vec<(String, i32)>);
1322    ///
1323    /// impl fmt::Debug for Foo {
1324    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1325    ///         fmt.debug_map()
1326    ///            // We map our vec so each entries' first field will become
1327    ///            // the "key".
1328    ///            .entries(self.0.iter().map(|&(ref k, ref v)| (k, v)))
1329    ///            .finish()
1330    ///     }
1331    /// }
1332    ///
1333    /// assert_eq!(
1334    ///     format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1335    ///     r#"{"A": 10, "B": 11}"#,
1336    /// );
1337    /// ```
1338    #[stable(feature = "debug_builders", since = "1.2.0")]
1339    #[ferrocene::prevalidated]
1340    pub fn entries<K, V, I>(&mut self, entries: I) -> &mut Self
1341    where
1342        K: fmt::Debug,
1343        V: fmt::Debug,
1344        I: IntoIterator<Item = (K, V)>,
1345    {
1346        for (k, v) in entries {
1347            self.entry(&k, &v);
1348        }
1349        self
1350    }
1351
1352    /// Marks the map as non-exhaustive, indicating to the reader that there are some other
1353    /// entries that are not shown in the debug representation.
1354    ///
1355    /// # Examples
1356    ///
1357    /// ```
1358    /// use std::fmt;
1359    ///
1360    /// struct Foo(Vec<(String, i32)>);
1361    ///
1362    /// impl fmt::Debug for Foo {
1363    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1364    ///         // Print at most two elements, abbreviate the rest
1365    ///         let mut f = fmt.debug_map();
1366    ///         let mut f = f.entries(self.0.iter().take(2).map(|&(ref k, ref v)| (k, v)));
1367    ///         if self.0.len() > 2 {
1368    ///             f.finish_non_exhaustive()
1369    ///         } else {
1370    ///             f.finish()
1371    ///         }
1372    ///     }
1373    /// }
1374    ///
1375    /// assert_eq!(
1376    ///     format!("{:?}", Foo(vec![
1377    ///         ("A".to_string(), 10),
1378    ///         ("B".to_string(), 11),
1379    ///         ("C".to_string(), 12),
1380    ///     ])),
1381    ///     r#"{"A": 10, "B": 11, ..}"#,
1382    /// );
1383    /// ```
1384    #[stable(feature = "debug_more_non_exhaustive", since = "1.83.0")]
1385    #[ferrocene::prevalidated]
1386    pub fn finish_non_exhaustive(&mut self) -> fmt::Result {
1387        self.result = self.result.and_then(|_| {
1388            assert!(!self.has_key, "attempted to finish a map with a partial entry");
1389
1390            if self.has_fields {
1391                if self.is_pretty() {
1392                    let mut slot = None;
1393                    let mut state = Default::default();
1394                    let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
1395                    writer.write_str("..\n")?;
1396                    self.fmt.write_str("}")
1397                } else {
1398                    self.fmt.write_str(", ..}")
1399                }
1400            } else {
1401                self.fmt.write_str("..}")
1402            }
1403        });
1404        self.result
1405    }
1406
1407    /// Finishes output and returns any error encountered.
1408    ///
1409    /// # Panics
1410    ///
1411    /// `key` or `key_with` must be called before `value` or `value_with`, and each
1412    /// `key` call must be followed by a corresponding `value` call. Otherwise this
1413    /// method will panic.
1414    ///
1415    /// # Examples
1416    ///
1417    /// ```
1418    /// use std::fmt;
1419    ///
1420    /// struct Foo(Vec<(String, i32)>);
1421    ///
1422    /// impl fmt::Debug for Foo {
1423    ///     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1424    ///         fmt.debug_map()
1425    ///            .entries(self.0.iter().map(|&(ref k, ref v)| (k, v)))
1426    ///            .finish() // Ends the map formatting.
1427    ///     }
1428    /// }
1429    ///
1430    /// assert_eq!(
1431    ///     format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1432    ///     r#"{"A": 10, "B": 11}"#,
1433    /// );
1434    /// ```
1435    #[stable(feature = "debug_builders", since = "1.2.0")]
1436    #[ferrocene::prevalidated]
1437    pub fn finish(&mut self) -> fmt::Result {
1438        self.result = self.result.and_then(|_| {
1439            assert!(!self.has_key, "attempted to finish a map with a partial entry");
1440
1441            self.fmt.write_str("}")
1442        });
1443        self.result
1444    }
1445
1446    #[ferrocene::prevalidated]
1447    fn is_pretty(&self) -> bool {
1448        self.fmt.alternate()
1449    }
1450}
1451
1452/// Creates a type whose [`fmt::Debug`] and [`fmt::Display`] impls are
1453/// forwarded to the provided closure.
1454///
1455/// # Examples
1456///
1457/// ```
1458/// use std::fmt;
1459///
1460/// let value = 'a';
1461/// assert_eq!(format!("{}", value), "a");
1462/// assert_eq!(format!("{:?}", value), "'a'");
1463///
1464/// let wrapped = fmt::from_fn(|f| write!(f, "{value:?}"));
1465/// assert_eq!(format!("{}", wrapped), "'a'");
1466/// assert_eq!(format!("{:?}", wrapped), "'a'");
1467/// ```
1468#[stable(feature = "fmt_from_fn", since = "1.93.0")]
1469#[rustc_const_stable(feature = "const_fmt_from_fn", since = "1.95.0")]
1470#[must_use = "returns a type implementing Debug and Display, which do not have any effects unless they are used"]
1471#[ferrocene::prevalidated]
1472pub const fn from_fn<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result>(f: F) -> FromFn<F> {
1473    FromFn(f)
1474}
1475
1476/// Implements [`fmt::Debug`] and [`fmt::Display`] via the provided closure.
1477///
1478/// Created with [`from_fn`].
1479#[stable(feature = "fmt_from_fn", since = "1.93.0")]
1480#[ferrocene::prevalidated]
1481pub struct FromFn<F>(F);
1482
1483#[stable(feature = "fmt_from_fn", since = "1.93.0")]
1484impl<F> fmt::Debug for FromFn<F>
1485where
1486    F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result,
1487{
1488    #[ferrocene::prevalidated]
1489    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1490        (self.0)(f)
1491    }
1492}
1493
1494#[stable(feature = "fmt_from_fn", since = "1.93.0")]
1495impl<F> fmt::Display for FromFn<F>
1496where
1497    F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result,
1498{
1499    #[ferrocene::prevalidated]
1500    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1501        (self.0)(f)
1502    }
1503}