1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
#![allow(unused_imports)]
use crate::fmt::{self, Debug, Formatter};
struct PadAdapter<'buf, 'state> {
buf: &'buf mut (dyn fmt::Write + 'buf),
state: &'state mut PadAdapterState,
}
struct PadAdapterState {
on_newline: bool,
}
impl Default for PadAdapterState {
fn default() -> Self {
PadAdapterState { on_newline: true }
}
}
impl<'buf, 'state> PadAdapter<'buf, 'state> {
fn wrap<'slot, 'fmt: 'buf + 'slot>(
fmt: &'fmt mut fmt::Formatter<'_>,
slot: &'slot mut Option<Self>,
state: &'state mut PadAdapterState,
) -> fmt::Formatter<'slot> {
fmt.wrap_buf(move |buf| slot.insert(PadAdapter { buf, state }))
}
}
impl fmt::Write for PadAdapter<'_, '_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
for s in s.split_inclusive('\n') {
if self.state.on_newline {
self.buf.write_str(" ")?;
}
self.state.on_newline = s.ends_with('\n');
self.buf.write_str(s)?;
}
Ok(())
}
}
/// 一个有助于 [`fmt::Debug`](Debug) 实现的结构体。
///
/// 当您希望将格式化的结构体作为 [`Debug::fmt`] 实现的一部分输出时,此功能很有用。
///
///
/// 这可以通过 [`Formatter::debug_struct`] 方法创建。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo {
/// bar: i32,
/// baz: String,
/// }
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_struct("Foo")
/// .field("bar", &self.bar)
/// .field("baz", &self.baz)
/// .finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() }),
/// "Foo { bar: 10, baz: \"Hello World\" }",
/// );
/// ```
#[must_use = "must eventually call `finish()` on Debug builders"]
#[allow(missing_debug_implementations)]
#[stable(feature = "debug_builders", since = "1.2.0")]
pub struct DebugStruct<'a, 'b: 'a> {
fmt: &'a mut fmt::Formatter<'b>,
result: fmt::Result,
has_fields: bool,
}
pub(super) fn debug_struct_new<'a, 'b>(
fmt: &'a mut fmt::Formatter<'b>,
name: &str,
) -> DebugStruct<'a, 'b> {
let result = fmt.write_str(name);
DebugStruct { fmt, result, has_fields: false }
}
impl<'a, 'b: 'a> DebugStruct<'a, 'b> {
/// 在生成的结构体输出中添加一个新字段。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Bar {
/// bar: i32,
/// another: String,
/// }
///
/// impl fmt::Debug for Bar {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_struct("Bar")
/// .field("bar", &self.bar) // 我们添加 `bar` 字段。
/// .field("another", &self.another) // 我们添加 `another` 字段。
/// // 我们甚至添加了一个不存在的字段 (因为为什么不呢?)。
/// .field("nonexistent_field", &1)
/// .finish() // 我们很高兴去!
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Bar { bar: 10, another: "Hello World".to_string() }),
/// "Bar { bar: 10, another: \"Hello World\", nonexistent_field: 1 }",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn field(&mut self, name: &str, value: &dyn fmt::Debug) -> &mut Self {
self.result = self.result.and_then(|_| {
if self.is_pretty() {
if !self.has_fields {
self.fmt.write_str(" {\n")?;
}
let mut slot = None;
let mut state = Default::default();
let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
writer.write_str(name)?;
writer.write_str(": ")?;
value.fmt(&mut writer)?;
writer.write_str(",\n")
} else {
let prefix = if self.has_fields { ", " } else { " { " };
self.fmt.write_str(prefix)?;
self.fmt.write_str(name)?;
self.fmt.write_str(": ")?;
value.fmt(self.fmt)
}
});
self.has_fields = true;
self
}
/// 将结构体标记为非穷举,向 reader 指示在调试表示中未显示其他一些字段。
///
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Bar {
/// bar: i32,
/// hidden: f32,
/// }
///
/// impl fmt::Debug for Bar {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_struct("Bar")
/// .field("bar", &self.bar)
/// .finish_non_exhaustive() // 证明存在其他 field(s)。
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Bar { bar: 10, hidden: 1.0 }),
/// "Bar { bar: 10, .. }",
/// );
/// ```
#[stable(feature = "debug_non_exhaustive", since = "1.53.0")]
pub fn finish_non_exhaustive(&mut self) -> fmt::Result {
self.result = self.result.and_then(|_| {
if self.has_fields {
if self.is_pretty() {
let mut slot = None;
let mut state = Default::default();
let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
writer.write_str("..\n")?;
self.fmt.write_str("}")
} else {
self.fmt.write_str(", .. }")
}
} else {
self.fmt.write_str(" { .. }")
}
});
self.result
}
/// 完成输出并返回遇到的任何错误。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Bar {
/// bar: i32,
/// baz: String,
/// }
///
/// impl fmt::Debug for Bar {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_struct("Bar")
/// .field("bar", &self.bar)
/// .field("baz", &self.baz)
/// .finish() // 您需要调用它到 "finish"
/// // 结构体格式化。
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Bar { bar: 10, baz: "Hello World".to_string() }),
/// "Bar { bar: 10, baz: \"Hello World\" }",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn finish(&mut self) -> fmt::Result {
if self.has_fields {
self.result = self.result.and_then(|_| {
if self.is_pretty() { self.fmt.write_str("}") } else { self.fmt.write_str(" }") }
});
}
self.result
}
fn is_pretty(&self) -> bool {
self.fmt.alternate()
}
}
/// 一个有助于 [`fmt::Debug`](Debug) 实现的结构体。
///
/// 当您希望将格式化的元组作为 [`Debug::fmt`] 实现的一部分输出时,此功能很有用。
///
///
/// 这可以通过 [`Formatter::debug_tuple`] 方法创建。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(i32, String);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_tuple("Foo")
/// .field(&self.0)
/// .field(&self.1)
/// .finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(10, "Hello World".to_string())),
/// "Foo(10, \"Hello World\")",
/// );
/// ```
#[must_use = "must eventually call `finish()` on Debug builders"]
#[allow(missing_debug_implementations)]
#[stable(feature = "debug_builders", since = "1.2.0")]
pub struct DebugTuple<'a, 'b: 'a> {
fmt: &'a mut fmt::Formatter<'b>,
result: fmt::Result,
fields: usize,
empty_name: bool,
}
pub(super) fn debug_tuple_new<'a, 'b>(
fmt: &'a mut fmt::Formatter<'b>,
name: &str,
) -> DebugTuple<'a, 'b> {
let result = fmt.write_str(name);
DebugTuple { fmt, result, fields: 0, empty_name: name.is_empty() }
}
impl<'a, 'b: 'a> DebugTuple<'a, 'b> {
/// 在生成的元组结构体输出中添加一个新字段。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(i32, String);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_tuple("Foo")
/// .field(&self.0) // 我们添加第一个字段。
/// .field(&self.1) // 我们添加第二个字段。
/// .finish() // 我们很高兴去!
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(10, "Hello World".to_string())),
/// "Foo(10, \"Hello World\")",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn field(&mut self, value: &dyn fmt::Debug) -> &mut Self {
self.result = self.result.and_then(|_| {
if self.is_pretty() {
if self.fields == 0 {
self.fmt.write_str("(\n")?;
}
let mut slot = None;
let mut state = Default::default();
let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
value.fmt(&mut writer)?;
writer.write_str(",\n")
} else {
let prefix = if self.fields == 0 { "(" } else { ", " };
self.fmt.write_str(prefix)?;
value.fmt(self.fmt)
}
});
self.fields += 1;
self
}
/// 完成输出并返回遇到的任何错误。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(i32, String);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_tuple("Foo")
/// .field(&self.0)
/// .field(&self.1)
/// .finish() // 您需要调用它到 "finish"
/// // 元组格式。
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(10, "Hello World".to_string())),
/// "Foo(10, \"Hello World\")",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn finish(&mut self) -> fmt::Result {
if self.fields > 0 {
self.result = self.result.and_then(|_| {
if self.fields == 1 && self.empty_name && !self.is_pretty() {
self.fmt.write_str(",")?;
}
self.fmt.write_str(")")
});
}
self.result
}
fn is_pretty(&self) -> bool {
self.fmt.alternate()
}
}
struct DebugInner<'a, 'b: 'a> {
fmt: &'a mut fmt::Formatter<'b>,
result: fmt::Result,
has_fields: bool,
}
impl<'a, 'b: 'a> DebugInner<'a, 'b> {
fn entry(&mut self, entry: &dyn fmt::Debug) {
self.result = self.result.and_then(|_| {
if self.is_pretty() {
if !self.has_fields {
self.fmt.write_str("\n")?;
}
let mut slot = None;
let mut state = Default::default();
let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut state);
entry.fmt(&mut writer)?;
writer.write_str(",\n")
} else {
if self.has_fields {
self.fmt.write_str(", ")?
}
entry.fmt(self.fmt)
}
});
self.has_fields = true;
}
fn is_pretty(&self) -> bool {
self.fmt.alternate()
}
}
/// 一个有助于 [`fmt::Debug`](Debug) 实现的结构体。
///
/// 当您希望输出格式化的项集作为 [`Debug::fmt`] 实现的一部分时,这很有用。
///
///
/// 这可以通过 [`Formatter::debug_set`] 方法创建。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<i32>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_set().entries(self.0.iter()).finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![10, 11])),
/// "{10, 11}",
/// );
/// ```
#[must_use = "must eventually call `finish()` on Debug builders"]
#[allow(missing_debug_implementations)]
#[stable(feature = "debug_builders", since = "1.2.0")]
pub struct DebugSet<'a, 'b: 'a> {
inner: DebugInner<'a, 'b>,
}
pub(super) fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugSet<'a, 'b> {
let result = fmt.write_str("{");
DebugSet { inner: DebugInner { fmt, result, has_fields: false } }
}
impl<'a, 'b: 'a> DebugSet<'a, 'b> {
/// 将新条目添加到设置的输出中。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<i32>, Vec<u32>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_set()
/// .entry(&self.0) // 添加第一个 "entry"。
/// .entry(&self.1) // 添加第二个 "entry"。
/// .finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
/// "{[10, 11], [12, 13]}",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut Self {
self.inner.entry(entry);
self
}
/// 将条目迭代器的内容添加到设置的输出中。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<i32>, Vec<u32>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_set()
/// .entries(self.0.iter()) // 添加第一个 "entry"。
/// .entries(self.1.iter()) // 添加第二个 "entry"。
/// .finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
/// "{10, 11, 12, 13}",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn entries<D, I>(&mut self, entries: I) -> &mut Self
where
D: fmt::Debug,
I: IntoIterator<Item = D>,
{
for entry in entries {
self.entry(&entry);
}
self
}
/// 完成输出并返回遇到的任何错误。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<i32>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_set()
/// .entries(self.0.iter())
/// .finish() // 结束结构体格式化。
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![10, 11])),
/// "{10, 11}",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn finish(&mut self) -> fmt::Result {
self.inner.result.and_then(|_| self.inner.fmt.write_str("}"))
}
}
/// 一个有助于 [`fmt::Debug`](Debug) 实现的结构体。
///
/// 当您希望输出格式化的项列表作为 [`Debug::fmt`] 实现的一部分时,此功能很有用。
///
///
/// 这可以通过 [`Formatter::debug_list`] 方法创建。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<i32>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_list().entries(self.0.iter()).finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![10, 11])),
/// "[10, 11]",
/// );
/// ```
#[must_use = "must eventually call `finish()` on Debug builders"]
#[allow(missing_debug_implementations)]
#[stable(feature = "debug_builders", since = "1.2.0")]
pub struct DebugList<'a, 'b: 'a> {
inner: DebugInner<'a, 'b>,
}
pub(super) fn debug_list_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugList<'a, 'b> {
let result = fmt.write_str("[");
DebugList { inner: DebugInner { fmt, result, has_fields: false } }
}
impl<'a, 'b: 'a> DebugList<'a, 'b> {
/// 将新条目添加到列表输出中。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<i32>, Vec<u32>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_list()
/// .entry(&self.0) // 我们添加第一个 "entry"。
/// .entry(&self.1) // 我们添加第二个 "entry"。
/// .finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
/// "[[10, 11], [12, 13]]",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn entry(&mut self, entry: &dyn fmt::Debug) -> &mut Self {
self.inner.entry(entry);
self
}
/// 将条目迭代器的内容添加到列表输出中。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<i32>, Vec<u32>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_list()
/// .entries(self.0.iter())
/// .entries(self.1.iter())
/// .finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![10, 11], vec![12, 13])),
/// "[10, 11, 12, 13]",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn entries<D, I>(&mut self, entries: I) -> &mut Self
where
D: fmt::Debug,
I: IntoIterator<Item = D>,
{
for entry in entries {
self.entry(&entry);
}
self
}
/// 完成输出并返回遇到的任何错误。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<i32>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_list()
/// .entries(self.0.iter())
/// .finish() // 结束结构体格式化。
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![10, 11])),
/// "[10, 11]",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn finish(&mut self) -> fmt::Result {
self.inner.result.and_then(|_| self.inner.fmt.write_str("]"))
}
}
/// 一个有助于 [`fmt::Debug`](Debug) 实现的结构体。
///
/// 当您希望输出格式化的 map 作为 [`Debug::fmt`] 实现的一部分时,此功能很有用。
///
///
/// 这可以通过 [`Formatter::debug_map`] 方法创建。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<(String, i32)>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
/// "{\"A\": 10, \"B\": 11}",
/// );
/// ```
#[must_use = "must eventually call `finish()` on Debug builders"]
#[allow(missing_debug_implementations)]
#[stable(feature = "debug_builders", since = "1.2.0")]
pub struct DebugMap<'a, 'b: 'a> {
fmt: &'a mut fmt::Formatter<'b>,
result: fmt::Result,
has_fields: bool,
has_key: bool,
// 在键和值之间跟踪换行状态
state: PadAdapterState,
}
pub(super) fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugMap<'a, 'b> {
let result = fmt.write_str("{");
DebugMap { fmt, result, has_fields: false, has_key: false, state: Default::default() }
}
impl<'a, 'b: 'a> DebugMap<'a, 'b> {
/// 在 map 输出中添加一个新条目。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<(String, i32)>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_map()
/// .entry(&"whole", &self.0) // 我们添加 "whole" 条目。
/// .finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
/// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn entry(&mut self, key: &dyn fmt::Debug, value: &dyn fmt::Debug) -> &mut Self {
self.key(key).value(value)
}
/// 将新条目的关键部分添加到 map 输出中。
///
/// 该方法与 `value` 一起,是 `entry` 的替代方法,可以在事先不知道完整条目的情况下使用。
///
/// 尽可能使用 `entry` 方法。
///
/// # Panics
///
/// `key` 必须在 `value` 之前调用,每个调用到 `key` 必须跟在对应的调用到 `value` 之后。
/// 否则,此方法将为 panic。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<(String, i32)>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_map()
/// .key(&"whole").value(&self.0) // 我们添加 "whole" 条目。
/// .finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
/// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
/// );
/// ```
#[stable(feature = "debug_map_key_value", since = "1.42.0")]
pub fn key(&mut self, key: &dyn fmt::Debug) -> &mut Self {
self.result = self.result.and_then(|_| {
assert!(
!self.has_key,
"attempted to begin a new map entry \
without completing the previous one"
);
if self.is_pretty() {
if !self.has_fields {
self.fmt.write_str("\n")?;
}
let mut slot = None;
self.state = Default::default();
let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut self.state);
key.fmt(&mut writer)?;
writer.write_str(": ")?;
} else {
if self.has_fields {
self.fmt.write_str(", ")?
}
key.fmt(self.fmt)?;
self.fmt.write_str(": ")?;
}
self.has_key = true;
Ok(())
});
self
}
/// 将新条目的值部分添加到 map 输出中。
///
/// 该方法与 `key` 一起,是 `entry` 的替代方法,可以在事先不知道完整条目的情况下使用。
///
/// 尽可能使用 `entry` 方法。
///
/// # Panics
///
/// `key` 必须在 `value` 之前调用,每个调用到 `key` 必须跟在对应的调用到 `value` 之后。
/// 否则,此方法将为 panic。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<(String, i32)>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_map()
/// .key(&"whole").value(&self.0) // 我们添加 "whole" 条目。
/// .finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
/// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
/// );
/// ```
#[stable(feature = "debug_map_key_value", since = "1.42.0")]
pub fn value(&mut self, value: &dyn fmt::Debug) -> &mut Self {
self.result = self.result.and_then(|_| {
assert!(self.has_key, "attempted to format a map value before its key");
if self.is_pretty() {
let mut slot = None;
let mut writer = PadAdapter::wrap(self.fmt, &mut slot, &mut self.state);
value.fmt(&mut writer)?;
writer.write_str(",\n")?;
} else {
value.fmt(self.fmt)?;
}
self.has_key = false;
Ok(())
});
self.has_fields = true;
self
}
/// 将条目迭代器的内容添加到 map 输出中。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<(String, i32)>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_map()
/// // 我们将 vec 设为 map,因此每个条目的第一个字段将成为 "key"。
/////
/// .entries(self.0.iter().map(|&(ref k, ref v)| (k, v)))
/// .finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
/// "{\"A\": 10, \"B\": 11}",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn entries<K, V, I>(&mut self, entries: I) -> &mut Self
where
K: fmt::Debug,
V: fmt::Debug,
I: IntoIterator<Item = (K, V)>,
{
for (k, v) in entries {
self.entry(&k, &v);
}
self
}
/// 完成输出并返回遇到的任何错误。
///
/// # Panics
///
/// `key` 必须在 `value` 之前调用,每个调用到 `key` 必须跟在对应的调用到 `value` 之后。
/// 否则,此方法将为 panic。
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<(String, i32)>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_map()
/// .entries(self.0.iter().map(|&(ref k, ref v)| (k, v)))
/// .finish() // 结束结构体格式化。
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
/// "{\"A\": 10, \"B\": 11}",
/// );
/// ```
#[stable(feature = "debug_builders", since = "1.2.0")]
pub fn finish(&mut self) -> fmt::Result {
self.result.and_then(|_| {
assert!(!self.has_key, "attempted to finish a map with a partial entry");
self.fmt.write_str("}")
})
}
fn is_pretty(&self) -> bool {
self.fmt.alternate()
}
}