1 #![allow(unused_imports)]
3 use crate::fmt::{self, Debug, Formatter};
5 struct PadAdapter<'buf, 'state> {
6 buf: &'buf mut (dyn fmt::Write + 'buf),
7 state: &'state mut PadAdapterState,
10 struct PadAdapterState {
14 impl Default for PadAdapterState {
15 fn default() -> Self {
16 PadAdapterState { on_newline: true }
20 impl<'buf, 'state> PadAdapter<'buf, 'state> {
21 fn wrap<'slot, 'fmt: 'buf + 'slot>(
22 fmt: &'fmt mut fmt::Formatter<'_>,
23 slot: &'slot mut Option<Self>,
24 state: &'state mut PadAdapterState,
25 ) -> fmt::Formatter<'slot> {
26 fmt.wrap_buf(move |buf| slot.insert(PadAdapter { buf, state }))
30 impl fmt::Write for PadAdapter<'_, '_> {
31 fn write_str(&mut self, s: &str) -> fmt::Result {
32 for s in s.split_inclusive('\n') {
33 if self.state.on_newline {
34 self.buf.write_str(" ")?;
37 self.state.on_newline = s.ends_with('\n');
38 self.buf.write_str(s)?;
45 /// A struct to help with [`fmt::Debug`](Debug) implementations.
47 /// This is useful when you wish to output a formatted struct as a part of your
48 /// [`Debug::fmt`] implementation.
50 /// This can be constructed by the [`Formatter::debug_struct`] method.
62 /// impl fmt::Debug for Foo {
63 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
64 /// fmt.debug_struct("Foo")
65 /// .field("bar", &self.bar)
66 /// .field("baz", &self.baz)
72 /// format!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() }),
73 /// "Foo { bar: 10, baz: \"Hello World\" }",
76 #[must_use = "must eventually call `finish()` on Debug builders"]
77 #[allow(missing_debug_implementations)]
78 #[stable(feature = "debug_builders", since = "1.2.0")]
79 pub struct DebugStruct<'a, 'b: 'a> {
80 fmt: &'a mut fmt::Formatter<'b>,
85 pub(super) fn debug_struct_new<'a, 'b>(
86 fmt: &'a mut fmt::Formatter<'b>,
88 ) -> DebugStruct<'a, 'b> {
89 let result = fmt.write_str(name);
90 DebugStruct { fmt, result, has_fields: false }
93 impl<'a, 'b: 'a> DebugStruct<'a, 'b> {
94 /// Adds a new field to the generated struct output.
106 /// impl fmt::Debug for Bar {
107 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
108 /// fmt.debug_struct("Bar")
109 /// .field("bar", &self.bar) // We add `bar` field.
110 /// .field("another", &self.another) // We add `another` field.
111 /// // We even add a field which doesn't exist (because why not?).
112 /// .field("not_existing_field", &1)
113 /// .finish() // We're good to go!
118 /// format!("{:?}", Bar { bar: 10, another: "Hello World".to_string() }),
119 /// "Bar { bar: 10, another: \"Hello World\", not_existing_field: 1 }",
122 #[stable(feature = "debug_builders", since = "1.2.0")]
123 pub fn field(&mut self, name: &str, value: &dyn fmt::Debug) -> &mut Self {
124 self.result = self.result.and_then(|_| {
125 if self.is_pretty() {
126 if !self.has_fields {
127 self.fmt.write_str(" {\n")?;
130 let mut state = Default::default();
131 let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
132 writer.write_str(name)?;
133 writer.write_str(": ")?;
134 value.fmt(&mut writer)?;
135 writer.write_str(",\n")
137 let prefix = if self.has_fields { ", " } else { " { " };
138 self.fmt.write_str(prefix)?;
139 self.fmt.write_str(name)?;
140 self.fmt.write_str(": ")?;
145 self.has_fields = true;
149 /// Marks the struct as non-exhaustive, indicating to the reader that there are some other
150 /// fields that are not shown in the debug representation.
162 /// impl fmt::Debug for Bar {
163 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
164 /// fmt.debug_struct("Bar")
165 /// .field("bar", &self.bar)
166 /// .finish_non_exhaustive() // Show that some other field(s) exist.
171 /// format!("{:?}", Bar { bar: 10, hidden: 1.0 }),
172 /// "Bar { bar: 10, .. }",
175 #[stable(feature = "debug_non_exhaustive", since = "1.53.0")]
176 pub fn finish_non_exhaustive(&mut self) -> fmt::Result {
177 self.result = self.result.and_then(|_| {
179 if self.is_pretty() {
181 let mut state = Default::default();
182 let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
183 writer.write_str("..\n")?;
184 self.fmt.write_str("}")
186 self.fmt.write_str(", .. }")
189 self.fmt.write_str(" { .. }")
195 /// Finishes output and returns any error encountered.
207 /// impl fmt::Debug for Bar {
208 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
209 /// fmt.debug_struct("Bar")
210 /// .field("bar", &self.bar)
211 /// .field("baz", &self.baz)
212 /// .finish() // You need to call it to "finish" the
213 /// // struct formatting.
218 /// format!("{:?}", Bar { bar: 10, baz: "Hello World".to_string() }),
219 /// "Bar { bar: 10, baz: \"Hello World\" }",
222 #[stable(feature = "debug_builders", since = "1.2.0")]
223 pub fn finish(&mut self) -> fmt::Result {
225 self.result = self.result.and_then(|_| {
226 if self.is_pretty() { self.fmt.write_str("}") } else { self.fmt.write_str(" }") }
232 fn is_pretty(&self) -> bool {
237 /// A struct to help with [`fmt::Debug`](Debug) implementations.
239 /// This is useful when you wish to output a formatted tuple as a part of your
240 /// [`Debug::fmt`] implementation.
242 /// This can be constructed by the [`Formatter::debug_tuple`] method.
249 /// struct Foo(i32, String);
251 /// impl fmt::Debug for Foo {
252 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
253 /// fmt.debug_tuple("Foo")
261 /// format!("{:?}", Foo(10, "Hello World".to_string())),
262 /// "Foo(10, \"Hello World\")",
265 #[must_use = "must eventually call `finish()` on Debug builders"]
266 #[allow(missing_debug_implementations)]
267 #[stable(feature = "debug_builders", since = "1.2.0")]
268 pub struct DebugTuple<'a, 'b: 'a> {
269 fmt: &'a mut fmt::Formatter<'b>,
275 pub(super) fn debug_tuple_new<'a, 'b>(
276 fmt: &'a mut fmt::Formatter<'b>,
278 ) -> DebugTuple<'a, 'b> {
279 let result = fmt.write_str(name);
280 DebugTuple { fmt, result, fields: 0, empty_name: name.is_empty() }
283 impl<'a, 'b: 'a> DebugTuple<'a, 'b> {
284 /// Adds a new field to the generated tuple struct output.
291 /// struct Foo(i32, String);
293 /// impl fmt::Debug for Foo {
294 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
295 /// fmt.debug_tuple("Foo")
296 /// .field(&self.0) // We add the first field.
297 /// .field(&self.1) // We add the second field.
298 /// .finish() // We're good to go!
303 /// format!("{:?}", Foo(10, "Hello World".to_string())),
304 /// "Foo(10, \"Hello World\")",
307 #[stable(feature = "debug_builders", since = "1.2.0")]
308 pub fn field(&mut self, value: &dyn fmt::Debug) -> &mut Self {
309 self.result = self.result.and_then(|_| {
310 if self.is_pretty() {
311 if self.fields == 0 {
312 self.fmt.write_str("(\n")?;
315 let mut state = Default::default();
316 let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
317 value.fmt(&mut writer)?;
318 writer.write_str(",\n")
320 let prefix = if self.fields == 0 { "(" } else { ", " };
321 self.fmt.write_str(prefix)?;
330 /// Finishes output and returns any error encountered.
337 /// struct Foo(i32, String);
339 /// impl fmt::Debug for Foo {
340 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
341 /// fmt.debug_tuple("Foo")
344 /// .finish() // You need to call it to "finish" the
345 /// // tuple formatting.
350 /// format!("{:?}", Foo(10, "Hello World".to_string())),
351 /// "Foo(10, \"Hello World\")",
354 #[stable(feature = "debug_builders", since = "1.2.0")]
355 pub fn finish(&mut self) -> fmt::Result {
357 self.result = self.result.and_then(|_| {
358 if self.fields == 1 && self.empty_name && !self.is_pretty() {
359 self.fmt.write_str(",")?;
361 self.fmt.write_str(")")
367 fn is_pretty(&self) -> bool {
372 struct DebugInner<'a, 'b: 'a> {
373 fmt: &'a mut fmt::Formatter<'b>,
378 impl<'a, 'b: 'a> DebugInner<'a, 'b> {
379 fn entry(&mut self, entry: &dyn fmt::Debug) {
380 self.result = self.result.and_then(|_| {
381 if self.is_pretty() {
382 if !self.has_fields {
383 self.fmt.write_str("\n")?;
386 let mut state = Default::default();
387 let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
388 entry.fmt(&mut writer)?;
389 writer.write_str(",\n")
392 self.fmt.write_str(", ")?
398 self.has_fields = true;
401 fn is_pretty(&self) -> bool {
406 /// A struct to help with [`fmt::Debug`](Debug) implementations.
408 /// This is useful when you wish to output a formatted set of items as a part
409 /// of your [`Debug::fmt`] implementation.
411 /// This can be constructed by the [`Formatter::debug_set`] method.
418 /// struct Foo(Vec<i32>);
420 /// impl fmt::Debug for Foo {
421 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
422 /// fmt.debug_set().entries(self.0.iter()).finish()
427 /// format!("{:?}", Foo(vec![10, 11])),
431 #[must_use = "must eventually call `finish()` on Debug builders"]
432 #[allow(missing_debug_implementations)]
433 #[stable(feature = "debug_builders", since = "1.2.0")]
434 pub struct DebugSet<'a, 'b: 'a> {
435 inner: DebugInner<'a, 'b>,
438 pub(super) fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugSet<'a, 'b> {
439 let result = fmt.write_str("{");
440 DebugSet { inner: DebugInner { fmt, result, has_fields: false } }
443 impl<'a, 'b: 'a> DebugSet<'a, 'b> {
444 /// Adds a new entry to the set output.
451 /// struct Foo(Vec<i32>, Vec<u32>);
453 /// impl fmt::Debug for Foo {
454 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
456 /// .entry(&self.0) // Adds the first "entry".
457 /// .entry(&self.1) // Adds the second "entry".
463 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
464 /// "{[10, 11], [12, 13]}",
467 #[stable(feature = "debug_builders", since = "1.2.0")]
468 pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut Self {
469 self.inner.entry(entry);
473 /// Adds the contents of an iterator of entries to the set output.
480 /// struct Foo(Vec<i32>, Vec<u32>);
482 /// impl fmt::Debug for Foo {
483 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
485 /// .entries(self.0.iter()) // Adds the first "entry".
486 /// .entries(self.1.iter()) // Adds the second "entry".
492 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
493 /// "{10, 11, 12, 13}",
496 #[stable(feature = "debug_builders", since = "1.2.0")]
497 pub fn entries<D, I>(&mut self, entries: I) -> &mut Self
500 I: IntoIterator<Item = D>,
502 for entry in entries {
508 /// Finishes output and returns any error encountered.
515 /// struct Foo(Vec<i32>);
517 /// impl fmt::Debug for Foo {
518 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
520 /// .entries(self.0.iter())
521 /// .finish() // Ends the struct formatting.
526 /// format!("{:?}", Foo(vec![10, 11])),
530 #[stable(feature = "debug_builders", since = "1.2.0")]
531 pub fn finish(&mut self) -> fmt::Result {
532 self.inner.result.and_then(|_| self.inner.fmt.write_str("}"))
536 /// A struct to help with [`fmt::Debug`](Debug) implementations.
538 /// This is useful when you wish to output a formatted list of items as a part
539 /// of your [`Debug::fmt`] implementation.
541 /// This can be constructed by the [`Formatter::debug_list`] method.
548 /// struct Foo(Vec<i32>);
550 /// impl fmt::Debug for Foo {
551 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
552 /// fmt.debug_list().entries(self.0.iter()).finish()
557 /// format!("{:?}", Foo(vec![10, 11])),
561 #[must_use = "must eventually call `finish()` on Debug builders"]
562 #[allow(missing_debug_implementations)]
563 #[stable(feature = "debug_builders", since = "1.2.0")]
564 pub struct DebugList<'a, 'b: 'a> {
565 inner: DebugInner<'a, 'b>,
568 pub(super) fn debug_list_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugList<'a, 'b> {
569 let result = fmt.write_str("[");
570 DebugList { inner: DebugInner { fmt, result, has_fields: false } }
573 impl<'a, 'b: 'a> DebugList<'a, 'b> {
574 /// Adds a new entry to the list output.
581 /// struct Foo(Vec<i32>, Vec<u32>);
583 /// impl fmt::Debug for Foo {
584 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
586 /// .entry(&self.0) // We add the first "entry".
587 /// .entry(&self.1) // We add the second "entry".
593 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
594 /// "[[10, 11], [12, 13]]",
597 #[stable(feature = "debug_builders", since = "1.2.0")]
598 pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut Self {
599 self.inner.entry(entry);
603 /// Adds the contents of an iterator of entries to the list output.
610 /// struct Foo(Vec<i32>, Vec<u32>);
612 /// impl fmt::Debug for Foo {
613 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
615 /// .entries(self.0.iter())
616 /// .entries(self.1.iter())
622 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
623 /// "[10, 11, 12, 13]",
626 #[stable(feature = "debug_builders", since = "1.2.0")]
627 pub fn entries<D, I>(&mut self, entries: I) -> &mut Self
630 I: IntoIterator<Item = D>,
632 for entry in entries {
638 /// Finishes output and returns any error encountered.
645 /// struct Foo(Vec<i32>);
647 /// impl fmt::Debug for Foo {
648 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
650 /// .entries(self.0.iter())
651 /// .finish() // Ends the struct formatting.
656 /// format!("{:?}", Foo(vec![10, 11])),
660 #[stable(feature = "debug_builders", since = "1.2.0")]
661 pub fn finish(&mut self) -> fmt::Result {
662 self.inner.result.and_then(|_| self.inner.fmt.write_str("]"))
666 /// A struct to help with [`fmt::Debug`](Debug) implementations.
668 /// This is useful when you wish to output a formatted map as a part of your
669 /// [`Debug::fmt`] implementation.
671 /// This can be constructed by the [`Formatter::debug_map`] method.
678 /// struct Foo(Vec<(String, i32)>);
680 /// impl fmt::Debug for Foo {
681 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
682 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
687 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
688 /// "{\"A\": 10, \"B\": 11}",
691 #[must_use = "must eventually call `finish()` on Debug builders"]
692 #[allow(missing_debug_implementations)]
693 #[stable(feature = "debug_builders", since = "1.2.0")]
694 pub struct DebugMap<'a, 'b: 'a> {
695 fmt: &'a mut fmt::Formatter<'b>,
699 // The state of newlines is tracked between keys and values
700 state: PadAdapterState,
703 pub(super) fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugMap<'a, 'b> {
704 let result = fmt.write_str("{");
705 DebugMap { fmt, result, has_fields: false, has_key: false, state: Default::default() }
708 impl<'a, 'b: 'a> DebugMap<'a, 'b> {
709 /// Adds a new entry to the map output.
716 /// struct Foo(Vec<(String, i32)>);
718 /// impl fmt::Debug for Foo {
719 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
721 /// .entry(&"whole", &self.0) // We add the "whole" entry.
727 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
728 /// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
731 #[stable(feature = "debug_builders", since = "1.2.0")]
732 pub fn entry(&mut self, key: &dyn fmt::Debug, value: &dyn fmt::Debug) -> &mut Self {
733 self.key(key).value(value)
736 /// Adds the key part of a new entry to the map output.
738 /// This method, together with `value`, is an alternative to `entry` that
739 /// can be used when the complete entry isn't known upfront. Prefer the `entry`
740 /// method when it's possible to use.
744 /// `key` must be called before `value` and each call to `key` must be followed
745 /// by a corresponding call to `value`. Otherwise this method will panic.
752 /// struct Foo(Vec<(String, i32)>);
754 /// impl fmt::Debug for Foo {
755 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
757 /// .key(&"whole").value(&self.0) // We add the "whole" entry.
763 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
764 /// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
767 #[stable(feature = "debug_map_key_value", since = "1.42.0")]
768 pub fn key(&mut self, key: &dyn fmt::Debug) -> &mut Self {
769 self.result = self.result.and_then(|_| {
772 "attempted to begin a new map entry \
773 without completing the previous one"
776 if self.is_pretty() {
777 if !self.has_fields {
778 self.fmt.write_str("\n")?;
781 self.state = Default::default();
782 let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut self.state);
783 key.fmt(&mut writer)?;
784 writer.write_str(": ")?;
787 self.fmt.write_str(", ")?
790 self.fmt.write_str(": ")?;
800 /// Adds the value part of a new entry to the map output.
802 /// This method, together with `key`, is an alternative to `entry` that
803 /// can be used when the complete entry isn't known upfront. Prefer the `entry`
804 /// method when it's possible to use.
808 /// `key` must be called before `value` and each call to `key` must be followed
809 /// by a corresponding call to `value`. Otherwise this method will panic.
816 /// struct Foo(Vec<(String, i32)>);
818 /// impl fmt::Debug for Foo {
819 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
821 /// .key(&"whole").value(&self.0) // We add the "whole" entry.
827 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
828 /// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
831 #[stable(feature = "debug_map_key_value", since = "1.42.0")]
832 pub fn value(&mut self, value: &dyn fmt::Debug) -> &mut Self {
833 self.result = self.result.and_then(|_| {
834 assert!(self.has_key, "attempted to format a map value before its key");
836 if self.is_pretty() {
838 let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut self.state);
839 value.fmt(&mut writer)?;
840 writer.write_str(",\n")?;
842 value.fmt(self.fmt)?;
845 self.has_key = false;
849 self.has_fields = true;
853 /// Adds the contents of an iterator of entries to the map output.
860 /// struct Foo(Vec<(String, i32)>);
862 /// impl fmt::Debug for Foo {
863 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
865 /// // We map our vec so each entries' first field will become
867 /// .entries(self.0.iter().map(|&(ref k, ref v)| (k, v)))
873 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
874 /// "{\"A\": 10, \"B\": 11}",
877 #[stable(feature = "debug_builders", since = "1.2.0")]
878 pub fn entries<K, V, I>(&mut self, entries: I) -> &mut Self
882 I: IntoIterator<Item = (K, V)>,
884 for (k, v) in entries {
890 /// Finishes output and returns any error encountered.
894 /// `key` must be called before `value` and each call to `key` must be followed
895 /// by a corresponding call to `value`. Otherwise this method will panic.
902 /// struct Foo(Vec<(String, i32)>);
904 /// impl fmt::Debug for Foo {
905 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
907 /// .entries(self.0.iter().map(|&(ref k, ref v)| (k, v)))
908 /// .finish() // Ends the struct formatting.
913 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
914 /// "{\"A\": 10, \"B\": 11}",
917 #[stable(feature = "debug_builders", since = "1.2.0")]
918 pub fn finish(&mut self) -> fmt::Result {
919 self.result.and_then(|_| {
920 assert!(!self.has_key, "attempted to finish a map with a partial entry");
922 self.fmt.write_str("}")
926 fn is_pretty(&self) -> bool {