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, mut s: &str) -> fmt::Result {
33 if self.state.on_newline {
34 self.buf.write_str(" ")?;
37 let split = match s.find('\n') {
39 self.state.on_newline = true;
43 self.state.on_newline = false;
47 self.buf.write_str(&s[..split])?;
55 /// A struct to help with [`fmt::Debug`](Debug) implementations.
57 /// This is useful when you wish to output a formatted struct as a part of your
58 /// [`Debug::fmt`] implementation.
60 /// This can be constructed by the [`Formatter::debug_struct`] method.
72 /// impl fmt::Debug for Foo {
73 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
74 /// fmt.debug_struct("Foo")
75 /// .field("bar", &self.bar)
76 /// .field("baz", &self.baz)
82 /// format!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() }),
83 /// "Foo { bar: 10, baz: \"Hello World\" }",
86 #[must_use = "must eventually call `finish()` on Debug builders"]
87 #[allow(missing_debug_implementations)]
88 #[stable(feature = "debug_builders", since = "1.2.0")]
89 pub struct DebugStruct<'a, 'b: 'a> {
90 fmt: &'a mut fmt::Formatter<'b>,
95 pub(super) fn debug_struct_new<'a, 'b>(
96 fmt: &'a mut fmt::Formatter<'b>,
98 ) -> DebugStruct<'a, 'b> {
99 let result = fmt.write_str(name);
100 DebugStruct { fmt, result, has_fields: false }
103 impl<'a, 'b: 'a> DebugStruct<'a, 'b> {
104 /// Adds a new field to the generated struct output.
116 /// impl fmt::Debug for Bar {
117 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
118 /// fmt.debug_struct("Bar")
119 /// .field("bar", &self.bar) // We add `bar` field.
120 /// .field("another", &self.another) // We add `another` field.
121 /// // We even add a field which doesn't exist (because why not?).
122 /// .field("not_existing_field", &1)
123 /// .finish() // We're good to go!
128 /// format!("{:?}", Bar { bar: 10, another: "Hello World".to_string() }),
129 /// "Bar { bar: 10, another: \"Hello World\", not_existing_field: 1 }",
132 #[stable(feature = "debug_builders", since = "1.2.0")]
133 pub fn field(&mut self, name: &str, value: &dyn fmt::Debug) -> &mut Self {
134 self.result = self.result.and_then(|_| {
135 if self.is_pretty() {
136 if !self.has_fields {
137 self.fmt.write_str(" {\n")?;
140 let mut state = Default::default();
141 let mut writer = PadAdapter::wrap(&mut self.fmt, &mut slot, &mut state);
142 writer.write_str(name)?;
143 writer.write_str(": ")?;
144 value.fmt(&mut writer)?;
145 writer.write_str(",\n")
147 let prefix = if self.has_fields { ", " } else { " { " };
148 self.fmt.write_str(prefix)?;
149 self.fmt.write_str(name)?;
150 self.fmt.write_str(": ")?;
155 self.has_fields = true;
159 /// Marks the struct as non-exhaustive, indicating to the reader that there are some other
160 /// fields that are not shown in the debug representation.
172 /// impl fmt::Debug for Bar {
173 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
174 /// fmt.debug_struct("Bar")
175 /// .field("bar", &self.bar)
176 /// .finish_non_exhaustive() // Show that some other field(s) exist.
181 /// format!("{:?}", Bar { bar: 10, hidden: 1.0 }),
182 /// "Bar { bar: 10, .. }",
185 #[stable(feature = "debug_non_exhaustive", since = "1.53.0")]
186 pub fn finish_non_exhaustive(&mut self) -> fmt::Result {
187 self.result = self.result.and_then(|_| {
189 if self.is_pretty() {
191 let mut state = Default::default();
192 let mut writer = PadAdapter::wrap(&mut self.fmt, &mut slot, &mut state);
193 writer.write_str("..\n")?;
194 self.fmt.write_str("}")
196 self.fmt.write_str(", .. }")
199 self.fmt.write_str(" { .. }")
205 /// Finishes output and returns any error encountered.
217 /// impl fmt::Debug for Bar {
218 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
219 /// fmt.debug_struct("Bar")
220 /// .field("bar", &self.bar)
221 /// .field("baz", &self.baz)
222 /// .finish() // You need to call it to "finish" the
223 /// // struct formatting.
228 /// format!("{:?}", Bar { bar: 10, baz: "Hello World".to_string() }),
229 /// "Bar { bar: 10, baz: \"Hello World\" }",
232 #[stable(feature = "debug_builders", since = "1.2.0")]
233 pub fn finish(&mut self) -> fmt::Result {
235 self.result = self.result.and_then(|_| {
236 if self.is_pretty() { self.fmt.write_str("}") } else { self.fmt.write_str(" }") }
242 fn is_pretty(&self) -> bool {
247 /// A struct to help with [`fmt::Debug`](Debug) implementations.
249 /// This is useful when you wish to output a formatted tuple as a part of your
250 /// [`Debug::fmt`] implementation.
252 /// This can be constructed by the [`Formatter::debug_tuple`] method.
259 /// struct Foo(i32, String);
261 /// impl fmt::Debug for Foo {
262 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
263 /// fmt.debug_tuple("Foo")
271 /// format!("{:?}", Foo(10, "Hello World".to_string())),
272 /// "Foo(10, \"Hello World\")",
275 #[must_use = "must eventually call `finish()` on Debug builders"]
276 #[allow(missing_debug_implementations)]
277 #[stable(feature = "debug_builders", since = "1.2.0")]
278 pub struct DebugTuple<'a, 'b: 'a> {
279 fmt: &'a mut fmt::Formatter<'b>,
285 pub(super) fn debug_tuple_new<'a, 'b>(
286 fmt: &'a mut fmt::Formatter<'b>,
288 ) -> DebugTuple<'a, 'b> {
289 let result = fmt.write_str(name);
290 DebugTuple { fmt, result, fields: 0, empty_name: name.is_empty() }
293 impl<'a, 'b: 'a> DebugTuple<'a, 'b> {
294 /// Adds a new field to the generated tuple struct output.
301 /// struct Foo(i32, String);
303 /// impl fmt::Debug for Foo {
304 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
305 /// fmt.debug_tuple("Foo")
306 /// .field(&self.0) // We add the first field.
307 /// .field(&self.1) // We add the second field.
308 /// .finish() // We're good to go!
313 /// format!("{:?}", Foo(10, "Hello World".to_string())),
314 /// "Foo(10, \"Hello World\")",
317 #[stable(feature = "debug_builders", since = "1.2.0")]
318 pub fn field(&mut self, value: &dyn fmt::Debug) -> &mut Self {
319 self.result = self.result.and_then(|_| {
320 if self.is_pretty() {
321 if self.fields == 0 {
322 self.fmt.write_str("(\n")?;
325 let mut state = Default::default();
326 let mut writer = PadAdapter::wrap(&mut self.fmt, &mut slot, &mut state);
327 value.fmt(&mut writer)?;
328 writer.write_str(",\n")
330 let prefix = if self.fields == 0 { "(" } else { ", " };
331 self.fmt.write_str(prefix)?;
340 /// Finishes output and returns any error encountered.
347 /// struct Foo(i32, String);
349 /// impl fmt::Debug for Foo {
350 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
351 /// fmt.debug_tuple("Foo")
354 /// .finish() // You need to call it to "finish" the
355 /// // tuple formatting.
360 /// format!("{:?}", Foo(10, "Hello World".to_string())),
361 /// "Foo(10, \"Hello World\")",
364 #[stable(feature = "debug_builders", since = "1.2.0")]
365 pub fn finish(&mut self) -> fmt::Result {
367 self.result = self.result.and_then(|_| {
368 if self.fields == 1 && self.empty_name && !self.is_pretty() {
369 self.fmt.write_str(",")?;
371 self.fmt.write_str(")")
377 fn is_pretty(&self) -> bool {
382 struct DebugInner<'a, 'b: 'a> {
383 fmt: &'a mut fmt::Formatter<'b>,
388 impl<'a, 'b: 'a> DebugInner<'a, 'b> {
389 fn entry(&mut self, entry: &dyn fmt::Debug) {
390 self.result = self.result.and_then(|_| {
391 if self.is_pretty() {
392 if !self.has_fields {
393 self.fmt.write_str("\n")?;
396 let mut state = Default::default();
397 let mut writer = PadAdapter::wrap(&mut self.fmt, &mut slot, &mut state);
398 entry.fmt(&mut writer)?;
399 writer.write_str(",\n")
402 self.fmt.write_str(", ")?
408 self.has_fields = true;
411 fn is_pretty(&self) -> bool {
416 /// A struct to help with [`fmt::Debug`](Debug) implementations.
418 /// This is useful when you wish to output a formatted set of items as a part
419 /// of your [`Debug::fmt`] implementation.
421 /// This can be constructed by the [`Formatter::debug_set`] method.
428 /// struct Foo(Vec<i32>);
430 /// impl fmt::Debug for Foo {
431 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
432 /// fmt.debug_set().entries(self.0.iter()).finish()
437 /// format!("{:?}", Foo(vec![10, 11])),
441 #[must_use = "must eventually call `finish()` on Debug builders"]
442 #[allow(missing_debug_implementations)]
443 #[stable(feature = "debug_builders", since = "1.2.0")]
444 pub struct DebugSet<'a, 'b: 'a> {
445 inner: DebugInner<'a, 'b>,
448 pub(super) fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugSet<'a, 'b> {
449 let result = fmt.write_str("{");
450 DebugSet { inner: DebugInner { fmt, result, has_fields: false } }
453 impl<'a, 'b: 'a> DebugSet<'a, 'b> {
454 /// Adds a new entry to the set output.
461 /// struct Foo(Vec<i32>, Vec<u32>);
463 /// impl fmt::Debug for Foo {
464 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
466 /// .entry(&self.0) // Adds the first "entry".
467 /// .entry(&self.1) // Adds the second "entry".
473 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
474 /// "{[10, 11], [12, 13]}",
477 #[stable(feature = "debug_builders", since = "1.2.0")]
478 pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut Self {
479 self.inner.entry(entry);
483 /// Adds the contents of an iterator of entries to the set output.
490 /// struct Foo(Vec<i32>, Vec<u32>);
492 /// impl fmt::Debug for Foo {
493 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
495 /// .entries(self.0.iter()) // Adds the first "entry".
496 /// .entries(self.1.iter()) // Adds the second "entry".
502 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
503 /// "{10, 11, 12, 13}",
506 #[stable(feature = "debug_builders", since = "1.2.0")]
507 pub fn entries<D, I>(&mut self, entries: I) -> &mut Self
510 I: IntoIterator<Item = D>,
512 for entry in entries {
518 /// Finishes output and returns any error encountered.
525 /// struct Foo(Vec<i32>);
527 /// impl fmt::Debug for Foo {
528 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
530 /// .entries(self.0.iter())
531 /// .finish() // Ends the struct formatting.
536 /// format!("{:?}", Foo(vec![10, 11])),
540 #[stable(feature = "debug_builders", since = "1.2.0")]
541 pub fn finish(&mut self) -> fmt::Result {
542 self.inner.result.and_then(|_| self.inner.fmt.write_str("}"))
546 /// A struct to help with [`fmt::Debug`](Debug) implementations.
548 /// This is useful when you wish to output a formatted list of items as a part
549 /// of your [`Debug::fmt`] implementation.
551 /// This can be constructed by the [`Formatter::debug_list`] method.
558 /// struct Foo(Vec<i32>);
560 /// impl fmt::Debug for Foo {
561 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
562 /// fmt.debug_list().entries(self.0.iter()).finish()
567 /// format!("{:?}", Foo(vec![10, 11])),
571 #[must_use = "must eventually call `finish()` on Debug builders"]
572 #[allow(missing_debug_implementations)]
573 #[stable(feature = "debug_builders", since = "1.2.0")]
574 pub struct DebugList<'a, 'b: 'a> {
575 inner: DebugInner<'a, 'b>,
578 pub(super) fn debug_list_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugList<'a, 'b> {
579 let result = fmt.write_str("[");
580 DebugList { inner: DebugInner { fmt, result, has_fields: false } }
583 impl<'a, 'b: 'a> DebugList<'a, 'b> {
584 /// Adds a new entry to the list output.
591 /// struct Foo(Vec<i32>, Vec<u32>);
593 /// impl fmt::Debug for Foo {
594 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
596 /// .entry(&self.0) // We add the first "entry".
597 /// .entry(&self.1) // We add the second "entry".
603 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
604 /// "[[10, 11], [12, 13]]",
607 #[stable(feature = "debug_builders", since = "1.2.0")]
608 pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut Self {
609 self.inner.entry(entry);
613 /// Adds the contents of an iterator of entries to the list output.
620 /// struct Foo(Vec<i32>, Vec<u32>);
622 /// impl fmt::Debug for Foo {
623 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
625 /// .entries(self.0.iter())
626 /// .entries(self.1.iter())
632 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
633 /// "[10, 11, 12, 13]",
636 #[stable(feature = "debug_builders", since = "1.2.0")]
637 pub fn entries<D, I>(&mut self, entries: I) -> &mut Self
640 I: IntoIterator<Item = D>,
642 for entry in entries {
648 /// Finishes output and returns any error encountered.
655 /// struct Foo(Vec<i32>);
657 /// impl fmt::Debug for Foo {
658 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
660 /// .entries(self.0.iter())
661 /// .finish() // Ends the struct formatting.
666 /// format!("{:?}", Foo(vec![10, 11])),
670 #[stable(feature = "debug_builders", since = "1.2.0")]
671 pub fn finish(&mut self) -> fmt::Result {
672 self.inner.result.and_then(|_| self.inner.fmt.write_str("]"))
676 /// A struct to help with [`fmt::Debug`](Debug) implementations.
678 /// This is useful when you wish to output a formatted map as a part of your
679 /// [`Debug::fmt`] implementation.
681 /// This can be constructed by the [`Formatter::debug_map`] method.
688 /// struct Foo(Vec<(String, i32)>);
690 /// impl fmt::Debug for Foo {
691 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
692 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
697 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
698 /// "{\"A\": 10, \"B\": 11}",
701 #[must_use = "must eventually call `finish()` on Debug builders"]
702 #[allow(missing_debug_implementations)]
703 #[stable(feature = "debug_builders", since = "1.2.0")]
704 pub struct DebugMap<'a, 'b: 'a> {
705 fmt: &'a mut fmt::Formatter<'b>,
709 // The state of newlines is tracked between keys and values
710 state: PadAdapterState,
713 pub(super) fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugMap<'a, 'b> {
714 let result = fmt.write_str("{");
715 DebugMap { fmt, result, has_fields: false, has_key: false, state: Default::default() }
718 impl<'a, 'b: 'a> DebugMap<'a, 'b> {
719 /// Adds a new entry to the map output.
726 /// struct Foo(Vec<(String, i32)>);
728 /// impl fmt::Debug for Foo {
729 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
731 /// .entry(&"whole", &self.0) // We add the "whole" entry.
737 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
738 /// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
741 #[stable(feature = "debug_builders", since = "1.2.0")]
742 pub fn entry(&mut self, key: &dyn fmt::Debug, value: &dyn fmt::Debug) -> &mut Self {
743 self.key(key).value(value)
746 /// Adds the key part of a new entry to the map output.
748 /// This method, together with `value`, is an alternative to `entry` that
749 /// can be used when the complete entry isn't known upfront. Prefer the `entry`
750 /// method when it's possible to use.
754 /// `key` must be called before `value` and each call to `key` must be followed
755 /// by a corresponding call to `value`. Otherwise this method will panic.
762 /// struct Foo(Vec<(String, i32)>);
764 /// impl fmt::Debug for Foo {
765 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
767 /// .key(&"whole").value(&self.0) // We add the "whole" entry.
773 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
774 /// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
777 #[stable(feature = "debug_map_key_value", since = "1.42.0")]
778 pub fn key(&mut self, key: &dyn fmt::Debug) -> &mut Self {
779 self.result = self.result.and_then(|_| {
782 "attempted to begin a new map entry \
783 without completing the previous one"
786 if self.is_pretty() {
787 if !self.has_fields {
788 self.fmt.write_str("\n")?;
791 self.state = Default::default();
792 let mut writer = PadAdapter::wrap(&mut self.fmt, &mut slot, &mut self.state);
793 key.fmt(&mut writer)?;
794 writer.write_str(": ")?;
797 self.fmt.write_str(", ")?
800 self.fmt.write_str(": ")?;
810 /// Adds the value part of a new entry to the map output.
812 /// This method, together with `key`, is an alternative to `entry` that
813 /// can be used when the complete entry isn't known upfront. Prefer the `entry`
814 /// method when it's possible to use.
818 /// `key` must be called before `value` and each call to `key` must be followed
819 /// by a corresponding call to `value`. Otherwise this method will panic.
826 /// struct Foo(Vec<(String, i32)>);
828 /// impl fmt::Debug for Foo {
829 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
831 /// .key(&"whole").value(&self.0) // We add the "whole" entry.
837 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
838 /// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
841 #[stable(feature = "debug_map_key_value", since = "1.42.0")]
842 pub fn value(&mut self, value: &dyn fmt::Debug) -> &mut Self {
843 self.result = self.result.and_then(|_| {
844 assert!(self.has_key, "attempted to format a map value before its key");
846 if self.is_pretty() {
848 let mut writer = PadAdapter::wrap(&mut self.fmt, &mut slot, &mut self.state);
849 value.fmt(&mut writer)?;
850 writer.write_str(",\n")?;
852 value.fmt(self.fmt)?;
855 self.has_key = false;
859 self.has_fields = true;
863 /// Adds the contents of an iterator of entries to the map output.
870 /// struct Foo(Vec<(String, i32)>);
872 /// impl fmt::Debug for Foo {
873 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
875 /// // We map our vec so each entries' first field will become
877 /// .entries(self.0.iter().map(|&(ref k, ref v)| (k, v)))
883 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
884 /// "{\"A\": 10, \"B\": 11}",
887 #[stable(feature = "debug_builders", since = "1.2.0")]
888 pub fn entries<K, V, I>(&mut self, entries: I) -> &mut Self
892 I: IntoIterator<Item = (K, V)>,
894 for (k, v) in entries {
900 /// Finishes output and returns any error encountered.
904 /// `key` must be called before `value` and each call to `key` must be followed
905 /// by a corresponding call to `value`. Otherwise this method will panic.
912 /// struct Foo(Vec<(String, i32)>);
914 /// impl fmt::Debug for Foo {
915 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
917 /// .entries(self.0.iter().map(|&(ref k, ref v)| (k, v)))
918 /// .finish() // Ends the struct formatting.
923 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
924 /// "{\"A\": 10, \"B\": 11}",
927 #[stable(feature = "debug_builders", since = "1.2.0")]
928 pub fn finish(&mut self) -> fmt::Result {
929 self.result.and_then(|_| {
930 assert!(!self.has_key, "attempted to finish a map with a partial entry");
932 self.fmt.write_str("}")
936 fn is_pretty(&self) -> bool {