1 //! Utilities for formatting and printing strings.
2
3 #![stable(feature = "rust1", since = "1.0.0")]
4
5 use crate::cell::{Cell, Ref, RefCell, RefMut, SyncUnsafeCell, UnsafeCell};
6 use crate::char::EscapeDebugExtArgs;
7 use crate::iter;
8 use crate::marker::PhantomData;
9 use crate::mem;
10 use crate::num::fmt as numfmt;
11 use crate::ops::Deref;
12 use crate::result;
13 use crate::str;
14
15 mod builders;
16 #[cfg(not(no_fp_fmt_parse))]
17 mod float;
18 #[cfg(no_fp_fmt_parse)]
19 mod nofloat;
20 mod num;
21 mod rt;
22
23 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
24 #[cfg_attr(not(test), rustc_diagnostic_item = "Alignment")]
25 /// Possible alignments returned by `Formatter::align`
26 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
27 pub enum Alignment {
28 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
29 /// Indication that contents should be left-aligned.
30 Left,
31 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
32 /// Indication that contents should be right-aligned.
33 Right,
34 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
35 /// Indication that contents should be center-aligned.
36 Center,
37 }
38
39 #[stable(feature = "debug_builders", since = "1.2.0")]
40 pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
41
42 /// The type returned by formatter methods.
43 ///
44 /// # Examples
45 ///
46 /// ```
47 /// use std::fmt;
48 ///
49 /// #[derive(Debug)]
50 /// struct Triangle {
51 /// a: f32,
52 /// b: f32,
53 /// c: f32
54 /// }
55 ///
56 /// impl fmt::Display for Triangle {
57 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 /// write!(f, "({}, {}, {})", self.a, self.b, self.c)
59 /// }
60 /// }
61 ///
62 /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
63 ///
64 /// assert_eq!(format!("{pythagorean_triple}"), "(3, 4, 5)");
65 /// ```
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub type Result = result::Result<(), Error>;
68
69 /// The error type which is returned from formatting a message into a stream.
70 ///
71 /// This type does not support transmission of an error other than that an error
72 /// occurred. Any extra information must be arranged to be transmitted through
73 /// some other means.
74 ///
75 /// An important thing to remember is that the type `fmt::Error` should not be
76 /// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
77 /// have in scope.
78 ///
79 /// [`std::io::Error`]: ../../std/io/struct.Error.html
80 /// [`std::error::Error`]: ../../std/error/trait.Error.html
81 ///
82 /// # Examples
83 ///
84 /// ```rust
85 /// use std::fmt::{self, write};
86 ///
87 /// let mut output = String::new();
88 /// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
89 /// panic!("An error occurred");
90 /// }
91 /// ```
92 #[stable(feature = "rust1", since = "1.0.0")]
93 #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
94 pub struct Error;
95
96 /// A trait for writing or formatting into Unicode-accepting buffers or streams.
97 ///
98 /// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
99 /// want to accept Unicode and you don't need flushing, you should implement this trait;
100 /// otherwise you should implement [`std::io::Write`].
101 ///
102 /// [`std::io::Write`]: ../../std/io/trait.Write.html
103 /// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
104 #[stable(feature = "rust1", since = "1.0.0")]
105 pub trait Write {
106 /// Writes a string slice into this writer, returning whether the write
107 /// succeeded.
108 ///
109 /// This method can only succeed if the entire string slice was successfully
110 /// written, and this method will not return until all data has been
111 /// written or an error occurs.
112 ///
113 /// # Errors
114 ///
115 /// This function will return an instance of [`Error`] on error.
116 ///
117 /// The purpose of std::fmt::Error is to abort the formatting operation when the underlying
118 /// destination encounters some error preventing it from accepting more text; it should
119 /// generally be propagated rather than handled, at least when implementing formatting traits.
120 ///
121 /// # Examples
122 ///
123 /// ```
124 /// use std::fmt::{Error, Write};
125 ///
126 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
127 /// f.write_str(s)
128 /// }
129 ///
130 /// let mut buf = String::new();
131 /// writer(&mut buf, "hola").unwrap();
132 /// assert_eq!(&buf, "hola");
133 /// ```
134 #[stable(feature = "rust1", since = "1.0.0")]
write_str(&mut self, s: &str) -> Result135 fn write_str(&mut self, s: &str) -> Result;
136
137 /// Writes a [`char`] into this writer, returning whether the write succeeded.
138 ///
139 /// A single [`char`] may be encoded as more than one byte.
140 /// This method can only succeed if the entire byte sequence was successfully
141 /// written, and this method will not return until all data has been
142 /// written or an error occurs.
143 ///
144 /// # Errors
145 ///
146 /// This function will return an instance of [`Error`] on error.
147 ///
148 /// # Examples
149 ///
150 /// ```
151 /// use std::fmt::{Error, Write};
152 ///
153 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
154 /// f.write_char(c)
155 /// }
156 ///
157 /// let mut buf = String::new();
158 /// writer(&mut buf, 'a').unwrap();
159 /// writer(&mut buf, 'b').unwrap();
160 /// assert_eq!(&buf, "ab");
161 /// ```
162 #[stable(feature = "fmt_write_char", since = "1.1.0")]
write_char(&mut self, c: char) -> Result163 fn write_char(&mut self, c: char) -> Result {
164 self.write_str(c.encode_utf8(&mut [0; 4]))
165 }
166
167 /// Glue for usage of the [`write!`] macro with implementors of this trait.
168 ///
169 /// This method should generally not be invoked manually, but rather through
170 /// the [`write!`] macro itself.
171 ///
172 /// # Errors
173 ///
174 /// This function will return an instance of [`Error`] on error. Please see
175 /// [write_str](Write::write_str) for details.
176 ///
177 /// # Examples
178 ///
179 /// ```
180 /// use std::fmt::{Error, Write};
181 ///
182 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
183 /// f.write_fmt(format_args!("{s}"))
184 /// }
185 ///
186 /// let mut buf = String::new();
187 /// writer(&mut buf, "world").unwrap();
188 /// assert_eq!(&buf, "world");
189 /// ```
190 #[stable(feature = "rust1", since = "1.0.0")]
write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result191 fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result {
192 write(&mut self, args)
193 }
194 }
195
196 #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
197 impl<W: Write + ?Sized> Write for &mut W {
write_str(&mut self, s: &str) -> Result198 fn write_str(&mut self, s: &str) -> Result {
199 (**self).write_str(s)
200 }
201
write_char(&mut self, c: char) -> Result202 fn write_char(&mut self, c: char) -> Result {
203 (**self).write_char(c)
204 }
205
write_fmt(&mut self, args: Arguments<'_>) -> Result206 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
207 (**self).write_fmt(args)
208 }
209 }
210
211 /// Configuration for formatting.
212 ///
213 /// A `Formatter` represents various options related to formatting. Users do not
214 /// construct `Formatter`s directly; a mutable reference to one is passed to
215 /// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
216 ///
217 /// To interact with a `Formatter`, you'll call various methods to change the
218 /// various options related to formatting. For examples, please see the
219 /// documentation of the methods defined on `Formatter` below.
220 #[allow(missing_debug_implementations)]
221 #[stable(feature = "rust1", since = "1.0.0")]
222 pub struct Formatter<'a> {
223 flags: u32,
224 fill: char,
225 align: rt::Alignment,
226 width: Option<usize>,
227 precision: Option<usize>,
228
229 buf: &'a mut (dyn Write + 'a),
230 }
231
232 impl<'a> Formatter<'a> {
233 /// Creates a new formatter with default settings.
234 ///
235 /// This can be used as a micro-optimization in cases where a full `Arguments`
236 /// structure (as created by `format_args!`) is not necessary; `Arguments`
237 /// is a little more expensive to use in simple formatting scenarios.
238 ///
239 /// Currently not intended for use outside of the standard library.
240 #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
241 #[doc(hidden)]
new(buf: &'a mut (dyn Write + 'a)) -> Formatter<'a>242 pub fn new(buf: &'a mut (dyn Write + 'a)) -> Formatter<'a> {
243 Formatter {
244 flags: 0,
245 fill: ' ',
246 align: rt::Alignment::Unknown,
247 width: None,
248 precision: None,
249 buf,
250 }
251 }
252 }
253
254 /// This structure represents a safely precompiled version of a format string
255 /// and its arguments. This cannot be generated at runtime because it cannot
256 /// safely be done, so no constructors are given and the fields are private
257 /// to prevent modification.
258 ///
259 /// The [`format_args!`] macro will safely create an instance of this structure.
260 /// The macro validates the format string at compile-time so usage of the
261 /// [`write()`] and [`format()`] functions can be safely performed.
262 ///
263 /// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
264 /// and `Display` contexts as seen below. The example also shows that `Debug`
265 /// and `Display` format to the same thing: the interpolated format string
266 /// in `format_args!`.
267 ///
268 /// ```rust
269 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
270 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
271 /// assert_eq!("1 foo 2", display);
272 /// assert_eq!(display, debug);
273 /// ```
274 ///
275 /// [`format()`]: ../../std/fmt/fn.format.html
276 #[lang = "format_arguments"]
277 #[stable(feature = "rust1", since = "1.0.0")]
278 #[derive(Copy, Clone)]
279 pub struct Arguments<'a> {
280 // Format string pieces to print.
281 pieces: &'a [&'static str],
282
283 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
284 fmt: Option<&'a [rt::Placeholder]>,
285
286 // Dynamic arguments for interpolation, to be interleaved with string
287 // pieces. (Every argument is preceded by a string piece.)
288 args: &'a [rt::Argument<'a>],
289 }
290
291 /// Used by the format_args!() macro to create a fmt::Arguments object.
292 #[doc(hidden)]
293 #[unstable(feature = "fmt_internals", issue = "none")]
294 impl<'a> Arguments<'a> {
295 #[inline]
296 #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
new_const(pieces: &'a [&'static str]) -> Self297 pub const fn new_const(pieces: &'a [&'static str]) -> Self {
298 if pieces.len() > 1 {
299 panic!("invalid args");
300 }
301 Arguments { pieces, fmt: None, args: &[] }
302 }
303
304 /// When using the format_args!() macro, this function is used to generate the
305 /// Arguments structure.
306 #[inline]
new_v1(pieces: &'a [&'static str], args: &'a [rt::Argument<'a>]) -> Arguments<'a>307 pub fn new_v1(pieces: &'a [&'static str], args: &'a [rt::Argument<'a>]) -> Arguments<'a> {
308 if pieces.len() < args.len() || pieces.len() > args.len() + 1 {
309 panic!("invalid args");
310 }
311 Arguments { pieces, fmt: None, args }
312 }
313
314 /// This function is used to specify nonstandard formatting parameters.
315 ///
316 /// An `rt::UnsafeArg` is required because the following invariants must be held
317 /// in order for this function to be safe:
318 /// 1. The `pieces` slice must be at least as long as `fmt`.
319 /// 2. Every `rt::Placeholder::position` value within `fmt` must be a valid index of `args`.
320 /// 3. Every `rt::Count::Param` within `fmt` must contain a valid index of `args`.
321 #[inline]
new_v1_formatted( pieces: &'a [&'static str], args: &'a [rt::Argument<'a>], fmt: &'a [rt::Placeholder], _unsafe_arg: rt::UnsafeArg, ) -> Arguments<'a>322 pub fn new_v1_formatted(
323 pieces: &'a [&'static str],
324 args: &'a [rt::Argument<'a>],
325 fmt: &'a [rt::Placeholder],
326 _unsafe_arg: rt::UnsafeArg,
327 ) -> Arguments<'a> {
328 Arguments { pieces, fmt: Some(fmt), args }
329 }
330
331 /// Estimates the length of the formatted text.
332 ///
333 /// This is intended to be used for setting initial `String` capacity
334 /// when using `format!`. Note: this is neither the lower nor upper bound.
335 #[inline]
estimated_capacity(&self) -> usize336 pub fn estimated_capacity(&self) -> usize {
337 let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
338
339 if self.args.is_empty() {
340 pieces_length
341 } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
342 // If the format string starts with an argument,
343 // don't preallocate anything, unless length
344 // of pieces is significant.
345 0
346 } else {
347 // There are some arguments, so any additional push
348 // will reallocate the string. To avoid that,
349 // we're "pre-doubling" the capacity here.
350 pieces_length.checked_mul(2).unwrap_or(0)
351 }
352 }
353 }
354
355 impl<'a> Arguments<'a> {
356 /// Get the formatted string, if it has no arguments to be formatted at runtime.
357 ///
358 /// This can be used to avoid allocations in some cases.
359 ///
360 /// # Guarantees
361 ///
362 /// For `format_args!("just a literal")`, this function is guaranteed to
363 /// return `Some("just a literal")`.
364 ///
365 /// For most cases with placeholders, this function will return `None`.
366 ///
367 /// However, the compiler may perform optimizations that can cause this
368 /// function to return `Some(_)` even if the format string contains
369 /// placeholders. For example, `format_args!("Hello, {}!", "world")` may be
370 /// optimized to `format_args!("Hello, world!")`, such that `as_str()`
371 /// returns `Some("Hello, world!")`.
372 ///
373 /// The behavior for anything but the trivial case (without placeholders)
374 /// is not guaranteed, and should not be relied upon for anything other
375 /// than optimization.
376 ///
377 /// # Examples
378 ///
379 /// ```rust
380 /// use std::fmt::Arguments;
381 ///
382 /// fn write_str(_: &str) { /* ... */ }
383 ///
384 /// fn write_fmt(args: &Arguments<'_>) {
385 /// if let Some(s) = args.as_str() {
386 /// write_str(s)
387 /// } else {
388 /// write_str(&args.to_string());
389 /// }
390 /// }
391 /// ```
392 ///
393 /// ```rust
394 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
395 /// assert_eq!(format_args!("").as_str(), Some(""));
396 /// assert_eq!(format_args!("{:?}", std::env::current_dir()).as_str(), None);
397 /// ```
398 #[stable(feature = "fmt_as_str", since = "1.52.0")]
399 #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "103900")]
400 #[must_use]
401 #[inline]
as_str(&self) -> Option<&'static str>402 pub const fn as_str(&self) -> Option<&'static str> {
403 match (self.pieces, self.args) {
404 ([], []) => Some(""),
405 ([s], []) => Some(s),
406 _ => None,
407 }
408 }
409 }
410
411 #[stable(feature = "rust1", since = "1.0.0")]
412 impl Debug for Arguments<'_> {
fmt(&self, fmt: &mut Formatter<'_>) -> Result413 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
414 Display::fmt(self, fmt)
415 }
416 }
417
418 #[stable(feature = "rust1", since = "1.0.0")]
419 impl Display for Arguments<'_> {
fmt(&self, fmt: &mut Formatter<'_>) -> Result420 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
421 write(fmt.buf, *self)
422 }
423 }
424
425 /// `?` formatting.
426 ///
427 /// `Debug` should format the output in a programmer-facing, debugging context.
428 ///
429 /// Generally speaking, you should just `derive` a `Debug` implementation.
430 ///
431 /// When used with the alternate format specifier `#?`, the output is pretty-printed.
432 ///
433 /// For more information on formatters, see [the module-level documentation][module].
434 ///
435 /// [module]: ../../std/fmt/index.html
436 ///
437 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
438 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
439 /// comma-separated list of each field's name and `Debug` value, then `}`. For
440 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
441 /// `Debug` values of the fields, then `)`.
442 ///
443 /// # Stability
444 ///
445 /// Derived `Debug` formats are not stable, and so may change with future Rust
446 /// versions. Additionally, `Debug` implementations of types provided by the
447 /// standard library (`std`, `core`, `alloc`, etc.) are not stable, and
448 /// may also change with future Rust versions.
449 ///
450 /// # Examples
451 ///
452 /// Deriving an implementation:
453 ///
454 /// ```
455 /// #[derive(Debug)]
456 /// struct Point {
457 /// x: i32,
458 /// y: i32,
459 /// }
460 ///
461 /// let origin = Point { x: 0, y: 0 };
462 ///
463 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
464 /// ```
465 ///
466 /// Manually implementing:
467 ///
468 /// ```
469 /// use std::fmt;
470 ///
471 /// struct Point {
472 /// x: i32,
473 /// y: i32,
474 /// }
475 ///
476 /// impl fmt::Debug for Point {
477 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478 /// f.debug_struct("Point")
479 /// .field("x", &self.x)
480 /// .field("y", &self.y)
481 /// .finish()
482 /// }
483 /// }
484 ///
485 /// let origin = Point { x: 0, y: 0 };
486 ///
487 /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
488 /// ```
489 ///
490 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
491 /// implementations, such as [`debug_struct`].
492 ///
493 /// [`debug_struct`]: Formatter::debug_struct
494 ///
495 /// Types that do not wish to use the standard suite of debug representations
496 /// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
497 /// `debug_list`, `debug_set`, `debug_map`) can do something totally custom by
498 /// manually writing an arbitrary representation to the `Formatter`.
499 ///
500 /// ```
501 /// # use std::fmt;
502 /// # struct Point {
503 /// # x: i32,
504 /// # y: i32,
505 /// # }
506 /// #
507 /// impl fmt::Debug for Point {
508 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509 /// write!(f, "Point [{} {}]", self.x, self.y)
510 /// }
511 /// }
512 /// ```
513 ///
514 /// `Debug` implementations using either `derive` or the debug builder API
515 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
516 ///
517 /// Pretty-printing with `#?`:
518 ///
519 /// ```
520 /// #[derive(Debug)]
521 /// struct Point {
522 /// x: i32,
523 /// y: i32,
524 /// }
525 ///
526 /// let origin = Point { x: 0, y: 0 };
527 ///
528 /// assert_eq!(format!("The origin is: {origin:#?}"),
529 /// "The origin is: Point {
530 /// x: 0,
531 /// y: 0,
532 /// }");
533 /// ```
534
535 #[stable(feature = "rust1", since = "1.0.0")]
536 #[rustc_on_unimplemented(
537 on(
538 crate_local,
539 label = "`{Self}` cannot be formatted using `{{:?}}`",
540 note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
541 ),
542 message = "`{Self}` doesn't implement `{Debug}`",
543 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
544 )]
545 #[doc(alias = "{:?}")]
546 #[rustc_diagnostic_item = "Debug"]
547 #[rustc_trivial_field_reads]
548 pub trait Debug {
549 /// Formats the value using the given formatter.
550 ///
551 /// # Examples
552 ///
553 /// ```
554 /// use std::fmt;
555 ///
556 /// struct Position {
557 /// longitude: f32,
558 /// latitude: f32,
559 /// }
560 ///
561 /// impl fmt::Debug for Position {
562 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563 /// f.debug_tuple("")
564 /// .field(&self.longitude)
565 /// .field(&self.latitude)
566 /// .finish()
567 /// }
568 /// }
569 ///
570 /// let position = Position { longitude: 1.987, latitude: 2.983 };
571 /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
572 ///
573 /// assert_eq!(format!("{position:#?}"), "(
574 /// 1.987,
575 /// 2.983,
576 /// )");
577 /// ```
578 #[stable(feature = "rust1", since = "1.0.0")]
fmt(&self, f: &mut Formatter<'_>) -> Result579 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
580 }
581
582 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
583 pub(crate) mod macros {
584 /// Derive macro generating an impl of the trait `Debug`.
585 #[rustc_builtin_macro]
586 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
587 #[allow_internal_unstable(core_intrinsics, fmt_helpers_for_derive)]
588 pub macro Debug($item:item) {
589 /* compiler built-in */
590 }
591 }
592 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
593 #[doc(inline)]
594 pub use macros::Debug;
595
596 /// Format trait for an empty format, `{}`.
597 ///
598 /// Implementing this trait for a type will automatically implement the
599 /// [`ToString`][tostring] trait for the type, allowing the usage
600 /// of the [`.to_string()`][tostring_function] method. Prefer implementing
601 /// the `Display` trait for a type, rather than [`ToString`][tostring].
602 ///
603 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
604 /// output, and so cannot be derived.
605 ///
606 /// For more information on formatters, see [the module-level documentation][module].
607 ///
608 /// [module]: ../../std/fmt/index.html
609 /// [tostring]: ../../std/string/trait.ToString.html
610 /// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
611 ///
612 /// # Examples
613 ///
614 /// Implementing `Display` on a type:
615 ///
616 /// ```
617 /// use std::fmt;
618 ///
619 /// struct Point {
620 /// x: i32,
621 /// y: i32,
622 /// }
623 ///
624 /// impl fmt::Display for Point {
625 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
626 /// write!(f, "({}, {})", self.x, self.y)
627 /// }
628 /// }
629 ///
630 /// let origin = Point { x: 0, y: 0 };
631 ///
632 /// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
633 /// ```
634 #[rustc_on_unimplemented(
635 on(
636 any(_Self = "std::path::Path", _Self = "std::path::PathBuf"),
637 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
638 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
639 as they may contain non-Unicode data"
640 ),
641 message = "`{Self}` doesn't implement `{Display}`",
642 label = "`{Self}` cannot be formatted with the default formatter",
643 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
644 )]
645 #[doc(alias = "{}")]
646 #[rustc_diagnostic_item = "Display"]
647 #[stable(feature = "rust1", since = "1.0.0")]
648 pub trait Display {
649 /// Formats the value using the given formatter.
650 ///
651 /// # Examples
652 ///
653 /// ```
654 /// use std::fmt;
655 ///
656 /// struct Position {
657 /// longitude: f32,
658 /// latitude: f32,
659 /// }
660 ///
661 /// impl fmt::Display for Position {
662 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
663 /// write!(f, "({}, {})", self.longitude, self.latitude)
664 /// }
665 /// }
666 ///
667 /// assert_eq!("(1.987, 2.983)",
668 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
669 /// ```
670 #[stable(feature = "rust1", since = "1.0.0")]
fmt(&self, f: &mut Formatter<'_>) -> Result671 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
672 }
673
674 /// `o` formatting.
675 ///
676 /// The `Octal` trait should format its output as a number in base-8.
677 ///
678 /// For primitive signed integers (`i8` to `i128`, and `isize`),
679 /// negative values are formatted as the two’s complement representation.
680 ///
681 /// The alternate flag, `#`, adds a `0o` in front of the output.
682 ///
683 /// For more information on formatters, see [the module-level documentation][module].
684 ///
685 /// [module]: ../../std/fmt/index.html
686 ///
687 /// # Examples
688 ///
689 /// Basic usage with `i32`:
690 ///
691 /// ```
692 /// let x = 42; // 42 is '52' in octal
693 ///
694 /// assert_eq!(format!("{x:o}"), "52");
695 /// assert_eq!(format!("{x:#o}"), "0o52");
696 ///
697 /// assert_eq!(format!("{:o}", -16), "37777777760");
698 /// ```
699 ///
700 /// Implementing `Octal` on a type:
701 ///
702 /// ```
703 /// use std::fmt;
704 ///
705 /// struct Length(i32);
706 ///
707 /// impl fmt::Octal for Length {
708 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
709 /// let val = self.0;
710 ///
711 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
712 /// }
713 /// }
714 ///
715 /// let l = Length(9);
716 ///
717 /// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
718 ///
719 /// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
720 /// ```
721 #[stable(feature = "rust1", since = "1.0.0")]
722 pub trait Octal {
723 /// Formats the value using the given formatter.
724 #[stable(feature = "rust1", since = "1.0.0")]
fmt(&self, f: &mut Formatter<'_>) -> Result725 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
726 }
727
728 /// `b` formatting.
729 ///
730 /// The `Binary` trait should format its output as a number in binary.
731 ///
732 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
733 /// negative values are formatted as the two’s complement representation.
734 ///
735 /// The alternate flag, `#`, adds a `0b` in front of the output.
736 ///
737 /// For more information on formatters, see [the module-level documentation][module].
738 ///
739 /// [module]: ../../std/fmt/index.html
740 ///
741 /// # Examples
742 ///
743 /// Basic usage with [`i32`]:
744 ///
745 /// ```
746 /// let x = 42; // 42 is '101010' in binary
747 ///
748 /// assert_eq!(format!("{x:b}"), "101010");
749 /// assert_eq!(format!("{x:#b}"), "0b101010");
750 ///
751 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
752 /// ```
753 ///
754 /// Implementing `Binary` on a type:
755 ///
756 /// ```
757 /// use std::fmt;
758 ///
759 /// struct Length(i32);
760 ///
761 /// impl fmt::Binary for Length {
762 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
763 /// let val = self.0;
764 ///
765 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
766 /// }
767 /// }
768 ///
769 /// let l = Length(107);
770 ///
771 /// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
772 ///
773 /// assert_eq!(
774 /// format!("l as binary is: {l:#032b}"),
775 /// "l as binary is: 0b000000000000000000000001101011"
776 /// );
777 /// ```
778 #[stable(feature = "rust1", since = "1.0.0")]
779 pub trait Binary {
780 /// Formats the value using the given formatter.
781 #[stable(feature = "rust1", since = "1.0.0")]
fmt(&self, f: &mut Formatter<'_>) -> Result782 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
783 }
784
785 /// `x` formatting.
786 ///
787 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
788 /// in lower case.
789 ///
790 /// For primitive signed integers (`i8` to `i128`, and `isize`),
791 /// negative values are formatted as the two’s complement representation.
792 ///
793 /// The alternate flag, `#`, adds a `0x` in front of the output.
794 ///
795 /// For more information on formatters, see [the module-level documentation][module].
796 ///
797 /// [module]: ../../std/fmt/index.html
798 ///
799 /// # Examples
800 ///
801 /// Basic usage with `i32`:
802 ///
803 /// ```
804 /// let x = 42; // 42 is '2a' in hex
805 ///
806 /// assert_eq!(format!("{x:x}"), "2a");
807 /// assert_eq!(format!("{x:#x}"), "0x2a");
808 ///
809 /// assert_eq!(format!("{:x}", -16), "fffffff0");
810 /// ```
811 ///
812 /// Implementing `LowerHex` on a type:
813 ///
814 /// ```
815 /// use std::fmt;
816 ///
817 /// struct Length(i32);
818 ///
819 /// impl fmt::LowerHex for Length {
820 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
821 /// let val = self.0;
822 ///
823 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
824 /// }
825 /// }
826 ///
827 /// let l = Length(9);
828 ///
829 /// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
830 ///
831 /// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
832 /// ```
833 #[stable(feature = "rust1", since = "1.0.0")]
834 pub trait LowerHex {
835 /// Formats the value using the given formatter.
836 #[stable(feature = "rust1", since = "1.0.0")]
fmt(&self, f: &mut Formatter<'_>) -> Result837 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
838 }
839
840 /// `X` formatting.
841 ///
842 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
843 /// in upper case.
844 ///
845 /// For primitive signed integers (`i8` to `i128`, and `isize`),
846 /// negative values are formatted as the two’s complement representation.
847 ///
848 /// The alternate flag, `#`, adds a `0x` in front of the output.
849 ///
850 /// For more information on formatters, see [the module-level documentation][module].
851 ///
852 /// [module]: ../../std/fmt/index.html
853 ///
854 /// # Examples
855 ///
856 /// Basic usage with `i32`:
857 ///
858 /// ```
859 /// let x = 42; // 42 is '2A' in hex
860 ///
861 /// assert_eq!(format!("{x:X}"), "2A");
862 /// assert_eq!(format!("{x:#X}"), "0x2A");
863 ///
864 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
865 /// ```
866 ///
867 /// Implementing `UpperHex` on a type:
868 ///
869 /// ```
870 /// use std::fmt;
871 ///
872 /// struct Length(i32);
873 ///
874 /// impl fmt::UpperHex for Length {
875 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
876 /// let val = self.0;
877 ///
878 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
879 /// }
880 /// }
881 ///
882 /// let l = Length(i32::MAX);
883 ///
884 /// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
885 ///
886 /// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
887 /// ```
888 #[stable(feature = "rust1", since = "1.0.0")]
889 pub trait UpperHex {
890 /// Formats the value using the given formatter.
891 #[stable(feature = "rust1", since = "1.0.0")]
fmt(&self, f: &mut Formatter<'_>) -> Result892 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
893 }
894
895 /// `p` formatting.
896 ///
897 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
898 /// as hexadecimal.
899 ///
900 /// For more information on formatters, see [the module-level documentation][module].
901 ///
902 /// [module]: ../../std/fmt/index.html
903 ///
904 /// # Examples
905 ///
906 /// Basic usage with `&i32`:
907 ///
908 /// ```
909 /// let x = &42;
910 ///
911 /// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
912 /// ```
913 ///
914 /// Implementing `Pointer` on a type:
915 ///
916 /// ```
917 /// use std::fmt;
918 ///
919 /// struct Length(i32);
920 ///
921 /// impl fmt::Pointer for Length {
922 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
923 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
924 ///
925 /// let ptr = self as *const Self;
926 /// fmt::Pointer::fmt(&ptr, f)
927 /// }
928 /// }
929 ///
930 /// let l = Length(42);
931 ///
932 /// println!("l is in memory here: {l:p}");
933 ///
934 /// let l_ptr = format!("{l:018p}");
935 /// assert_eq!(l_ptr.len(), 18);
936 /// assert_eq!(&l_ptr[..2], "0x");
937 /// ```
938 #[stable(feature = "rust1", since = "1.0.0")]
939 #[rustc_diagnostic_item = "Pointer"]
940 pub trait Pointer {
941 /// Formats the value using the given formatter.
942 #[stable(feature = "rust1", since = "1.0.0")]
fmt(&self, f: &mut Formatter<'_>) -> Result943 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
944 }
945
946 /// `e` formatting.
947 ///
948 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
949 ///
950 /// For more information on formatters, see [the module-level documentation][module].
951 ///
952 /// [module]: ../../std/fmt/index.html
953 ///
954 /// # Examples
955 ///
956 /// Basic usage with `f64`:
957 ///
958 /// ```
959 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
960 ///
961 /// assert_eq!(format!("{x:e}"), "4.2e1");
962 /// ```
963 ///
964 /// Implementing `LowerExp` on a type:
965 ///
966 /// ```
967 /// use std::fmt;
968 ///
969 /// struct Length(i32);
970 ///
971 /// impl fmt::LowerExp for Length {
972 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
973 /// let val = f64::from(self.0);
974 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
975 /// }
976 /// }
977 ///
978 /// let l = Length(100);
979 ///
980 /// assert_eq!(
981 /// format!("l in scientific notation is: {l:e}"),
982 /// "l in scientific notation is: 1e2"
983 /// );
984 ///
985 /// assert_eq!(
986 /// format!("l in scientific notation is: {l:05e}"),
987 /// "l in scientific notation is: 001e2"
988 /// );
989 /// ```
990 #[stable(feature = "rust1", since = "1.0.0")]
991 pub trait LowerExp {
992 /// Formats the value using the given formatter.
993 #[stable(feature = "rust1", since = "1.0.0")]
fmt(&self, f: &mut Formatter<'_>) -> Result994 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
995 }
996
997 /// `E` formatting.
998 ///
999 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1000 ///
1001 /// For more information on formatters, see [the module-level documentation][module].
1002 ///
1003 /// [module]: ../../std/fmt/index.html
1004 ///
1005 /// # Examples
1006 ///
1007 /// Basic usage with `f64`:
1008 ///
1009 /// ```
1010 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1011 ///
1012 /// assert_eq!(format!("{x:E}"), "4.2E1");
1013 /// ```
1014 ///
1015 /// Implementing `UpperExp` on a type:
1016 ///
1017 /// ```
1018 /// use std::fmt;
1019 ///
1020 /// struct Length(i32);
1021 ///
1022 /// impl fmt::UpperExp for Length {
1023 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1024 /// let val = f64::from(self.0);
1025 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1026 /// }
1027 /// }
1028 ///
1029 /// let l = Length(100);
1030 ///
1031 /// assert_eq!(
1032 /// format!("l in scientific notation is: {l:E}"),
1033 /// "l in scientific notation is: 1E2"
1034 /// );
1035 ///
1036 /// assert_eq!(
1037 /// format!("l in scientific notation is: {l:05E}"),
1038 /// "l in scientific notation is: 001E2"
1039 /// );
1040 /// ```
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 pub trait UpperExp {
1043 /// Formats the value using the given formatter.
1044 #[stable(feature = "rust1", since = "1.0.0")]
fmt(&self, f: &mut Formatter<'_>) -> Result1045 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1046 }
1047
1048 /// The `write` function takes an output stream, and an `Arguments` struct
1049 /// that can be precompiled with the `format_args!` macro.
1050 ///
1051 /// The arguments will be formatted according to the specified format string
1052 /// into the output stream provided.
1053 ///
1054 /// # Examples
1055 ///
1056 /// Basic usage:
1057 ///
1058 /// ```
1059 /// use std::fmt;
1060 ///
1061 /// let mut output = String::new();
1062 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1063 /// .expect("Error occurred while trying to write in String");
1064 /// assert_eq!(output, "Hello world!");
1065 /// ```
1066 ///
1067 /// Please note that using [`write!`] might be preferable. Example:
1068 ///
1069 /// ```
1070 /// use std::fmt::Write;
1071 ///
1072 /// let mut output = String::new();
1073 /// write!(&mut output, "Hello {}!", "world")
1074 /// .expect("Error occurred while trying to write in String");
1075 /// assert_eq!(output, "Hello world!");
1076 /// ```
1077 ///
1078 /// [`write!`]: crate::write!
1079 #[stable(feature = "rust1", since = "1.0.0")]
write(output: &mut dyn Write, args: Arguments<'_>) -> Result1080 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1081 let mut formatter = Formatter::new(output);
1082 let mut idx = 0;
1083
1084 match args.fmt {
1085 None => {
1086 // We can use default formatting parameters for all arguments.
1087 for (i, arg) in args.args.iter().enumerate() {
1088 // SAFETY: args.args and args.pieces come from the same Arguments,
1089 // which guarantees the indexes are always within bounds.
1090 let piece = unsafe { args.pieces.get_unchecked(i) };
1091 if !piece.is_empty() {
1092 formatter.buf.write_str(*piece)?;
1093 }
1094 arg.fmt(&mut formatter)?;
1095 idx += 1;
1096 }
1097 }
1098 Some(fmt) => {
1099 // Every spec has a corresponding argument that is preceded by
1100 // a string piece.
1101 for (i, arg) in fmt.iter().enumerate() {
1102 // SAFETY: fmt and args.pieces come from the same Arguments,
1103 // which guarantees the indexes are always within bounds.
1104 let piece = unsafe { args.pieces.get_unchecked(i) };
1105 if !piece.is_empty() {
1106 formatter.buf.write_str(*piece)?;
1107 }
1108 // SAFETY: arg and args.args come from the same Arguments,
1109 // which guarantees the indexes are always within bounds.
1110 unsafe { run(&mut formatter, arg, args.args) }?;
1111 idx += 1;
1112 }
1113 }
1114 }
1115
1116 // There can be only one trailing string piece left.
1117 if let Some(piece) = args.pieces.get(idx) {
1118 formatter.buf.write_str(*piece)?;
1119 }
1120
1121 Ok(())
1122 }
1123
run(fmt: &mut Formatter<'_>, arg: &rt::Placeholder, args: &[rt::Argument<'_>]) -> Result1124 unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::Placeholder, args: &[rt::Argument<'_>]) -> Result {
1125 fmt.fill = arg.fill;
1126 fmt.align = arg.align;
1127 fmt.flags = arg.flags;
1128 // SAFETY: arg and args come from the same Arguments,
1129 // which guarantees the indexes are always within bounds.
1130 unsafe {
1131 fmt.width = getcount(args, &arg.width);
1132 fmt.precision = getcount(args, &arg.precision);
1133 }
1134
1135 // Extract the correct argument
1136 debug_assert!(arg.position < args.len());
1137 // SAFETY: arg and args come from the same Arguments,
1138 // which guarantees its index is always within bounds.
1139 let value = unsafe { args.get_unchecked(arg.position) };
1140
1141 // Then actually do some printing
1142 value.fmt(fmt)
1143 }
1144
getcount(args: &[rt::Argument<'_>], cnt: &rt::Count) -> Option<usize>1145 unsafe fn getcount(args: &[rt::Argument<'_>], cnt: &rt::Count) -> Option<usize> {
1146 match *cnt {
1147 rt::Count::Is(n) => Some(n),
1148 rt::Count::Implied => None,
1149 rt::Count::Param(i) => {
1150 debug_assert!(i < args.len());
1151 // SAFETY: cnt and args come from the same Arguments,
1152 // which guarantees this index is always within bounds.
1153 unsafe { args.get_unchecked(i).as_usize() }
1154 }
1155 }
1156 }
1157
1158 /// Padding after the end of something. Returned by `Formatter::padding`.
1159 #[must_use = "don't forget to write the post padding"]
1160 pub(crate) struct PostPadding {
1161 fill: char,
1162 padding: usize,
1163 }
1164
1165 impl PostPadding {
new(fill: char, padding: usize) -> PostPadding1166 fn new(fill: char, padding: usize) -> PostPadding {
1167 PostPadding { fill, padding }
1168 }
1169
1170 /// Write this post padding.
write(self, f: &mut Formatter<'_>) -> Result1171 pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1172 for _ in 0..self.padding {
1173 f.buf.write_char(self.fill)?;
1174 }
1175 Ok(())
1176 }
1177 }
1178
1179 impl<'a> Formatter<'a> {
wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c> where 'b: 'c, F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),1180 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1181 where
1182 'b: 'c,
1183 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1184 {
1185 Formatter {
1186 // We want to change this
1187 buf: wrap(self.buf),
1188
1189 // And preserve these
1190 flags: self.flags,
1191 fill: self.fill,
1192 align: self.align,
1193 width: self.width,
1194 precision: self.precision,
1195 }
1196 }
1197
1198 // Helper methods used for padding and processing formatting arguments that
1199 // all formatting traits can use.
1200
1201 /// Performs the correct padding for an integer which has already been
1202 /// emitted into a str. The str should *not* contain the sign for the
1203 /// integer, that will be added by this method.
1204 ///
1205 /// # Arguments
1206 ///
1207 /// * is_nonnegative - whether the original integer was either positive or zero.
1208 /// * prefix - if the '#' character (Alternate) is provided, this
1209 /// is the prefix to put in front of the number.
1210 /// * buf - the byte array that the number has been formatted into
1211 ///
1212 /// This function will correctly account for the flags provided as well as
1213 /// the minimum width. It will not take precision into account.
1214 ///
1215 /// # Examples
1216 ///
1217 /// ```
1218 /// use std::fmt;
1219 ///
1220 /// struct Foo { nb: i32 }
1221 ///
1222 /// impl Foo {
1223 /// fn new(nb: i32) -> Foo {
1224 /// Foo {
1225 /// nb,
1226 /// }
1227 /// }
1228 /// }
1229 ///
1230 /// impl fmt::Display for Foo {
1231 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1232 /// // We need to remove "-" from the number output.
1233 /// let tmp = self.nb.abs().to_string();
1234 ///
1235 /// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1236 /// }
1237 /// }
1238 ///
1239 /// assert_eq!(format!("{}", Foo::new(2)), "2");
1240 /// assert_eq!(format!("{}", Foo::new(-1)), "-1");
1241 /// assert_eq!(format!("{}", Foo::new(0)), "0");
1242 /// assert_eq!(format!("{:#}", Foo::new(-1)), "-Foo 1");
1243 /// assert_eq!(format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1244 /// ```
1245 #[stable(feature = "rust1", since = "1.0.0")]
pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result1246 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1247 let mut width = buf.len();
1248
1249 let mut sign = None;
1250 if !is_nonnegative {
1251 sign = Some('-');
1252 width += 1;
1253 } else if self.sign_plus() {
1254 sign = Some('+');
1255 width += 1;
1256 }
1257
1258 let prefix = if self.alternate() {
1259 width += prefix.chars().count();
1260 Some(prefix)
1261 } else {
1262 None
1263 };
1264
1265 // Writes the sign if it exists, and then the prefix if it was requested
1266 #[inline(never)]
1267 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1268 if let Some(c) = sign {
1269 f.buf.write_char(c)?;
1270 }
1271 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1272 }
1273
1274 // The `width` field is more of a `min-width` parameter at this point.
1275 match self.width {
1276 // If there's no minimum length requirements then we can just
1277 // write the bytes.
1278 None => {
1279 write_prefix(self, sign, prefix)?;
1280 self.buf.write_str(buf)
1281 }
1282 // Check if we're over the minimum width, if so then we can also
1283 // just write the bytes.
1284 Some(min) if width >= min => {
1285 write_prefix(self, sign, prefix)?;
1286 self.buf.write_str(buf)
1287 }
1288 // The sign and prefix goes before the padding if the fill character
1289 // is zero
1290 Some(min) if self.sign_aware_zero_pad() => {
1291 let old_fill = crate::mem::replace(&mut self.fill, '0');
1292 let old_align = crate::mem::replace(&mut self.align, rt::Alignment::Right);
1293 write_prefix(self, sign, prefix)?;
1294 let post_padding = self.padding(min - width, Alignment::Right)?;
1295 self.buf.write_str(buf)?;
1296 post_padding.write(self)?;
1297 self.fill = old_fill;
1298 self.align = old_align;
1299 Ok(())
1300 }
1301 // Otherwise, the sign and prefix goes after the padding
1302 Some(min) => {
1303 let post_padding = self.padding(min - width, Alignment::Right)?;
1304 write_prefix(self, sign, prefix)?;
1305 self.buf.write_str(buf)?;
1306 post_padding.write(self)
1307 }
1308 }
1309 }
1310
1311 /// This function takes a string slice and emits it to the internal buffer
1312 /// after applying the relevant formatting flags specified. The flags
1313 /// recognized for generic strings are:
1314 ///
1315 /// * width - the minimum width of what to emit
1316 /// * fill/align - what to emit and where to emit it if the string
1317 /// provided needs to be padded
1318 /// * precision - the maximum length to emit, the string is truncated if it
1319 /// is longer than this length
1320 ///
1321 /// Notably this function ignores the `flag` parameters.
1322 ///
1323 /// # Examples
1324 ///
1325 /// ```
1326 /// use std::fmt;
1327 ///
1328 /// struct Foo;
1329 ///
1330 /// impl fmt::Display for Foo {
1331 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1332 /// formatter.pad("Foo")
1333 /// }
1334 /// }
1335 ///
1336 /// assert_eq!(format!("{Foo:<4}"), "Foo ");
1337 /// assert_eq!(format!("{Foo:0>4}"), "0Foo");
1338 /// ```
1339 #[stable(feature = "rust1", since = "1.0.0")]
pad(&mut self, s: &str) -> Result1340 pub fn pad(&mut self, s: &str) -> Result {
1341 // Make sure there's a fast path up front
1342 if self.width.is_none() && self.precision.is_none() {
1343 return self.buf.write_str(s);
1344 }
1345 // The `precision` field can be interpreted as a `max-width` for the
1346 // string being formatted.
1347 let s = if let Some(max) = self.precision {
1348 // If our string is longer that the precision, then we must have
1349 // truncation. However other flags like `fill`, `width` and `align`
1350 // must act as always.
1351 if let Some((i, _)) = s.char_indices().nth(max) {
1352 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1353 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1354 // `unsafe` and otherwise don't emit any panic-related code
1355 // here.
1356 s.get(..i).unwrap_or(s)
1357 } else {
1358 &s
1359 }
1360 } else {
1361 &s
1362 };
1363 // The `width` field is more of a `min-width` parameter at this point.
1364 match self.width {
1365 // If we're under the maximum length, and there's no minimum length
1366 // requirements, then we can just emit the string
1367 None => self.buf.write_str(s),
1368 Some(width) => {
1369 let chars_count = s.chars().count();
1370 // If we're under the maximum width, check if we're over the minimum
1371 // width, if so it's as easy as just emitting the string.
1372 if chars_count >= width {
1373 self.buf.write_str(s)
1374 }
1375 // If we're under both the maximum and the minimum width, then fill
1376 // up the minimum width with the specified string + some alignment.
1377 else {
1378 let align = Alignment::Left;
1379 let post_padding = self.padding(width - chars_count, align)?;
1380 self.buf.write_str(s)?;
1381 post_padding.write(self)
1382 }
1383 }
1384 }
1385 }
1386
1387 /// Write the pre-padding and return the unwritten post-padding. Callers are
1388 /// responsible for ensuring post-padding is written after the thing that is
1389 /// being padded.
padding( &mut self, padding: usize, default: Alignment, ) -> result::Result<PostPadding, Error>1390 pub(crate) fn padding(
1391 &mut self,
1392 padding: usize,
1393 default: Alignment,
1394 ) -> result::Result<PostPadding, Error> {
1395 let align = match self.align {
1396 rt::Alignment::Unknown => default,
1397 rt::Alignment::Left => Alignment::Left,
1398 rt::Alignment::Right => Alignment::Right,
1399 rt::Alignment::Center => Alignment::Center,
1400 };
1401
1402 let (pre_pad, post_pad) = match align {
1403 Alignment::Left => (0, padding),
1404 Alignment::Right => (padding, 0),
1405 Alignment::Center => (padding / 2, (padding + 1) / 2),
1406 };
1407
1408 for _ in 0..pre_pad {
1409 self.buf.write_char(self.fill)?;
1410 }
1411
1412 Ok(PostPadding::new(self.fill, post_pad))
1413 }
1414
1415 /// Takes the formatted parts and applies the padding.
1416 /// Assumes that the caller already has rendered the parts with required precision,
1417 /// so that `self.precision` can be ignored.
1418 ///
1419 /// # Safety
1420 ///
1421 /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result1422 unsafe fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1423 if let Some(mut width) = self.width {
1424 // for the sign-aware zero padding, we render the sign first and
1425 // behave as if we had no sign from the beginning.
1426 let mut formatted = formatted.clone();
1427 let old_fill = self.fill;
1428 let old_align = self.align;
1429 if self.sign_aware_zero_pad() {
1430 // a sign always goes first
1431 let sign = formatted.sign;
1432 self.buf.write_str(sign)?;
1433
1434 // remove the sign from the formatted parts
1435 formatted.sign = "";
1436 width = width.saturating_sub(sign.len());
1437 self.fill = '0';
1438 self.align = rt::Alignment::Right;
1439 }
1440
1441 // remaining parts go through the ordinary padding process.
1442 let len = formatted.len();
1443 let ret = if width <= len {
1444 // no padding
1445 // SAFETY: Per the precondition.
1446 unsafe { self.write_formatted_parts(&formatted) }
1447 } else {
1448 let post_padding = self.padding(width - len, Alignment::Right)?;
1449 // SAFETY: Per the precondition.
1450 unsafe {
1451 self.write_formatted_parts(&formatted)?;
1452 }
1453 post_padding.write(self)
1454 };
1455 self.fill = old_fill;
1456 self.align = old_align;
1457 ret
1458 } else {
1459 // this is the common case and we take a shortcut
1460 // SAFETY: Per the precondition.
1461 unsafe { self.write_formatted_parts(formatted) }
1462 }
1463 }
1464
1465 /// # Safety
1466 ///
1467 /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result1468 unsafe fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1469 unsafe fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1470 // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1471 // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1472 // `b'0'` and `b'9'`, which means `s` is valid UTF-8. It's safe to use for
1473 // `numfmt::Part::Copy` due to this function's precondition.
1474 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1475 }
1476
1477 if !formatted.sign.is_empty() {
1478 self.buf.write_str(formatted.sign)?;
1479 }
1480 for part in formatted.parts {
1481 match *part {
1482 numfmt::Part::Zero(mut nzeroes) => {
1483 const ZEROES: &str = // 64 zeroes
1484 "0000000000000000000000000000000000000000000000000000000000000000";
1485 while nzeroes > ZEROES.len() {
1486 self.buf.write_str(ZEROES)?;
1487 nzeroes -= ZEROES.len();
1488 }
1489 if nzeroes > 0 {
1490 self.buf.write_str(&ZEROES[..nzeroes])?;
1491 }
1492 }
1493 numfmt::Part::Num(mut v) => {
1494 let mut s = [0; 5];
1495 let len = part.len();
1496 for c in s[..len].iter_mut().rev() {
1497 *c = b'0' + (v % 10) as u8;
1498 v /= 10;
1499 }
1500 // SAFETY: Per the precondition.
1501 unsafe {
1502 write_bytes(self.buf, &s[..len])?;
1503 }
1504 }
1505 // SAFETY: Per the precondition.
1506 numfmt::Part::Copy(buf) => unsafe {
1507 write_bytes(self.buf, buf)?;
1508 },
1509 }
1510 }
1511 Ok(())
1512 }
1513
1514 /// Writes some data to the underlying buffer contained within this
1515 /// formatter.
1516 ///
1517 /// # Examples
1518 ///
1519 /// ```
1520 /// use std::fmt;
1521 ///
1522 /// struct Foo;
1523 ///
1524 /// impl fmt::Display for Foo {
1525 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1526 /// formatter.write_str("Foo")
1527 /// // This is equivalent to:
1528 /// // write!(formatter, "Foo")
1529 /// }
1530 /// }
1531 ///
1532 /// assert_eq!(format!("{Foo}"), "Foo");
1533 /// assert_eq!(format!("{Foo:0>8}"), "Foo");
1534 /// ```
1535 #[stable(feature = "rust1", since = "1.0.0")]
write_str(&mut self, data: &str) -> Result1536 pub fn write_str(&mut self, data: &str) -> Result {
1537 self.buf.write_str(data)
1538 }
1539
1540 /// Writes some formatted information into this instance.
1541 ///
1542 /// # Examples
1543 ///
1544 /// ```
1545 /// use std::fmt;
1546 ///
1547 /// struct Foo(i32);
1548 ///
1549 /// impl fmt::Display for Foo {
1550 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1551 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1552 /// }
1553 /// }
1554 ///
1555 /// assert_eq!(format!("{}", Foo(-1)), "Foo -1");
1556 /// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
1557 /// ```
1558 #[stable(feature = "rust1", since = "1.0.0")]
write_fmt(&mut self, fmt: Arguments<'_>) -> Result1559 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1560 write(self.buf, fmt)
1561 }
1562
1563 /// Flags for formatting
1564 #[must_use]
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 #[deprecated(
1567 since = "1.24.0",
1568 note = "use the `sign_plus`, `sign_minus`, `alternate`, \
1569 or `sign_aware_zero_pad` methods instead"
1570 )]
flags(&self) -> u321571 pub fn flags(&self) -> u32 {
1572 self.flags
1573 }
1574
1575 /// Character used as 'fill' whenever there is alignment.
1576 ///
1577 /// # Examples
1578 ///
1579 /// ```
1580 /// use std::fmt;
1581 ///
1582 /// struct Foo;
1583 ///
1584 /// impl fmt::Display for Foo {
1585 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1586 /// let c = formatter.fill();
1587 /// if let Some(width) = formatter.width() {
1588 /// for _ in 0..width {
1589 /// write!(formatter, "{c}")?;
1590 /// }
1591 /// Ok(())
1592 /// } else {
1593 /// write!(formatter, "{c}")
1594 /// }
1595 /// }
1596 /// }
1597 ///
1598 /// // We set alignment to the right with ">".
1599 /// assert_eq!(format!("{Foo:G>3}"), "GGG");
1600 /// assert_eq!(format!("{Foo:t>6}"), "tttttt");
1601 /// ```
1602 #[must_use]
1603 #[stable(feature = "fmt_flags", since = "1.5.0")]
fill(&self) -> char1604 pub fn fill(&self) -> char {
1605 self.fill
1606 }
1607
1608 /// Flag indicating what form of alignment was requested.
1609 ///
1610 /// # Examples
1611 ///
1612 /// ```
1613 /// use std::fmt::{self, Alignment};
1614 ///
1615 /// struct Foo;
1616 ///
1617 /// impl fmt::Display for Foo {
1618 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1619 /// let s = if let Some(s) = formatter.align() {
1620 /// match s {
1621 /// Alignment::Left => "left",
1622 /// Alignment::Right => "right",
1623 /// Alignment::Center => "center",
1624 /// }
1625 /// } else {
1626 /// "into the void"
1627 /// };
1628 /// write!(formatter, "{s}")
1629 /// }
1630 /// }
1631 ///
1632 /// assert_eq!(format!("{Foo:<}"), "left");
1633 /// assert_eq!(format!("{Foo:>}"), "right");
1634 /// assert_eq!(format!("{Foo:^}"), "center");
1635 /// assert_eq!(format!("{Foo}"), "into the void");
1636 /// ```
1637 #[must_use]
1638 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
align(&self) -> Option<Alignment>1639 pub fn align(&self) -> Option<Alignment> {
1640 match self.align {
1641 rt::Alignment::Left => Some(Alignment::Left),
1642 rt::Alignment::Right => Some(Alignment::Right),
1643 rt::Alignment::Center => Some(Alignment::Center),
1644 rt::Alignment::Unknown => None,
1645 }
1646 }
1647
1648 /// Optionally specified integer width that the output should be.
1649 ///
1650 /// # Examples
1651 ///
1652 /// ```
1653 /// use std::fmt;
1654 ///
1655 /// struct Foo(i32);
1656 ///
1657 /// impl fmt::Display for Foo {
1658 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1659 /// if let Some(width) = formatter.width() {
1660 /// // If we received a width, we use it
1661 /// write!(formatter, "{:width$}", format!("Foo({})", self.0), width = width)
1662 /// } else {
1663 /// // Otherwise we do nothing special
1664 /// write!(formatter, "Foo({})", self.0)
1665 /// }
1666 /// }
1667 /// }
1668 ///
1669 /// assert_eq!(format!("{:10}", Foo(23)), "Foo(23) ");
1670 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
1671 /// ```
1672 #[must_use]
1673 #[stable(feature = "fmt_flags", since = "1.5.0")]
width(&self) -> Option<usize>1674 pub fn width(&self) -> Option<usize> {
1675 self.width
1676 }
1677
1678 /// Optionally specified precision for numeric types. Alternatively, the
1679 /// maximum width for string types.
1680 ///
1681 /// # Examples
1682 ///
1683 /// ```
1684 /// use std::fmt;
1685 ///
1686 /// struct Foo(f32);
1687 ///
1688 /// impl fmt::Display for Foo {
1689 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1690 /// if let Some(precision) = formatter.precision() {
1691 /// // If we received a precision, we use it.
1692 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1693 /// } else {
1694 /// // Otherwise we default to 2.
1695 /// write!(formatter, "Foo({:.2})", self.0)
1696 /// }
1697 /// }
1698 /// }
1699 ///
1700 /// assert_eq!(format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1701 /// assert_eq!(format!("{}", Foo(23.2)), "Foo(23.20)");
1702 /// ```
1703 #[must_use]
1704 #[stable(feature = "fmt_flags", since = "1.5.0")]
precision(&self) -> Option<usize>1705 pub fn precision(&self) -> Option<usize> {
1706 self.precision
1707 }
1708
1709 /// Determines if the `+` flag was specified.
1710 ///
1711 /// # Examples
1712 ///
1713 /// ```
1714 /// use std::fmt;
1715 ///
1716 /// struct Foo(i32);
1717 ///
1718 /// impl fmt::Display for Foo {
1719 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1720 /// if formatter.sign_plus() {
1721 /// write!(formatter,
1722 /// "Foo({}{})",
1723 /// if self.0 < 0 { '-' } else { '+' },
1724 /// self.0.abs())
1725 /// } else {
1726 /// write!(formatter, "Foo({})", self.0)
1727 /// }
1728 /// }
1729 /// }
1730 ///
1731 /// assert_eq!(format!("{:+}", Foo(23)), "Foo(+23)");
1732 /// assert_eq!(format!("{:+}", Foo(-23)), "Foo(-23)");
1733 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
1734 /// ```
1735 #[must_use]
1736 #[stable(feature = "fmt_flags", since = "1.5.0")]
sign_plus(&self) -> bool1737 pub fn sign_plus(&self) -> bool {
1738 self.flags & (1 << rt::Flag::SignPlus as u32) != 0
1739 }
1740
1741 /// Determines if the `-` flag was specified.
1742 ///
1743 /// # Examples
1744 ///
1745 /// ```
1746 /// use std::fmt;
1747 ///
1748 /// struct Foo(i32);
1749 ///
1750 /// impl fmt::Display for Foo {
1751 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1752 /// if formatter.sign_minus() {
1753 /// // You want a minus sign? Have one!
1754 /// write!(formatter, "-Foo({})", self.0)
1755 /// } else {
1756 /// write!(formatter, "Foo({})", self.0)
1757 /// }
1758 /// }
1759 /// }
1760 ///
1761 /// assert_eq!(format!("{:-}", Foo(23)), "-Foo(23)");
1762 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
1763 /// ```
1764 #[must_use]
1765 #[stable(feature = "fmt_flags", since = "1.5.0")]
sign_minus(&self) -> bool1766 pub fn sign_minus(&self) -> bool {
1767 self.flags & (1 << rt::Flag::SignMinus as u32) != 0
1768 }
1769
1770 /// Determines if the `#` flag was specified.
1771 ///
1772 /// # Examples
1773 ///
1774 /// ```
1775 /// use std::fmt;
1776 ///
1777 /// struct Foo(i32);
1778 ///
1779 /// impl fmt::Display for Foo {
1780 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1781 /// if formatter.alternate() {
1782 /// write!(formatter, "Foo({})", self.0)
1783 /// } else {
1784 /// write!(formatter, "{}", self.0)
1785 /// }
1786 /// }
1787 /// }
1788 ///
1789 /// assert_eq!(format!("{:#}", Foo(23)), "Foo(23)");
1790 /// assert_eq!(format!("{}", Foo(23)), "23");
1791 /// ```
1792 #[must_use]
1793 #[stable(feature = "fmt_flags", since = "1.5.0")]
alternate(&self) -> bool1794 pub fn alternate(&self) -> bool {
1795 self.flags & (1 << rt::Flag::Alternate as u32) != 0
1796 }
1797
1798 /// Determines if the `0` flag was specified.
1799 ///
1800 /// # Examples
1801 ///
1802 /// ```
1803 /// use std::fmt;
1804 ///
1805 /// struct Foo(i32);
1806 ///
1807 /// impl fmt::Display for Foo {
1808 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1809 /// assert!(formatter.sign_aware_zero_pad());
1810 /// assert_eq!(formatter.width(), Some(4));
1811 /// // We ignore the formatter's options.
1812 /// write!(formatter, "{}", self.0)
1813 /// }
1814 /// }
1815 ///
1816 /// assert_eq!(format!("{:04}", Foo(23)), "23");
1817 /// ```
1818 #[must_use]
1819 #[stable(feature = "fmt_flags", since = "1.5.0")]
sign_aware_zero_pad(&self) -> bool1820 pub fn sign_aware_zero_pad(&self) -> bool {
1821 self.flags & (1 << rt::Flag::SignAwareZeroPad as u32) != 0
1822 }
1823
1824 // FIXME: Decide what public API we want for these two flags.
1825 // https://github.com/rust-lang/rust/issues/48584
debug_lower_hex(&self) -> bool1826 fn debug_lower_hex(&self) -> bool {
1827 self.flags & (1 << rt::Flag::DebugLowerHex as u32) != 0
1828 }
1829
debug_upper_hex(&self) -> bool1830 fn debug_upper_hex(&self) -> bool {
1831 self.flags & (1 << rt::Flag::DebugUpperHex as u32) != 0
1832 }
1833
1834 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1835 /// [`fmt::Debug`] implementations for structs.
1836 ///
1837 /// [`fmt::Debug`]: self::Debug
1838 ///
1839 /// # Examples
1840 ///
1841 /// ```rust
1842 /// use std::fmt;
1843 /// use std::net::Ipv4Addr;
1844 ///
1845 /// struct Foo {
1846 /// bar: i32,
1847 /// baz: String,
1848 /// addr: Ipv4Addr,
1849 /// }
1850 ///
1851 /// impl fmt::Debug for Foo {
1852 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1853 /// fmt.debug_struct("Foo")
1854 /// .field("bar", &self.bar)
1855 /// .field("baz", &self.baz)
1856 /// .field("addr", &format_args!("{}", self.addr))
1857 /// .finish()
1858 /// }
1859 /// }
1860 ///
1861 /// assert_eq!(
1862 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1863 /// format!("{:?}", Foo {
1864 /// bar: 10,
1865 /// baz: "Hello World".to_string(),
1866 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1867 /// })
1868 /// );
1869 /// ```
1870 #[stable(feature = "debug_builders", since = "1.2.0")]
debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a>1871 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1872 builders::debug_struct_new(self, name)
1873 }
1874
1875 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
1876 /// `debug_struct_fields_finish` is more general, but this is faster for 1 field.
1877 #[doc(hidden)]
1878 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_struct_field1_finish<'b>( &'b mut self, name: &str, name1: &str, value1: &dyn Debug, ) -> Result1879 pub fn debug_struct_field1_finish<'b>(
1880 &'b mut self,
1881 name: &str,
1882 name1: &str,
1883 value1: &dyn Debug,
1884 ) -> Result {
1885 let mut builder = builders::debug_struct_new(self, name);
1886 builder.field(name1, value1);
1887 builder.finish()
1888 }
1889
1890 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
1891 /// `debug_struct_fields_finish` is more general, but this is faster for 2 fields.
1892 #[doc(hidden)]
1893 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_struct_field2_finish<'b>( &'b mut self, name: &str, name1: &str, value1: &dyn Debug, name2: &str, value2: &dyn Debug, ) -> Result1894 pub fn debug_struct_field2_finish<'b>(
1895 &'b mut self,
1896 name: &str,
1897 name1: &str,
1898 value1: &dyn Debug,
1899 name2: &str,
1900 value2: &dyn Debug,
1901 ) -> Result {
1902 let mut builder = builders::debug_struct_new(self, name);
1903 builder.field(name1, value1);
1904 builder.field(name2, value2);
1905 builder.finish()
1906 }
1907
1908 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
1909 /// `debug_struct_fields_finish` is more general, but this is faster for 3 fields.
1910 #[doc(hidden)]
1911 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_struct_field3_finish<'b>( &'b mut self, name: &str, name1: &str, value1: &dyn Debug, name2: &str, value2: &dyn Debug, name3: &str, value3: &dyn Debug, ) -> Result1912 pub fn debug_struct_field3_finish<'b>(
1913 &'b mut self,
1914 name: &str,
1915 name1: &str,
1916 value1: &dyn Debug,
1917 name2: &str,
1918 value2: &dyn Debug,
1919 name3: &str,
1920 value3: &dyn Debug,
1921 ) -> Result {
1922 let mut builder = builders::debug_struct_new(self, name);
1923 builder.field(name1, value1);
1924 builder.field(name2, value2);
1925 builder.field(name3, value3);
1926 builder.finish()
1927 }
1928
1929 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
1930 /// `debug_struct_fields_finish` is more general, but this is faster for 4 fields.
1931 #[doc(hidden)]
1932 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_struct_field4_finish<'b>( &'b mut self, name: &str, name1: &str, value1: &dyn Debug, name2: &str, value2: &dyn Debug, name3: &str, value3: &dyn Debug, name4: &str, value4: &dyn Debug, ) -> Result1933 pub fn debug_struct_field4_finish<'b>(
1934 &'b mut self,
1935 name: &str,
1936 name1: &str,
1937 value1: &dyn Debug,
1938 name2: &str,
1939 value2: &dyn Debug,
1940 name3: &str,
1941 value3: &dyn Debug,
1942 name4: &str,
1943 value4: &dyn Debug,
1944 ) -> Result {
1945 let mut builder = builders::debug_struct_new(self, name);
1946 builder.field(name1, value1);
1947 builder.field(name2, value2);
1948 builder.field(name3, value3);
1949 builder.field(name4, value4);
1950 builder.finish()
1951 }
1952
1953 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
1954 /// `debug_struct_fields_finish` is more general, but this is faster for 5 fields.
1955 #[doc(hidden)]
1956 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_struct_field5_finish<'b>( &'b mut self, name: &str, name1: &str, value1: &dyn Debug, name2: &str, value2: &dyn Debug, name3: &str, value3: &dyn Debug, name4: &str, value4: &dyn Debug, name5: &str, value5: &dyn Debug, ) -> Result1957 pub fn debug_struct_field5_finish<'b>(
1958 &'b mut self,
1959 name: &str,
1960 name1: &str,
1961 value1: &dyn Debug,
1962 name2: &str,
1963 value2: &dyn Debug,
1964 name3: &str,
1965 value3: &dyn Debug,
1966 name4: &str,
1967 value4: &dyn Debug,
1968 name5: &str,
1969 value5: &dyn Debug,
1970 ) -> Result {
1971 let mut builder = builders::debug_struct_new(self, name);
1972 builder.field(name1, value1);
1973 builder.field(name2, value2);
1974 builder.field(name3, value3);
1975 builder.field(name4, value4);
1976 builder.field(name5, value5);
1977 builder.finish()
1978 }
1979
1980 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
1981 /// For the cases not covered by `debug_struct_field[12345]_finish`.
1982 #[doc(hidden)]
1983 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_struct_fields_finish<'b>( &'b mut self, name: &str, names: &[&str], values: &[&dyn Debug], ) -> Result1984 pub fn debug_struct_fields_finish<'b>(
1985 &'b mut self,
1986 name: &str,
1987 names: &[&str],
1988 values: &[&dyn Debug],
1989 ) -> Result {
1990 assert_eq!(names.len(), values.len());
1991 let mut builder = builders::debug_struct_new(self, name);
1992 for (name, value) in iter::zip(names, values) {
1993 builder.field(name, value);
1994 }
1995 builder.finish()
1996 }
1997
1998 /// Creates a `DebugTuple` builder designed to assist with creation of
1999 /// `fmt::Debug` implementations for tuple structs.
2000 ///
2001 /// # Examples
2002 ///
2003 /// ```rust
2004 /// use std::fmt;
2005 /// use std::marker::PhantomData;
2006 ///
2007 /// struct Foo<T>(i32, String, PhantomData<T>);
2008 ///
2009 /// impl<T> fmt::Debug for Foo<T> {
2010 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2011 /// fmt.debug_tuple("Foo")
2012 /// .field(&self.0)
2013 /// .field(&self.1)
2014 /// .field(&format_args!("_"))
2015 /// .finish()
2016 /// }
2017 /// }
2018 ///
2019 /// assert_eq!(
2020 /// "Foo(10, \"Hello\", _)",
2021 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
2022 /// );
2023 /// ```
2024 #[stable(feature = "debug_builders", since = "1.2.0")]
debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a>2025 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
2026 builders::debug_tuple_new(self, name)
2027 }
2028
2029 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2030 /// `debug_tuple_fields_finish` is more general, but this is faster for 1 field.
2031 #[doc(hidden)]
2032 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result2033 pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result {
2034 let mut builder = builders::debug_tuple_new(self, name);
2035 builder.field(value1);
2036 builder.finish()
2037 }
2038
2039 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2040 /// `debug_tuple_fields_finish` is more general, but this is faster for 2 fields.
2041 #[doc(hidden)]
2042 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_tuple_field2_finish<'b>( &'b mut self, name: &str, value1: &dyn Debug, value2: &dyn Debug, ) -> Result2043 pub fn debug_tuple_field2_finish<'b>(
2044 &'b mut self,
2045 name: &str,
2046 value1: &dyn Debug,
2047 value2: &dyn Debug,
2048 ) -> Result {
2049 let mut builder = builders::debug_tuple_new(self, name);
2050 builder.field(value1);
2051 builder.field(value2);
2052 builder.finish()
2053 }
2054
2055 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2056 /// `debug_tuple_fields_finish` is more general, but this is faster for 3 fields.
2057 #[doc(hidden)]
2058 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_tuple_field3_finish<'b>( &'b mut self, name: &str, value1: &dyn Debug, value2: &dyn Debug, value3: &dyn Debug, ) -> Result2059 pub fn debug_tuple_field3_finish<'b>(
2060 &'b mut self,
2061 name: &str,
2062 value1: &dyn Debug,
2063 value2: &dyn Debug,
2064 value3: &dyn Debug,
2065 ) -> Result {
2066 let mut builder = builders::debug_tuple_new(self, name);
2067 builder.field(value1);
2068 builder.field(value2);
2069 builder.field(value3);
2070 builder.finish()
2071 }
2072
2073 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2074 /// `debug_tuple_fields_finish` is more general, but this is faster for 4 fields.
2075 #[doc(hidden)]
2076 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_tuple_field4_finish<'b>( &'b mut self, name: &str, value1: &dyn Debug, value2: &dyn Debug, value3: &dyn Debug, value4: &dyn Debug, ) -> Result2077 pub fn debug_tuple_field4_finish<'b>(
2078 &'b mut self,
2079 name: &str,
2080 value1: &dyn Debug,
2081 value2: &dyn Debug,
2082 value3: &dyn Debug,
2083 value4: &dyn Debug,
2084 ) -> Result {
2085 let mut builder = builders::debug_tuple_new(self, name);
2086 builder.field(value1);
2087 builder.field(value2);
2088 builder.field(value3);
2089 builder.field(value4);
2090 builder.finish()
2091 }
2092
2093 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2094 /// `debug_tuple_fields_finish` is more general, but this is faster for 5 fields.
2095 #[doc(hidden)]
2096 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_tuple_field5_finish<'b>( &'b mut self, name: &str, value1: &dyn Debug, value2: &dyn Debug, value3: &dyn Debug, value4: &dyn Debug, value5: &dyn Debug, ) -> Result2097 pub fn debug_tuple_field5_finish<'b>(
2098 &'b mut self,
2099 name: &str,
2100 value1: &dyn Debug,
2101 value2: &dyn Debug,
2102 value3: &dyn Debug,
2103 value4: &dyn Debug,
2104 value5: &dyn Debug,
2105 ) -> Result {
2106 let mut builder = builders::debug_tuple_new(self, name);
2107 builder.field(value1);
2108 builder.field(value2);
2109 builder.field(value3);
2110 builder.field(value4);
2111 builder.field(value5);
2112 builder.finish()
2113 }
2114
2115 /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries.
2116 /// For the cases not covered by `debug_tuple_field[12345]_finish`.
2117 #[doc(hidden)]
2118 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
debug_tuple_fields_finish<'b>( &'b mut self, name: &str, values: &[&dyn Debug], ) -> Result2119 pub fn debug_tuple_fields_finish<'b>(
2120 &'b mut self,
2121 name: &str,
2122 values: &[&dyn Debug],
2123 ) -> Result {
2124 let mut builder = builders::debug_tuple_new(self, name);
2125 for value in values {
2126 builder.field(value);
2127 }
2128 builder.finish()
2129 }
2130
2131 /// Creates a `DebugList` builder designed to assist with creation of
2132 /// `fmt::Debug` implementations for list-like structures.
2133 ///
2134 /// # Examples
2135 ///
2136 /// ```rust
2137 /// use std::fmt;
2138 ///
2139 /// struct Foo(Vec<i32>);
2140 ///
2141 /// impl fmt::Debug for Foo {
2142 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2143 /// fmt.debug_list().entries(self.0.iter()).finish()
2144 /// }
2145 /// }
2146 ///
2147 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2148 /// ```
2149 #[stable(feature = "debug_builders", since = "1.2.0")]
debug_list<'b>(&'b mut self) -> DebugList<'b, 'a>2150 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2151 builders::debug_list_new(self)
2152 }
2153
2154 /// Creates a `DebugSet` builder designed to assist with creation of
2155 /// `fmt::Debug` implementations for set-like structures.
2156 ///
2157 /// # Examples
2158 ///
2159 /// ```rust
2160 /// use std::fmt;
2161 ///
2162 /// struct Foo(Vec<i32>);
2163 ///
2164 /// impl fmt::Debug for Foo {
2165 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2166 /// fmt.debug_set().entries(self.0.iter()).finish()
2167 /// }
2168 /// }
2169 ///
2170 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2171 /// ```
2172 ///
2173 /// [`format_args!`]: crate::format_args
2174 ///
2175 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2176 /// to build a list of match arms:
2177 ///
2178 /// ```rust
2179 /// use std::fmt;
2180 ///
2181 /// struct Arm<'a, L, R>(&'a (L, R));
2182 /// struct Table<'a, K, V>(&'a [(K, V)], V);
2183 ///
2184 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2185 /// where
2186 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
2187 /// {
2188 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2189 /// L::fmt(&(self.0).0, fmt)?;
2190 /// fmt.write_str(" => ")?;
2191 /// R::fmt(&(self.0).1, fmt)
2192 /// }
2193 /// }
2194 ///
2195 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2196 /// where
2197 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
2198 /// {
2199 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2200 /// fmt.debug_set()
2201 /// .entries(self.0.iter().map(Arm))
2202 /// .entry(&Arm(&(format_args!("_"), &self.1)))
2203 /// .finish()
2204 /// }
2205 /// }
2206 /// ```
2207 #[stable(feature = "debug_builders", since = "1.2.0")]
debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a>2208 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2209 builders::debug_set_new(self)
2210 }
2211
2212 /// Creates a `DebugMap` builder designed to assist with creation of
2213 /// `fmt::Debug` implementations for map-like structures.
2214 ///
2215 /// # Examples
2216 ///
2217 /// ```rust
2218 /// use std::fmt;
2219 ///
2220 /// struct Foo(Vec<(String, i32)>);
2221 ///
2222 /// impl fmt::Debug for Foo {
2223 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2224 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2225 /// }
2226 /// }
2227 ///
2228 /// assert_eq!(
2229 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2230 /// r#"{"A": 10, "B": 11}"#
2231 /// );
2232 /// ```
2233 #[stable(feature = "debug_builders", since = "1.2.0")]
debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a>2234 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2235 builders::debug_map_new(self)
2236 }
2237 }
2238
2239 #[stable(since = "1.2.0", feature = "formatter_write")]
2240 impl Write for Formatter<'_> {
write_str(&mut self, s: &str) -> Result2241 fn write_str(&mut self, s: &str) -> Result {
2242 self.buf.write_str(s)
2243 }
2244
write_char(&mut self, c: char) -> Result2245 fn write_char(&mut self, c: char) -> Result {
2246 self.buf.write_char(c)
2247 }
2248
write_fmt(&mut self, args: Arguments<'_>) -> Result2249 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2250 write(self.buf, args)
2251 }
2252 }
2253
2254 #[stable(feature = "rust1", since = "1.0.0")]
2255 impl Display for Error {
fmt(&self, f: &mut Formatter<'_>) -> Result2256 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2257 Display::fmt("an error occurred when formatting an argument", f)
2258 }
2259 }
2260
2261 // Implementations of the core formatting traits
2262
2263 macro_rules! fmt_refs {
2264 ($($tr:ident),*) => {
2265 $(
2266 #[stable(feature = "rust1", since = "1.0.0")]
2267 impl<T: ?Sized + $tr> $tr for &T {
2268 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2269 }
2270 #[stable(feature = "rust1", since = "1.0.0")]
2271 impl<T: ?Sized + $tr> $tr for &mut T {
2272 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2273 }
2274 )*
2275 }
2276 }
2277
2278 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2279
2280 #[unstable(feature = "never_type", issue = "35121")]
2281 impl Debug for ! {
2282 #[inline]
fmt(&self, _: &mut Formatter<'_>) -> Result2283 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2284 *self
2285 }
2286 }
2287
2288 #[unstable(feature = "never_type", issue = "35121")]
2289 impl Display for ! {
2290 #[inline]
fmt(&self, _: &mut Formatter<'_>) -> Result2291 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2292 *self
2293 }
2294 }
2295
2296 #[stable(feature = "rust1", since = "1.0.0")]
2297 impl Debug for bool {
2298 #[inline]
fmt(&self, f: &mut Formatter<'_>) -> Result2299 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2300 Display::fmt(self, f)
2301 }
2302 }
2303
2304 #[stable(feature = "rust1", since = "1.0.0")]
2305 impl Display for bool {
fmt(&self, f: &mut Formatter<'_>) -> Result2306 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2307 Display::fmt(if *self { "true" } else { "false" }, f)
2308 }
2309 }
2310
2311 #[stable(feature = "rust1", since = "1.0.0")]
2312 impl Debug for str {
fmt(&self, f: &mut Formatter<'_>) -> Result2313 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2314 f.write_char('"')?;
2315 let mut from = 0;
2316 for (i, c) in self.char_indices() {
2317 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2318 escape_grapheme_extended: true,
2319 escape_single_quote: false,
2320 escape_double_quote: true,
2321 });
2322 // If char needs escaping, flush backlog so far and write, else skip
2323 if esc.len() != 1 {
2324 f.write_str(&self[from..i])?;
2325 for c in esc {
2326 f.write_char(c)?;
2327 }
2328 from = i + c.len_utf8();
2329 }
2330 }
2331 f.write_str(&self[from..])?;
2332 f.write_char('"')
2333 }
2334 }
2335
2336 #[stable(feature = "rust1", since = "1.0.0")]
2337 impl Display for str {
fmt(&self, f: &mut Formatter<'_>) -> Result2338 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2339 f.pad(self)
2340 }
2341 }
2342
2343 #[stable(feature = "rust1", since = "1.0.0")]
2344 impl Debug for char {
fmt(&self, f: &mut Formatter<'_>) -> Result2345 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2346 f.write_char('\'')?;
2347 for c in self.escape_debug_ext(EscapeDebugExtArgs {
2348 escape_grapheme_extended: true,
2349 escape_single_quote: true,
2350 escape_double_quote: false,
2351 }) {
2352 f.write_char(c)?
2353 }
2354 f.write_char('\'')
2355 }
2356 }
2357
2358 #[stable(feature = "rust1", since = "1.0.0")]
2359 impl Display for char {
fmt(&self, f: &mut Formatter<'_>) -> Result2360 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2361 if f.width.is_none() && f.precision.is_none() {
2362 f.write_char(*self)
2363 } else {
2364 f.pad(self.encode_utf8(&mut [0; 4]))
2365 }
2366 }
2367 }
2368
2369 #[stable(feature = "rust1", since = "1.0.0")]
2370 impl<T: ?Sized> Pointer for *const T {
fmt(&self, f: &mut Formatter<'_>) -> Result2371 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2372 // Cast is needed here because `.expose_addr()` requires `T: Sized`.
2373 pointer_fmt_inner((*self as *const ()).expose_addr(), f)
2374 }
2375 }
2376
2377 /// Since the formatting will be identical for all pointer types, use a non-monomorphized
2378 /// implementation for the actual formatting to reduce the amount of codegen work needed.
2379 ///
2380 /// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
2381 /// `fn(...) -> ...` without using [problematic] "Oxford Casts".
2382 ///
2383 /// [problematic]: https://github.com/rust-lang/rust/issues/95489
pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result2384 pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
2385 let old_width = f.width;
2386 let old_flags = f.flags;
2387
2388 // The alternate flag is already treated by LowerHex as being special-
2389 // it denotes whether to prefix with 0x. We use it to work out whether
2390 // or not to zero extend, and then unconditionally set it to get the
2391 // prefix.
2392 if f.alternate() {
2393 f.flags |= 1 << (rt::Flag::SignAwareZeroPad as u32);
2394
2395 if f.width.is_none() {
2396 f.width = Some((usize::BITS / 4) as usize + 2);
2397 }
2398 }
2399 f.flags |= 1 << (rt::Flag::Alternate as u32);
2400
2401 let ret = LowerHex::fmt(&ptr_addr, f);
2402
2403 f.width = old_width;
2404 f.flags = old_flags;
2405
2406 ret
2407 }
2408
2409 #[stable(feature = "rust1", since = "1.0.0")]
2410 impl<T: ?Sized> Pointer for *mut T {
fmt(&self, f: &mut Formatter<'_>) -> Result2411 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2412 Pointer::fmt(&(*self as *const T), f)
2413 }
2414 }
2415
2416 #[stable(feature = "rust1", since = "1.0.0")]
2417 impl<T: ?Sized> Pointer for &T {
fmt(&self, f: &mut Formatter<'_>) -> Result2418 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2419 Pointer::fmt(&(*self as *const T), f)
2420 }
2421 }
2422
2423 #[stable(feature = "rust1", since = "1.0.0")]
2424 impl<T: ?Sized> Pointer for &mut T {
fmt(&self, f: &mut Formatter<'_>) -> Result2425 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2426 Pointer::fmt(&(&**self as *const T), f)
2427 }
2428 }
2429
2430 // Implementation of Display/Debug for various core types
2431
2432 #[stable(feature = "rust1", since = "1.0.0")]
2433 impl<T: ?Sized> Debug for *const T {
fmt(&self, f: &mut Formatter<'_>) -> Result2434 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2435 Pointer::fmt(self, f)
2436 }
2437 }
2438 #[stable(feature = "rust1", since = "1.0.0")]
2439 impl<T: ?Sized> Debug for *mut T {
fmt(&self, f: &mut Formatter<'_>) -> Result2440 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2441 Pointer::fmt(self, f)
2442 }
2443 }
2444
2445 macro_rules! peel {
2446 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2447 }
2448
2449 macro_rules! tuple {
2450 () => ();
2451 ( $($name:ident,)+ ) => (
2452 maybe_tuple_doc! {
2453 $($name)+ @
2454 #[stable(feature = "rust1", since = "1.0.0")]
2455 impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2456 #[allow(non_snake_case, unused_assignments)]
2457 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2458 let mut builder = f.debug_tuple("");
2459 let ($(ref $name,)+) = *self;
2460 $(
2461 builder.field(&$name);
2462 )+
2463
2464 builder.finish()
2465 }
2466 }
2467 }
2468 peel! { $($name,)+ }
2469 )
2470 }
2471
2472 macro_rules! maybe_tuple_doc {
2473 ($a:ident @ #[$meta:meta] $item:item) => {
2474 #[doc(fake_variadic)]
2475 #[doc = "This trait is implemented for tuples up to twelve items long."]
2476 #[$meta]
2477 $item
2478 };
2479 ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
2480 #[doc(hidden)]
2481 #[$meta]
2482 $item
2483 };
2484 }
2485
2486 macro_rules! last_type {
2487 ($a:ident,) => { $a };
2488 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2489 }
2490
2491 tuple! { E, D, C, B, A, Z, Y, X, W, V, U, T, }
2492
2493 #[stable(feature = "rust1", since = "1.0.0")]
2494 impl<T: Debug> Debug for [T] {
fmt(&self, f: &mut Formatter<'_>) -> Result2495 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2496 f.debug_list().entries(self.iter()).finish()
2497 }
2498 }
2499
2500 #[stable(feature = "rust1", since = "1.0.0")]
2501 impl Debug for () {
2502 #[inline]
fmt(&self, f: &mut Formatter<'_>) -> Result2503 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2504 f.pad("()")
2505 }
2506 }
2507 #[stable(feature = "rust1", since = "1.0.0")]
2508 impl<T: ?Sized> Debug for PhantomData<T> {
fmt(&self, f: &mut Formatter<'_>) -> Result2509 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2510 write!(f, "PhantomData<{}>", crate::any::type_name::<T>())
2511 }
2512 }
2513
2514 #[stable(feature = "rust1", since = "1.0.0")]
2515 impl<T: Copy + Debug> Debug for Cell<T> {
fmt(&self, f: &mut Formatter<'_>) -> Result2516 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2517 f.debug_struct("Cell").field("value", &self.get()).finish()
2518 }
2519 }
2520
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 impl<T: ?Sized + Debug> Debug for RefCell<T> {
fmt(&self, f: &mut Formatter<'_>) -> Result2523 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2524 match self.try_borrow() {
2525 Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2526 Err(_) => {
2527 // The RefCell is mutably borrowed so we can't look at its value
2528 // here. Show a placeholder instead.
2529 struct BorrowedPlaceholder;
2530
2531 impl Debug for BorrowedPlaceholder {
2532 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2533 f.write_str("<borrowed>")
2534 }
2535 }
2536
2537 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2538 }
2539 }
2540 }
2541 }
2542
2543 #[stable(feature = "rust1", since = "1.0.0")]
2544 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
fmt(&self, f: &mut Formatter<'_>) -> Result2545 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2546 Debug::fmt(&**self, f)
2547 }
2548 }
2549
2550 #[stable(feature = "rust1", since = "1.0.0")]
2551 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
fmt(&self, f: &mut Formatter<'_>) -> Result2552 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2553 Debug::fmt(&*(self.deref()), f)
2554 }
2555 }
2556
2557 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2558 impl<T: ?Sized> Debug for UnsafeCell<T> {
fmt(&self, f: &mut Formatter<'_>) -> Result2559 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2560 f.debug_struct("UnsafeCell").finish_non_exhaustive()
2561 }
2562 }
2563
2564 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2565 impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
fmt(&self, f: &mut Formatter<'_>) -> Result2566 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2567 f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
2568 }
2569 }
2570
2571 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2572 // it's a lot easier than creating all of the rt::Piece structures here.
2573 // There are also tests in the alloc crate, for those that need allocations.
2574