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