3 struct PadAdapter<'buf, 'state> {
4 buf: &'buf mut (dyn fmt::Write + 'buf),
5 state: &'state mut PadAdapterState,
8 struct PadAdapterState {
12 impl Default for PadAdapterState {
13 fn default() -> Self {
20 impl<'buf, 'state> PadAdapter<'buf, 'state> {
21 fn wrap<'slot, 'fmt: 'buf+'slot>(fmt: &'fmt mut fmt::Formatter<'_>,
22 slot: &'slot mut Option<Self>,
23 state: &'state mut PadAdapterState) -> fmt::Formatter<'slot> {
24 fmt.wrap_buf(move |buf| {
25 *slot = Some(PadAdapter {
29 slot.as_mut().unwrap()
34 impl fmt::Write for PadAdapter<'_, '_> {
35 fn write_str(&mut self, mut s: &str) -> fmt::Result {
37 if self.state.on_newline {
38 self.buf.write_str(" ")?;
41 let split = match s.find('\n') {
43 self.state.on_newline = true;
47 self.state.on_newline = false;
51 self.buf.write_str(&s[..split])?;
59 /// A struct to help with [`fmt::Debug`](trait.Debug.html) implementations.
61 /// This is useful when you wish to output a formatted struct as a part of your
62 /// [`Debug::fmt`](trait.Debug.html#tymethod.fmt) implementation.
64 /// This can be constructed by the
65 /// [`Formatter::debug_struct`](struct.Formatter.html#method.debug_struct)
78 /// impl fmt::Debug for Foo {
79 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
80 /// fmt.debug_struct("Foo")
81 /// .field("bar", &self.bar)
82 /// .field("baz", &self.baz)
88 /// format!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() }),
89 /// "Foo { bar: 10, baz: \"Hello World\" }",
92 #[must_use = "must eventually call `finish()` on Debug builders"]
93 #[allow(missing_debug_implementations)]
94 #[stable(feature = "debug_builders", since = "1.2.0")]
95 pub struct DebugStruct<'a, 'b: 'a> {
96 fmt: &'a mut fmt::Formatter<'b>,
101 pub(super) fn debug_struct_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>,
103 -> DebugStruct<'a, 'b> {
104 let result = fmt.write_str(name);
112 impl<'a, 'b: 'a> DebugStruct<'a, 'b> {
113 /// Adds a new field to the generated struct output.
125 /// impl fmt::Debug for Bar {
126 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
127 /// fmt.debug_struct("Bar")
128 /// .field("bar", &self.bar) // We add `bar` field.
129 /// .field("another", &self.another) // We add `another` field.
130 /// // We even add a field which doesn't exist (because why not?).
131 /// .field("not_existing_field", &1)
132 /// .finish() // We're good to go!
137 /// format!("{:?}", Bar { bar: 10, another: "Hello World".to_string() }),
138 /// "Bar { bar: 10, another: \"Hello World\", not_existing_field: 1 }",
141 #[stable(feature = "debug_builders", since = "1.2.0")]
142 pub fn field(&mut self, name: &str, value: &dyn fmt::Debug) -> &mut DebugStruct<'a, 'b> {
143 self.result = self.result.and_then(|_| {
144 if self.is_pretty() {
145 if !self.has_fields {
146 self.fmt.write_str(" {\n")?;
149 let mut state = Default::default();
150 let mut writer = PadAdapter::wrap(&mut self.fmt, &mut slot, &mut state);
151 writer.write_str(name)?;
152 writer.write_str(": ")?;
153 value.fmt(&mut writer)?;
154 writer.write_str(",\n")
156 let prefix = if self.has_fields { ", " } else { " { " };
157 self.fmt.write_str(prefix)?;
158 self.fmt.write_str(name)?;
159 self.fmt.write_str(": ")?;
164 self.has_fields = true;
168 /// Finishes output and returns any error encountered.
180 /// impl fmt::Debug for Bar {
181 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
182 /// fmt.debug_struct("Bar")
183 /// .field("bar", &self.bar)
184 /// .field("baz", &self.baz)
185 /// .finish() // You need to call it to "finish" the
186 /// // struct formatting.
191 /// format!("{:?}", Bar { bar: 10, baz: "Hello World".to_string() }),
192 /// "Bar { bar: 10, baz: \"Hello World\" }",
195 #[stable(feature = "debug_builders", since = "1.2.0")]
196 pub fn finish(&mut self) -> fmt::Result {
198 self.result = self.result.and_then(|_| {
199 if self.is_pretty() {
200 self.fmt.write_str("}")
202 self.fmt.write_str(" }")
209 fn is_pretty(&self) -> bool {
214 /// A struct to help with [`fmt::Debug`](trait.Debug.html) implementations.
216 /// This is useful when you wish to output a formatted tuple as a part of your
217 /// [`Debug::fmt`](trait.Debug.html#tymethod.fmt) implementation.
219 /// This can be constructed by the
220 /// [`Formatter::debug_tuple`](struct.Formatter.html#method.debug_tuple)
228 /// struct Foo(i32, String);
230 /// impl fmt::Debug for Foo {
231 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
232 /// fmt.debug_tuple("Foo")
240 /// format!("{:?}", Foo(10, "Hello World".to_string())),
241 /// "Foo(10, \"Hello World\")",
244 #[must_use = "must eventually call `finish()` on Debug builders"]
245 #[allow(missing_debug_implementations)]
246 #[stable(feature = "debug_builders", since = "1.2.0")]
247 pub struct DebugTuple<'a, 'b: 'a> {
248 fmt: &'a mut fmt::Formatter<'b>,
254 pub(super) fn debug_tuple_new<'a, 'b>(
255 fmt: &'a mut fmt::Formatter<'b>,
257 ) -> DebugTuple<'a, 'b> {
258 let result = fmt.write_str(name);
263 empty_name: name.is_empty(),
267 impl<'a, 'b: 'a> DebugTuple<'a, 'b> {
268 /// Adds a new field to the generated tuple struct output.
275 /// struct Foo(i32, String);
277 /// impl fmt::Debug for Foo {
278 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
279 /// fmt.debug_tuple("Foo")
280 /// .field(&self.0) // We add the first field.
281 /// .field(&self.1) // We add the second field.
282 /// .finish() // We're good to go!
287 /// format!("{:?}", Foo(10, "Hello World".to_string())),
288 /// "Foo(10, \"Hello World\")",
291 #[stable(feature = "debug_builders", since = "1.2.0")]
292 pub fn field(&mut self, value: &dyn fmt::Debug) -> &mut DebugTuple<'a, 'b> {
293 self.result = self.result.and_then(|_| {
294 if self.is_pretty() {
295 if self.fields == 0 {
296 self.fmt.write_str("(\n")?;
299 let mut state = Default::default();
300 let mut writer = PadAdapter::wrap(&mut self.fmt, &mut slot, &mut state);
301 value.fmt(&mut writer)?;
302 writer.write_str(",\n")
304 let prefix = if self.fields == 0 { "(" } else { ", " };
305 self.fmt.write_str(prefix)?;
314 /// Finishes output and returns any error encountered.
321 /// struct Foo(i32, String);
323 /// impl fmt::Debug for Foo {
324 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
325 /// fmt.debug_tuple("Foo")
328 /// .finish() // You need to call it to "finish" the
329 /// // tuple formatting.
334 /// format!("{:?}", Foo(10, "Hello World".to_string())),
335 /// "Foo(10, \"Hello World\")",
338 #[stable(feature = "debug_builders", since = "1.2.0")]
339 pub fn finish(&mut self) -> fmt::Result {
341 self.result = self.result.and_then(|_| {
342 if self.fields == 1 && self.empty_name && !self.is_pretty() {
343 self.fmt.write_str(",")?;
345 self.fmt.write_str(")")
351 fn is_pretty(&self) -> bool {
356 struct DebugInner<'a, 'b: 'a> {
357 fmt: &'a mut fmt::Formatter<'b>,
362 impl<'a, 'b: 'a> DebugInner<'a, 'b> {
363 fn entry(&mut self, entry: &dyn fmt::Debug) {
364 self.result = self.result.and_then(|_| {
365 if self.is_pretty() {
366 if !self.has_fields {
367 self.fmt.write_str("\n")?;
370 let mut state = Default::default();
371 let mut writer = PadAdapter::wrap(&mut self.fmt, &mut slot, &mut state);
372 entry.fmt(&mut writer)?;
373 writer.write_str(",\n")
376 self.fmt.write_str(", ")?
382 self.has_fields = true;
385 fn is_pretty(&self) -> bool {
390 /// A struct to help with [`fmt::Debug`](trait.Debug.html) implementations.
392 /// This is useful when you wish to output a formatted set of items as a part
393 /// of your [`Debug::fmt`](trait.Debug.html#tymethod.fmt) implementation.
395 /// This can be constructed by the
396 /// [`Formatter::debug_set`](struct.Formatter.html#method.debug_set)
404 /// struct Foo(Vec<i32>);
406 /// impl fmt::Debug for Foo {
407 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
408 /// fmt.debug_set().entries(self.0.iter()).finish()
413 /// format!("{:?}", Foo(vec![10, 11])),
417 #[must_use = "must eventually call `finish()` on Debug builders"]
418 #[allow(missing_debug_implementations)]
419 #[stable(feature = "debug_builders", since = "1.2.0")]
420 pub struct DebugSet<'a, 'b: 'a> {
421 inner: DebugInner<'a, 'b>,
424 pub(super) fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugSet<'a, 'b> {
425 let result = fmt.write_str("{");
435 impl<'a, 'b: 'a> DebugSet<'a, 'b> {
436 /// Adds a new entry to the set output.
443 /// struct Foo(Vec<i32>, Vec<u32>);
445 /// impl fmt::Debug for Foo {
446 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
448 /// .entry(&self.0) // Adds the first "entry".
449 /// .entry(&self.1) // Adds the second "entry".
455 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
456 /// "{[10, 11], [12, 13]}",
459 #[stable(feature = "debug_builders", since = "1.2.0")]
460 pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut DebugSet<'a, 'b> {
461 self.inner.entry(entry);
465 /// Adds the contents of an iterator of entries to the set output.
472 /// struct Foo(Vec<i32>, Vec<u32>);
474 /// impl fmt::Debug for Foo {
475 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
477 /// .entries(self.0.iter()) // Adds the first "entry".
478 /// .entries(self.1.iter()) // Adds the second "entry".
484 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
485 /// "{10, 11, 12, 13}",
488 #[stable(feature = "debug_builders", since = "1.2.0")]
489 pub fn entries<D, I>(&mut self, entries: I) -> &mut DebugSet<'a, 'b>
491 I: IntoIterator<Item = D>
493 for entry in entries {
499 /// Finishes output and returns any error encountered.
506 /// struct Foo(Vec<i32>);
508 /// impl fmt::Debug for Foo {
509 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
511 /// .entries(self.0.iter())
512 /// .finish() // Ends the struct formatting.
517 /// format!("{:?}", Foo(vec![10, 11])),
521 #[stable(feature = "debug_builders", since = "1.2.0")]
522 pub fn finish(&mut self) -> fmt::Result {
523 self.inner.result.and_then(|_| self.inner.fmt.write_str("}"))
527 /// A struct to help with [`fmt::Debug`](trait.Debug.html) implementations.
529 /// This is useful when you wish to output a formatted list of items as a part
530 /// of your [`Debug::fmt`](trait.Debug.html#tymethod.fmt) implementation.
532 /// This can be constructed by the
533 /// [`Formatter::debug_list`](struct.Formatter.html#method.debug_list)
541 /// struct Foo(Vec<i32>);
543 /// impl fmt::Debug for Foo {
544 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
545 /// fmt.debug_list().entries(self.0.iter()).finish()
550 /// format!("{:?}", Foo(vec![10, 11])),
554 #[must_use = "must eventually call `finish()` on Debug builders"]
555 #[allow(missing_debug_implementations)]
556 #[stable(feature = "debug_builders", since = "1.2.0")]
557 pub struct DebugList<'a, 'b: 'a> {
558 inner: DebugInner<'a, 'b>,
561 pub(super) fn debug_list_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugList<'a, 'b> {
562 let result = fmt.write_str("[");
572 impl<'a, 'b: 'a> DebugList<'a, 'b> {
573 /// Adds a new entry to the list output.
580 /// struct Foo(Vec<i32>, Vec<u32>);
582 /// impl fmt::Debug for Foo {
583 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
585 /// .entry(&self.0) // We add the first "entry".
586 /// .entry(&self.1) // We add the second "entry".
592 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
593 /// "[[10, 11], [12, 13]]",
596 #[stable(feature = "debug_builders", since = "1.2.0")]
597 pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut DebugList<'a, 'b> {
598 self.inner.entry(entry);
602 /// Adds the contents of an iterator of entries to the list output.
609 /// struct Foo(Vec<i32>, Vec<u32>);
611 /// impl fmt::Debug for Foo {
612 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
614 /// .entries(self.0.iter())
615 /// .entries(self.1.iter())
621 /// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
622 /// "[10, 11, 12, 13]",
625 #[stable(feature = "debug_builders", since = "1.2.0")]
626 pub fn entries<D, I>(&mut self, entries: I) -> &mut DebugList<'a, 'b>
628 I: IntoIterator<Item = D>
630 for entry in entries {
636 /// Finishes output and returns any error encountered.
643 /// struct Foo(Vec<i32>);
645 /// impl fmt::Debug for Foo {
646 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
648 /// .entries(self.0.iter())
649 /// .finish() // Ends the struct formatting.
654 /// format!("{:?}", Foo(vec![10, 11])),
658 #[stable(feature = "debug_builders", since = "1.2.0")]
659 pub fn finish(&mut self) -> fmt::Result {
660 self.inner.result.and_then(|_| self.inner.fmt.write_str("]"))
664 /// A struct to help with [`fmt::Debug`](trait.Debug.html) implementations.
666 /// This is useful when you wish to output a formatted map as a part of your
667 /// [`Debug::fmt`](trait.Debug.html#tymethod.fmt) implementation.
669 /// This can be constructed by the
670 /// [`Formatter::debug_map`](struct.Formatter.html#method.debug_map)
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("{");
710 state: Default::default(),
714 impl<'a, 'b: 'a> DebugMap<'a, 'b> {
715 /// Adds a new entry to the map output.
722 /// struct Foo(Vec<(String, i32)>);
724 /// impl fmt::Debug for Foo {
725 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
727 /// .entry(&"whole", &self.0) // We add the "whole" entry.
733 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
734 /// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
737 #[stable(feature = "debug_builders", since = "1.2.0")]
738 pub fn entry(&mut self, key: &dyn fmt::Debug, value: &dyn fmt::Debug) -> &mut DebugMap<'a, 'b> {
739 self.key(key).value(value)
742 /// Adds the key part of a new entry to the map output.
744 /// This method, together with `value`, is an alternative to `entry` that
745 /// can be used when the complete entry isn't known upfront. Prefer the `entry`
746 /// method when it's possible to use.
750 /// `key` must be called before `value` and each call to `key` must be followed
751 /// by a corresponding call to `value`. Otherwise this method will panic.
756 /// # #![feature(debug_map_key_value)]
759 /// struct Foo(Vec<(String, i32)>);
761 /// impl fmt::Debug for Foo {
762 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
764 /// .key(&"whole").value(&self.0) // We add the "whole" entry.
770 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
771 /// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
774 #[unstable(feature = "debug_map_key_value",
775 reason = "recently added",
777 pub fn key(&mut self, key: &dyn fmt::Debug) -> &mut DebugMap<'a, 'b> {
778 assert!(!self.has_key, "attempted to begin a new map entry \
779 without completing the previous one");
781 self.result = self.result.and_then(|_| {
782 if self.is_pretty() {
783 if !self.has_fields {
784 self.fmt.write_str("\n")?;
787 self.state = Default::default();
788 let mut writer = PadAdapter::wrap(&mut self.fmt, &mut slot, &mut self.state);
789 key.fmt(&mut writer)?;
790 writer.write_str(": ")?;
793 self.fmt.write_str(", ")?
796 self.fmt.write_str(": ")?;
806 /// Adds the value part of a new entry to the map output.
808 /// This method, together with `key`, is an alternative to `entry` that
809 /// can be used when the complete entry isn't known upfront. Prefer the `entry`
810 /// method when it's possible to use.
814 /// `key` must be called before `value` and each call to `key` must be followed
815 /// by a corresponding call to `value`. Otherwise this method will panic.
820 /// # #![feature(debug_map_key_value)]
823 /// struct Foo(Vec<(String, i32)>);
825 /// impl fmt::Debug for Foo {
826 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
828 /// .key(&"whole").value(&self.0) // We add the "whole" entry.
834 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
835 /// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
838 #[unstable(feature = "debug_map_key_value",
839 reason = "recently added",
841 pub fn value(&mut self, value: &dyn fmt::Debug) -> &mut DebugMap<'a, 'b> {
842 assert!(self.has_key, "attempted to format a map value before its key");
844 self.result = self.result.and_then(|_| {
845 if self.is_pretty() {
847 let mut writer = PadAdapter::wrap(&mut self.fmt, &mut slot, &mut self.state);
848 value.fmt(&mut writer)?;
849 writer.write_str(",\n")?;
851 value.fmt(self.fmt)?;
854 self.has_key = false;
858 self.has_fields = true;
862 /// Adds the contents of an iterator of entries to the map output.
869 /// struct Foo(Vec<(String, i32)>);
871 /// impl fmt::Debug for Foo {
872 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
874 /// // We map our vec so each entries' first field will become
876 /// .entries(self.0.iter().map(|&(ref k, ref v)| (k, v)))
882 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
883 /// "{\"A\": 10, \"B\": 11}",
886 #[stable(feature = "debug_builders", since = "1.2.0")]
887 pub fn entries<K, V, I>(&mut self, entries: I) -> &mut DebugMap<'a, 'b>
890 I: IntoIterator<Item = (K, V)>
892 for (k, v) in entries {
898 /// Finishes output and returns any error encountered.
902 /// `key` must be called before `value` and each call to `key` must be followed
903 /// by a corresponding call to `value`. Otherwise this method will panic.
910 /// struct Foo(Vec<(String, i32)>);
912 /// impl fmt::Debug for Foo {
913 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
915 /// .entries(self.0.iter().map(|&(ref k, ref v)| (k, v)))
916 /// .finish() // Ends the struct formatting.
921 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
922 /// "{\"A\": 10, \"B\": 11}",
925 #[stable(feature = "debug_builders", since = "1.2.0")]
926 pub fn finish(&mut self) -> fmt::Result {
927 assert!(!self.has_key, "attempted to finish a map with a partial entry");
929 self.result.and_then(|_| self.fmt.write_str("}"))
932 fn is_pretty(&self) -> bool {