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