]> git.proxmox.com Git - rustc.git/blob - library/core/src/fmt/mod.rs
New upstream version 1.51.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::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 std::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][module].
460 ///
461 /// [module]: ../../std/fmt/index.html
462 ///
463 /// This trait can be used with `#[derive]` if all fields implement `Debug`. When
464 /// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
465 /// comma-separated list of each field's name and `Debug` value, then `}`. For
466 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
467 /// `Debug` values of the fields, then `)`.
468 ///
469 /// # Stability
470 ///
471 /// Derived `Debug` formats are not stable, and so may change with future Rust
472 /// versions. Additionally, `Debug` implementations of types provided by the
473 /// standard library (`libstd`, `libcore`, `liballoc`, etc.) are not stable, and
474 /// may also change with future Rust versions.
475 ///
476 /// # Examples
477 ///
478 /// Deriving an implementation:
479 ///
480 /// ```
481 /// #[derive(Debug)]
482 /// struct Point {
483 /// x: i32,
484 /// y: i32,
485 /// }
486 ///
487 /// let origin = Point { x: 0, y: 0 };
488 ///
489 /// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
490 /// ```
491 ///
492 /// Manually implementing:
493 ///
494 /// ```
495 /// use std::fmt;
496 ///
497 /// struct Point {
498 /// x: i32,
499 /// y: i32,
500 /// }
501 ///
502 /// impl fmt::Debug for Point {
503 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504 /// f.debug_struct("Point")
505 /// .field("x", &self.x)
506 /// .field("y", &self.y)
507 /// .finish()
508 /// }
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 /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
517 /// implementations, such as [`debug_struct`].
518 ///
519 /// `Debug` implementations using either `derive` or the debug builder API
520 /// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
521 ///
522 /// [`debug_struct`]: Formatter::debug_struct
523 ///
524 /// Pretty-printing with `#?`:
525 ///
526 /// ```
527 /// #[derive(Debug)]
528 /// struct Point {
529 /// x: i32,
530 /// y: i32,
531 /// }
532 ///
533 /// let origin = Point { x: 0, y: 0 };
534 ///
535 /// assert_eq!(format!("The origin is: {:#?}", origin),
536 /// "The origin is: Point {
537 /// x: 0,
538 /// y: 0,
539 /// }");
540 /// ```
541
542 #[stable(feature = "rust1", since = "1.0.0")]
543 #[rustc_on_unimplemented(
544 on(
545 crate_local,
546 label = "`{Self}` cannot be formatted using `{{:?}}`",
547 note = "add `#[derive(Debug)]` or manually implement `{Debug}`"
548 ),
549 message = "`{Self}` doesn't implement `{Debug}`",
550 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
551 )]
552 #[doc(alias = "{:?}")]
553 #[rustc_diagnostic_item = "debug_trait"]
554 pub trait Debug {
555 /// Formats the value using the given formatter.
556 ///
557 /// # Examples
558 ///
559 /// ```
560 /// use std::fmt;
561 ///
562 /// struct Position {
563 /// longitude: f32,
564 /// latitude: f32,
565 /// }
566 ///
567 /// impl fmt::Debug for Position {
568 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
569 /// f.debug_tuple("")
570 /// .field(&self.longitude)
571 /// .field(&self.latitude)
572 /// .finish()
573 /// }
574 /// }
575 ///
576 /// let position = Position { longitude: 1.987, latitude: 2.983 };
577 /// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
578 ///
579 /// assert_eq!(format!("{:#?}", position), "(
580 /// 1.987,
581 /// 2.983,
582 /// )");
583 /// ```
584 #[stable(feature = "rust1", since = "1.0.0")]
585 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
586 }
587
588 // Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
589 pub(crate) mod macros {
590 /// Derive macro generating an impl of the trait `Debug`.
591 #[rustc_builtin_macro]
592 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
593 #[allow_internal_unstable(core_intrinsics)]
594 pub macro Debug($item:item) {
595 /* compiler built-in */
596 }
597 }
598 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
599 #[doc(inline)]
600 pub use macros::Debug;
601
602 /// Format trait for an empty format, `{}`.
603 ///
604 /// `Display` is similar to [`Debug`], but `Display` is for user-facing
605 /// output, and so cannot be derived.
606 ///
607 /// For more information on formatters, see [the module-level documentation][module].
608 ///
609 /// [module]: ../../std/fmt/index.html
610 ///
611 /// # Examples
612 ///
613 /// Implementing `Display` on a type:
614 ///
615 /// ```
616 /// use std::fmt;
617 ///
618 /// struct Point {
619 /// x: i32,
620 /// y: i32,
621 /// }
622 ///
623 /// impl fmt::Display for Point {
624 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
625 /// write!(f, "({}, {})", self.x, self.y)
626 /// }
627 /// }
628 ///
629 /// let origin = Point { x: 0, y: 0 };
630 ///
631 /// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
632 /// ```
633 #[rustc_on_unimplemented(
634 on(
635 _Self = "std::path::Path",
636 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
637 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
638 as they may contain non-Unicode data"
639 ),
640 message = "`{Self}` doesn't implement `{Display}`",
641 label = "`{Self}` cannot be formatted with the default formatter",
642 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
643 )]
644 #[doc(alias = "{}")]
645 #[stable(feature = "rust1", since = "1.0.0")]
646 pub trait Display {
647 /// Formats the value using the given formatter.
648 ///
649 /// # Examples
650 ///
651 /// ```
652 /// use std::fmt;
653 ///
654 /// struct Position {
655 /// longitude: f32,
656 /// latitude: f32,
657 /// }
658 ///
659 /// impl fmt::Display for Position {
660 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661 /// write!(f, "({}, {})", self.longitude, self.latitude)
662 /// }
663 /// }
664 ///
665 /// assert_eq!("(1.987, 2.983)",
666 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }));
667 /// ```
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
670 }
671
672 /// `o` formatting.
673 ///
674 /// The `Octal` trait should format its output as a number in base-8.
675 ///
676 /// For primitive signed integers (`i8` to `i128`, and `isize`),
677 /// negative values are formatted as the two’s complement representation.
678 ///
679 /// The alternate flag, `#`, adds a `0o` in front of the output.
680 ///
681 /// For more information on formatters, see [the module-level documentation][module].
682 ///
683 /// [module]: ../../std/fmt/index.html
684 ///
685 /// # Examples
686 ///
687 /// Basic usage with `i32`:
688 ///
689 /// ```
690 /// let x = 42; // 42 is '52' in octal
691 ///
692 /// assert_eq!(format!("{:o}", x), "52");
693 /// assert_eq!(format!("{:#o}", x), "0o52");
694 ///
695 /// assert_eq!(format!("{:o}", -16), "37777777760");
696 /// ```
697 ///
698 /// Implementing `Octal` on a type:
699 ///
700 /// ```
701 /// use std::fmt;
702 ///
703 /// struct Length(i32);
704 ///
705 /// impl fmt::Octal for Length {
706 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707 /// let val = self.0;
708 ///
709 /// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
710 /// }
711 /// }
712 ///
713 /// let l = Length(9);
714 ///
715 /// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
716 ///
717 /// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
718 /// ```
719 #[stable(feature = "rust1", since = "1.0.0")]
720 pub trait Octal {
721 /// Formats the value using the given formatter.
722 #[stable(feature = "rust1", since = "1.0.0")]
723 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
724 }
725
726 /// `b` formatting.
727 ///
728 /// The `Binary` trait should format its output as a number in binary.
729 ///
730 /// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
731 /// negative values are formatted as the two’s complement representation.
732 ///
733 /// The alternate flag, `#`, adds a `0b` in front of the output.
734 ///
735 /// For more information on formatters, see [the module-level documentation][module].
736 ///
737 /// [module]: ../../std/fmt/index.html
738 ///
739 /// # Examples
740 ///
741 /// Basic usage with [`i32`]:
742 ///
743 /// ```
744 /// let x = 42; // 42 is '101010' in binary
745 ///
746 /// assert_eq!(format!("{:b}", x), "101010");
747 /// assert_eq!(format!("{:#b}", x), "0b101010");
748 ///
749 /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
750 /// ```
751 ///
752 /// Implementing `Binary` on a type:
753 ///
754 /// ```
755 /// use std::fmt;
756 ///
757 /// struct Length(i32);
758 ///
759 /// impl fmt::Binary for Length {
760 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
761 /// let val = self.0;
762 ///
763 /// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
764 /// }
765 /// }
766 ///
767 /// let l = Length(107);
768 ///
769 /// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
770 ///
771 /// assert_eq!(
772 /// format!("l as binary is: {:#032b}", l),
773 /// "l as binary is: 0b000000000000000000000001101011"
774 /// );
775 /// ```
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub trait Binary {
778 /// Formats the value using the given formatter.
779 #[stable(feature = "rust1", since = "1.0.0")]
780 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
781 }
782
783 /// `x` formatting.
784 ///
785 /// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
786 /// in lower case.
787 ///
788 /// For primitive signed integers (`i8` to `i128`, and `isize`),
789 /// negative values are formatted as the two’s complement representation.
790 ///
791 /// The alternate flag, `#`, adds a `0x` in front of the output.
792 ///
793 /// For more information on formatters, see [the module-level documentation][module].
794 ///
795 /// [module]: ../../std/fmt/index.html
796 ///
797 /// # Examples
798 ///
799 /// Basic usage with `i32`:
800 ///
801 /// ```
802 /// let x = 42; // 42 is '2a' in hex
803 ///
804 /// assert_eq!(format!("{:x}", x), "2a");
805 /// assert_eq!(format!("{:#x}", x), "0x2a");
806 ///
807 /// assert_eq!(format!("{:x}", -16), "fffffff0");
808 /// ```
809 ///
810 /// Implementing `LowerHex` on a type:
811 ///
812 /// ```
813 /// use std::fmt;
814 ///
815 /// struct Length(i32);
816 ///
817 /// impl fmt::LowerHex for Length {
818 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
819 /// let val = self.0;
820 ///
821 /// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
822 /// }
823 /// }
824 ///
825 /// let l = Length(9);
826 ///
827 /// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
828 ///
829 /// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
830 /// ```
831 #[stable(feature = "rust1", since = "1.0.0")]
832 pub trait LowerHex {
833 /// Formats the value using the given formatter.
834 #[stable(feature = "rust1", since = "1.0.0")]
835 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
836 }
837
838 /// `X` formatting.
839 ///
840 /// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
841 /// in upper case.
842 ///
843 /// For primitive signed integers (`i8` to `i128`, and `isize`),
844 /// negative values are formatted as the two’s complement representation.
845 ///
846 /// The alternate flag, `#`, adds a `0x` in front of the output.
847 ///
848 /// For more information on formatters, see [the module-level documentation][module].
849 ///
850 /// [module]: ../../std/fmt/index.html
851 ///
852 /// # Examples
853 ///
854 /// Basic usage with `i32`:
855 ///
856 /// ```
857 /// let x = 42; // 42 is '2A' in hex
858 ///
859 /// assert_eq!(format!("{:X}", x), "2A");
860 /// assert_eq!(format!("{:#X}", x), "0x2A");
861 ///
862 /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
863 /// ```
864 ///
865 /// Implementing `UpperHex` on a type:
866 ///
867 /// ```
868 /// use std::fmt;
869 ///
870 /// struct Length(i32);
871 ///
872 /// impl fmt::UpperHex for Length {
873 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
874 /// let val = self.0;
875 ///
876 /// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
877 /// }
878 /// }
879 ///
880 /// let l = Length(i32::MAX);
881 ///
882 /// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
883 ///
884 /// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
885 /// ```
886 #[stable(feature = "rust1", since = "1.0.0")]
887 pub trait UpperHex {
888 /// Formats the value using the given formatter.
889 #[stable(feature = "rust1", since = "1.0.0")]
890 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
891 }
892
893 /// `p` formatting.
894 ///
895 /// The `Pointer` trait should format its output as a memory location. This is commonly presented
896 /// as hexadecimal.
897 ///
898 /// For more information on formatters, see [the module-level documentation][module].
899 ///
900 /// [module]: ../../std/fmt/index.html
901 ///
902 /// # Examples
903 ///
904 /// Basic usage with `&i32`:
905 ///
906 /// ```
907 /// let x = &42;
908 ///
909 /// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
910 /// ```
911 ///
912 /// Implementing `Pointer` on a type:
913 ///
914 /// ```
915 /// use std::fmt;
916 ///
917 /// struct Length(i32);
918 ///
919 /// impl fmt::Pointer for Length {
920 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
921 /// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
922 ///
923 /// let ptr = self as *const Self;
924 /// fmt::Pointer::fmt(&ptr, f)
925 /// }
926 /// }
927 ///
928 /// let l = Length(42);
929 ///
930 /// println!("l is in memory here: {:p}", l);
931 ///
932 /// let l_ptr = format!("{:018p}", l);
933 /// assert_eq!(l_ptr.len(), 18);
934 /// assert_eq!(&l_ptr[..2], "0x");
935 /// ```
936 #[stable(feature = "rust1", since = "1.0.0")]
937 #[rustc_diagnostic_item = "pointer_trait"]
938 pub trait Pointer {
939 /// Formats the value using the given formatter.
940 #[stable(feature = "rust1", since = "1.0.0")]
941 #[rustc_diagnostic_item = "pointer_trait_fmt"]
942 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
943 }
944
945 /// `e` formatting.
946 ///
947 /// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
948 ///
949 /// For more information on formatters, see [the module-level documentation][module].
950 ///
951 /// [module]: ../../std/fmt/index.html
952 ///
953 /// # Examples
954 ///
955 /// Basic usage with `f64`:
956 ///
957 /// ```
958 /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
959 ///
960 /// assert_eq!(format!("{:e}", x), "4.2e1");
961 /// ```
962 ///
963 /// Implementing `LowerExp` on a type:
964 ///
965 /// ```
966 /// use std::fmt;
967 ///
968 /// struct Length(i32);
969 ///
970 /// impl fmt::LowerExp for Length {
971 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
972 /// let val = f64::from(self.0);
973 /// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
974 /// }
975 /// }
976 ///
977 /// let l = Length(100);
978 ///
979 /// assert_eq!(
980 /// format!("l in scientific notation is: {:e}", l),
981 /// "l in scientific notation is: 1e2"
982 /// );
983 ///
984 /// assert_eq!(
985 /// format!("l in scientific notation is: {:05e}", l),
986 /// "l in scientific notation is: 001e2"
987 /// );
988 /// ```
989 #[stable(feature = "rust1", since = "1.0.0")]
990 pub trait LowerExp {
991 /// Formats the value using the given formatter.
992 #[stable(feature = "rust1", since = "1.0.0")]
993 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
994 }
995
996 /// `E` formatting.
997 ///
998 /// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
999 ///
1000 /// For more information on formatters, see [the module-level documentation][module].
1001 ///
1002 /// [module]: ../../std/fmt/index.html
1003 ///
1004 /// # Examples
1005 ///
1006 /// Basic usage with `f64`:
1007 ///
1008 /// ```
1009 /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1010 ///
1011 /// assert_eq!(format!("{:E}", x), "4.2E1");
1012 /// ```
1013 ///
1014 /// Implementing `UpperExp` on a type:
1015 ///
1016 /// ```
1017 /// use std::fmt;
1018 ///
1019 /// struct Length(i32);
1020 ///
1021 /// impl fmt::UpperExp for Length {
1022 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1023 /// let val = f64::from(self.0);
1024 /// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1025 /// }
1026 /// }
1027 ///
1028 /// let l = Length(100);
1029 ///
1030 /// assert_eq!(
1031 /// format!("l in scientific notation is: {:E}", l),
1032 /// "l in scientific notation is: 1E2"
1033 /// );
1034 ///
1035 /// assert_eq!(
1036 /// format!("l in scientific notation is: {:05E}", l),
1037 /// "l in scientific notation is: 001E2"
1038 /// );
1039 /// ```
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 pub trait UpperExp {
1042 /// Formats the value using the given formatter.
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1045 }
1046
1047 /// The `write` function takes an output stream, and an `Arguments` struct
1048 /// that can be precompiled with the `format_args!` macro.
1049 ///
1050 /// The arguments will be formatted according to the specified format string
1051 /// into the output stream provided.
1052 ///
1053 /// # Examples
1054 ///
1055 /// Basic usage:
1056 ///
1057 /// ```
1058 /// use std::fmt;
1059 ///
1060 /// let mut output = String::new();
1061 /// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1062 /// .expect("Error occurred while trying to write in String");
1063 /// assert_eq!(output, "Hello world!");
1064 /// ```
1065 ///
1066 /// Please note that using [`write!`] might be preferable. Example:
1067 ///
1068 /// ```
1069 /// use std::fmt::Write;
1070 ///
1071 /// let mut output = String::new();
1072 /// write!(&mut output, "Hello {}!", "world")
1073 /// .expect("Error occurred while trying to write in String");
1074 /// assert_eq!(output, "Hello world!");
1075 /// ```
1076 ///
1077 /// [`write!`]: crate::write!
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1080 let mut formatter = Formatter {
1081 flags: 0,
1082 width: None,
1083 precision: None,
1084 buf: output,
1085 align: rt::v1::Alignment::Unknown,
1086 fill: ' ',
1087 };
1088
1089 let mut idx = 0;
1090
1091 match args.fmt {
1092 None => {
1093 // We can use default formatting parameters for all arguments.
1094 for (arg, piece) in args.args.iter().zip(args.pieces.iter()) {
1095 formatter.buf.write_str(*piece)?;
1096 (arg.formatter)(arg.value, &mut formatter)?;
1097 idx += 1;
1098 }
1099 }
1100 Some(fmt) => {
1101 // Every spec has a corresponding argument that is preceded by
1102 // a string piece.
1103 for (arg, piece) in fmt.iter().zip(args.pieces.iter()) {
1104 formatter.buf.write_str(*piece)?;
1105 // SAFETY: arg and args.args come from the same Arguments,
1106 // which guarantees the indexes are always within bounds.
1107 unsafe { run(&mut formatter, arg, &args.args) }?;
1108 idx += 1;
1109 }
1110 }
1111 }
1112
1113 // There can be only one trailing string piece left.
1114 if let Some(piece) = args.pieces.get(idx) {
1115 formatter.buf.write_str(*piece)?;
1116 }
1117
1118 Ok(())
1119 }
1120
1121 unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result {
1122 fmt.fill = arg.format.fill;
1123 fmt.align = arg.format.align;
1124 fmt.flags = arg.format.flags;
1125 // SAFETY: arg and args come from the same Arguments,
1126 // which guarantees the indexes are always within bounds.
1127 unsafe {
1128 fmt.width = getcount(args, &arg.format.width);
1129 fmt.precision = getcount(args, &arg.format.precision);
1130 }
1131
1132 // Extract the correct argument
1133 debug_assert!(arg.position < args.len());
1134 // SAFETY: arg and args come from the same Arguments,
1135 // which guarantees its index is always within bounds.
1136 let value = unsafe { args.get_unchecked(arg.position) };
1137
1138 // Then actually do some printing
1139 (value.formatter)(value.value, fmt)
1140 }
1141
1142 unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option<usize> {
1143 match *cnt {
1144 rt::v1::Count::Is(n) => Some(n),
1145 rt::v1::Count::Implied => None,
1146 rt::v1::Count::Param(i) => {
1147 debug_assert!(i < args.len());
1148 // SAFETY: cnt and args come from the same Arguments,
1149 // which guarantees this index is always within bounds.
1150 unsafe { args.get_unchecked(i).as_usize() }
1151 }
1152 }
1153 }
1154
1155 /// Padding after the end of something. Returned by `Formatter::padding`.
1156 #[must_use = "don't forget to write the post padding"]
1157 struct PostPadding {
1158 fill: char,
1159 padding: usize,
1160 }
1161
1162 impl PostPadding {
1163 fn new(fill: char, padding: usize) -> PostPadding {
1164 PostPadding { fill, padding }
1165 }
1166
1167 /// Write this post padding.
1168 fn write(self, buf: &mut dyn Write) -> Result {
1169 for _ in 0..self.padding {
1170 buf.write_char(self.fill)?;
1171 }
1172 Ok(())
1173 }
1174 }
1175
1176 impl<'a> Formatter<'a> {
1177 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1178 where
1179 'b: 'c,
1180 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1181 {
1182 Formatter {
1183 // We want to change this
1184 buf: wrap(self.buf),
1185
1186 // And preserve these
1187 flags: self.flags,
1188 fill: self.fill,
1189 align: self.align,
1190 width: self.width,
1191 precision: self.precision,
1192 }
1193 }
1194
1195 // Helper methods used for padding and processing formatting arguments that
1196 // all formatting traits can use.
1197
1198 /// Performs the correct padding for an integer which has already been
1199 /// emitted into a str. The str should *not* contain the sign for the
1200 /// integer, that will be added by this method.
1201 ///
1202 /// # Arguments
1203 ///
1204 /// * is_nonnegative - whether the original integer was either positive or zero.
1205 /// * prefix - if the '#' character (Alternate) is provided, this
1206 /// is the prefix to put in front of the number.
1207 /// * buf - the byte array that the number has been formatted into
1208 ///
1209 /// This function will correctly account for the flags provided as well as
1210 /// the minimum width. It will not take precision into account.
1211 ///
1212 /// # Examples
1213 ///
1214 /// ```
1215 /// use std::fmt;
1216 ///
1217 /// struct Foo { nb: i32 }
1218 ///
1219 /// impl Foo {
1220 /// fn new(nb: i32) -> Foo {
1221 /// Foo {
1222 /// nb,
1223 /// }
1224 /// }
1225 /// }
1226 ///
1227 /// impl fmt::Display for Foo {
1228 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1229 /// // We need to remove "-" from the number output.
1230 /// let tmp = self.nb.abs().to_string();
1231 ///
1232 /// formatter.pad_integral(self.nb > 0, "Foo ", &tmp)
1233 /// }
1234 /// }
1235 ///
1236 /// assert_eq!(&format!("{}", Foo::new(2)), "2");
1237 /// assert_eq!(&format!("{}", Foo::new(-1)), "-1");
1238 /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1");
1239 /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1240 /// ```
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1243 let mut width = buf.len();
1244
1245 let mut sign = None;
1246 if !is_nonnegative {
1247 sign = Some('-');
1248 width += 1;
1249 } else if self.sign_plus() {
1250 sign = Some('+');
1251 width += 1;
1252 }
1253
1254 let prefix = if self.alternate() {
1255 width += prefix.chars().count();
1256 Some(prefix)
1257 } else {
1258 None
1259 };
1260
1261 // Writes the sign if it exists, and then the prefix if it was requested
1262 #[inline(never)]
1263 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1264 if let Some(c) = sign {
1265 f.buf.write_char(c)?;
1266 }
1267 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1268 }
1269
1270 // The `width` field is more of a `min-width` parameter at this point.
1271 match self.width {
1272 // If there's no minimum length requirements then we can just
1273 // write the bytes.
1274 None => {
1275 write_prefix(self, sign, prefix)?;
1276 self.buf.write_str(buf)
1277 }
1278 // Check if we're over the minimum width, if so then we can also
1279 // just write the bytes.
1280 Some(min) if width >= min => {
1281 write_prefix(self, sign, prefix)?;
1282 self.buf.write_str(buf)
1283 }
1284 // The sign and prefix goes before the padding if the fill character
1285 // is zero
1286 Some(min) if self.sign_aware_zero_pad() => {
1287 let old_fill = crate::mem::replace(&mut self.fill, '0');
1288 let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right);
1289 write_prefix(self, sign, prefix)?;
1290 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1291 self.buf.write_str(buf)?;
1292 post_padding.write(self.buf)?;
1293 self.fill = old_fill;
1294 self.align = old_align;
1295 Ok(())
1296 }
1297 // Otherwise, the sign and prefix goes after the padding
1298 Some(min) => {
1299 let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?;
1300 write_prefix(self, sign, prefix)?;
1301 self.buf.write_str(buf)?;
1302 post_padding.write(self.buf)
1303 }
1304 }
1305 }
1306
1307 /// This function takes a string slice and emits it to the internal buffer
1308 /// after applying the relevant formatting flags specified. The flags
1309 /// recognized for generic strings are:
1310 ///
1311 /// * width - the minimum width of what to emit
1312 /// * fill/align - what to emit and where to emit it if the string
1313 /// provided needs to be padded
1314 /// * precision - the maximum length to emit, the string is truncated if it
1315 /// is longer than this length
1316 ///
1317 /// Notably this function ignores the `flag` parameters.
1318 ///
1319 /// # Examples
1320 ///
1321 /// ```
1322 /// use std::fmt;
1323 ///
1324 /// struct Foo;
1325 ///
1326 /// impl fmt::Display for Foo {
1327 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1328 /// formatter.pad("Foo")
1329 /// }
1330 /// }
1331 ///
1332 /// assert_eq!(&format!("{:<4}", Foo), "Foo ");
1333 /// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
1334 /// ```
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 pub fn pad(&mut self, s: &str) -> Result {
1337 // Make sure there's a fast path up front
1338 if self.width.is_none() && self.precision.is_none() {
1339 return self.buf.write_str(s);
1340 }
1341 // The `precision` field can be interpreted as a `max-width` for the
1342 // string being formatted.
1343 let s = if let Some(max) = self.precision {
1344 // If our string is longer that the precision, then we must have
1345 // truncation. However other flags like `fill`, `width` and `align`
1346 // must act as always.
1347 if let Some((i, _)) = s.char_indices().nth(max) {
1348 // LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1349 // we know that it can't panic. Use `get` + `unwrap_or` to avoid
1350 // `unsafe` and otherwise don't emit any panic-related code
1351 // here.
1352 s.get(..i).unwrap_or(&s)
1353 } else {
1354 &s
1355 }
1356 } else {
1357 &s
1358 };
1359 // The `width` field is more of a `min-width` parameter at this point.
1360 match self.width {
1361 // If we're under the maximum length, and there's no minimum length
1362 // requirements, then we can just emit the string
1363 None => self.buf.write_str(s),
1364 // If we're under the maximum width, check if we're over the minimum
1365 // width, if so it's as easy as just emitting the string.
1366 Some(width) if s.chars().count() >= width => self.buf.write_str(s),
1367 // If we're under both the maximum and the minimum width, then fill
1368 // up the minimum width with the specified string + some alignment.
1369 Some(width) => {
1370 let align = rt::v1::Alignment::Left;
1371 let post_padding = self.padding(width - s.chars().count(), align)?;
1372 self.buf.write_str(s)?;
1373 post_padding.write(self.buf)
1374 }
1375 }
1376 }
1377
1378 /// Write the pre-padding and return the unwritten post-padding. Callers are
1379 /// responsible for ensuring post-padding is written after the thing that is
1380 /// being padded.
1381 fn padding(
1382 &mut self,
1383 padding: usize,
1384 default: rt::v1::Alignment,
1385 ) -> result::Result<PostPadding, Error> {
1386 let align = match self.align {
1387 rt::v1::Alignment::Unknown => default,
1388 _ => self.align,
1389 };
1390
1391 let (pre_pad, post_pad) = match align {
1392 rt::v1::Alignment::Left => (0, padding),
1393 rt::v1::Alignment::Right | rt::v1::Alignment::Unknown => (padding, 0),
1394 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1395 };
1396
1397 for _ in 0..pre_pad {
1398 self.buf.write_char(self.fill)?;
1399 }
1400
1401 Ok(PostPadding::new(self.fill, post_pad))
1402 }
1403
1404 /// Takes the formatted parts and applies the padding.
1405 /// Assumes that the caller already has rendered the parts with required precision,
1406 /// so that `self.precision` can be ignored.
1407 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted<'_>) -> Result {
1408 if let Some(mut width) = self.width {
1409 // for the sign-aware zero padding, we render the sign first and
1410 // behave as if we had no sign from the beginning.
1411 let mut formatted = formatted.clone();
1412 let old_fill = self.fill;
1413 let old_align = self.align;
1414 let mut align = old_align;
1415 if self.sign_aware_zero_pad() {
1416 // a sign always goes first
1417 let sign = formatted.sign;
1418 self.buf.write_str(sign)?;
1419
1420 // remove the sign from the formatted parts
1421 formatted.sign = "";
1422 width = width.saturating_sub(sign.len());
1423 align = rt::v1::Alignment::Right;
1424 self.fill = '0';
1425 self.align = rt::v1::Alignment::Right;
1426 }
1427
1428 // remaining parts go through the ordinary padding process.
1429 let len = formatted.len();
1430 let ret = if width <= len {
1431 // no padding
1432 self.write_formatted_parts(&formatted)
1433 } else {
1434 let post_padding = self.padding(width - len, align)?;
1435 self.write_formatted_parts(&formatted)?;
1436 post_padding.write(self.buf)
1437 };
1438 self.fill = old_fill;
1439 self.align = old_align;
1440 ret
1441 } else {
1442 // this is the common case and we take a shortcut
1443 self.write_formatted_parts(formatted)
1444 }
1445 }
1446
1447 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted<'_>) -> Result {
1448 fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1449 // SAFETY: This is used for `flt2dec::Part::Num` and `flt2dec::Part::Copy`.
1450 // It's safe to use for `flt2dec::Part::Num` since every char `c` is between
1451 // `b'0'` and `b'9'`, which means `s` is valid UTF-8.
1452 // It's also probably safe in practice to use for `flt2dec::Part::Copy(buf)`
1453 // since `buf` should be plain ASCII, but it's possible for someone to pass
1454 // in a bad value for `buf` into `flt2dec::to_shortest_str` since it is a
1455 // public function.
1456 // FIXME: Determine whether this could result in UB.
1457 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1458 }
1459
1460 if !formatted.sign.is_empty() {
1461 self.buf.write_str(formatted.sign)?;
1462 }
1463 for part in formatted.parts {
1464 match *part {
1465 flt2dec::Part::Zero(mut nzeroes) => {
1466 const ZEROES: &str = // 64 zeroes
1467 "0000000000000000000000000000000000000000000000000000000000000000";
1468 while nzeroes > ZEROES.len() {
1469 self.buf.write_str(ZEROES)?;
1470 nzeroes -= ZEROES.len();
1471 }
1472 if nzeroes > 0 {
1473 self.buf.write_str(&ZEROES[..nzeroes])?;
1474 }
1475 }
1476 flt2dec::Part::Num(mut v) => {
1477 let mut s = [0; 5];
1478 let len = part.len();
1479 for c in s[..len].iter_mut().rev() {
1480 *c = b'0' + (v % 10) as u8;
1481 v /= 10;
1482 }
1483 write_bytes(self.buf, &s[..len])?;
1484 }
1485 flt2dec::Part::Copy(buf) => {
1486 write_bytes(self.buf, buf)?;
1487 }
1488 }
1489 }
1490 Ok(())
1491 }
1492
1493 /// Writes some data to the underlying buffer contained within this
1494 /// formatter.
1495 ///
1496 /// # Examples
1497 ///
1498 /// ```
1499 /// use std::fmt;
1500 ///
1501 /// struct Foo;
1502 ///
1503 /// impl fmt::Display for Foo {
1504 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1505 /// formatter.write_str("Foo")
1506 /// // This is equivalent to:
1507 /// // write!(formatter, "Foo")
1508 /// }
1509 /// }
1510 ///
1511 /// assert_eq!(&format!("{}", Foo), "Foo");
1512 /// assert_eq!(&format!("{:0>8}", Foo), "Foo");
1513 /// ```
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 pub fn write_str(&mut self, data: &str) -> Result {
1516 self.buf.write_str(data)
1517 }
1518
1519 /// Writes some formatted information into this instance.
1520 ///
1521 /// # Examples
1522 ///
1523 /// ```
1524 /// use std::fmt;
1525 ///
1526 /// struct Foo(i32);
1527 ///
1528 /// impl fmt::Display for Foo {
1529 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1530 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1531 /// }
1532 /// }
1533 ///
1534 /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1");
1535 /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2");
1536 /// ```
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1539 write(self.buf, fmt)
1540 }
1541
1542 /// Flags for formatting
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 #[rustc_deprecated(
1545 since = "1.24.0",
1546 reason = "use the `sign_plus`, `sign_minus`, `alternate`, \
1547 or `sign_aware_zero_pad` methods instead"
1548 )]
1549 pub fn flags(&self) -> u32 {
1550 self.flags
1551 }
1552
1553 /// Character used as 'fill' whenever there is alignment.
1554 ///
1555 /// # Examples
1556 ///
1557 /// ```
1558 /// use std::fmt;
1559 ///
1560 /// struct Foo;
1561 ///
1562 /// impl fmt::Display for Foo {
1563 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1564 /// let c = formatter.fill();
1565 /// if let Some(width) = formatter.width() {
1566 /// for _ in 0..width {
1567 /// write!(formatter, "{}", c)?;
1568 /// }
1569 /// Ok(())
1570 /// } else {
1571 /// write!(formatter, "{}", c)
1572 /// }
1573 /// }
1574 /// }
1575 ///
1576 /// // We set alignment to the right with ">".
1577 /// assert_eq!(&format!("{:G>3}", Foo), "GGG");
1578 /// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
1579 /// ```
1580 #[stable(feature = "fmt_flags", since = "1.5.0")]
1581 pub fn fill(&self) -> char {
1582 self.fill
1583 }
1584
1585 /// Flag indicating what form of alignment was requested.
1586 ///
1587 /// # Examples
1588 ///
1589 /// ```
1590 /// extern crate core;
1591 ///
1592 /// use std::fmt::{self, Alignment};
1593 ///
1594 /// struct Foo;
1595 ///
1596 /// impl fmt::Display for Foo {
1597 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1598 /// let s = if let Some(s) = formatter.align() {
1599 /// match s {
1600 /// Alignment::Left => "left",
1601 /// Alignment::Right => "right",
1602 /// Alignment::Center => "center",
1603 /// }
1604 /// } else {
1605 /// "into the void"
1606 /// };
1607 /// write!(formatter, "{}", s)
1608 /// }
1609 /// }
1610 ///
1611 /// assert_eq!(&format!("{:<}", Foo), "left");
1612 /// assert_eq!(&format!("{:>}", Foo), "right");
1613 /// assert_eq!(&format!("{:^}", Foo), "center");
1614 /// assert_eq!(&format!("{}", Foo), "into the void");
1615 /// ```
1616 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
1617 pub fn align(&self) -> Option<Alignment> {
1618 match self.align {
1619 rt::v1::Alignment::Left => Some(Alignment::Left),
1620 rt::v1::Alignment::Right => Some(Alignment::Right),
1621 rt::v1::Alignment::Center => Some(Alignment::Center),
1622 rt::v1::Alignment::Unknown => None,
1623 }
1624 }
1625
1626 /// Optionally specified integer width that the output should be.
1627 ///
1628 /// # Examples
1629 ///
1630 /// ```
1631 /// use std::fmt;
1632 ///
1633 /// struct Foo(i32);
1634 ///
1635 /// impl fmt::Display for Foo {
1636 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1637 /// if let Some(width) = formatter.width() {
1638 /// // If we received a width, we use it
1639 /// write!(formatter, "{:width$}", &format!("Foo({})", self.0), width = width)
1640 /// } else {
1641 /// // Otherwise we do nothing special
1642 /// write!(formatter, "Foo({})", self.0)
1643 /// }
1644 /// }
1645 /// }
1646 ///
1647 /// assert_eq!(&format!("{:10}", Foo(23)), "Foo(23) ");
1648 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1649 /// ```
1650 #[stable(feature = "fmt_flags", since = "1.5.0")]
1651 pub fn width(&self) -> Option<usize> {
1652 self.width
1653 }
1654
1655 /// Optionally specified precision for numeric types. Alternatively, the
1656 /// maximum width for string types.
1657 ///
1658 /// # Examples
1659 ///
1660 /// ```
1661 /// use std::fmt;
1662 ///
1663 /// struct Foo(f32);
1664 ///
1665 /// impl fmt::Display for Foo {
1666 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1667 /// if let Some(precision) = formatter.precision() {
1668 /// // If we received a precision, we use it.
1669 /// write!(formatter, "Foo({1:.*})", precision, self.0)
1670 /// } else {
1671 /// // Otherwise we default to 2.
1672 /// write!(formatter, "Foo({:.2})", self.0)
1673 /// }
1674 /// }
1675 /// }
1676 ///
1677 /// assert_eq!(&format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
1678 /// assert_eq!(&format!("{}", Foo(23.2)), "Foo(23.20)");
1679 /// ```
1680 #[stable(feature = "fmt_flags", since = "1.5.0")]
1681 pub fn precision(&self) -> Option<usize> {
1682 self.precision
1683 }
1684
1685 /// Determines if the `+` flag was specified.
1686 ///
1687 /// # Examples
1688 ///
1689 /// ```
1690 /// use std::fmt;
1691 ///
1692 /// struct Foo(i32);
1693 ///
1694 /// impl fmt::Display for Foo {
1695 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1696 /// if formatter.sign_plus() {
1697 /// write!(formatter,
1698 /// "Foo({}{})",
1699 /// if self.0 < 0 { '-' } else { '+' },
1700 /// self.0)
1701 /// } else {
1702 /// write!(formatter, "Foo({})", self.0)
1703 /// }
1704 /// }
1705 /// }
1706 ///
1707 /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
1708 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1709 /// ```
1710 #[stable(feature = "fmt_flags", since = "1.5.0")]
1711 pub fn sign_plus(&self) -> bool {
1712 self.flags & (1 << FlagV1::SignPlus as u32) != 0
1713 }
1714
1715 /// Determines if the `-` flag was specified.
1716 ///
1717 /// # Examples
1718 ///
1719 /// ```
1720 /// use std::fmt;
1721 ///
1722 /// struct Foo(i32);
1723 ///
1724 /// impl fmt::Display for Foo {
1725 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1726 /// if formatter.sign_minus() {
1727 /// // You want a minus sign? Have one!
1728 /// write!(formatter, "-Foo({})", self.0)
1729 /// } else {
1730 /// write!(formatter, "Foo({})", self.0)
1731 /// }
1732 /// }
1733 /// }
1734 ///
1735 /// assert_eq!(&format!("{:-}", Foo(23)), "-Foo(23)");
1736 /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
1737 /// ```
1738 #[stable(feature = "fmt_flags", since = "1.5.0")]
1739 pub fn sign_minus(&self) -> bool {
1740 self.flags & (1 << FlagV1::SignMinus as u32) != 0
1741 }
1742
1743 /// Determines if the `#` flag was specified.
1744 ///
1745 /// # Examples
1746 ///
1747 /// ```
1748 /// use std::fmt;
1749 ///
1750 /// struct Foo(i32);
1751 ///
1752 /// impl fmt::Display for Foo {
1753 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1754 /// if formatter.alternate() {
1755 /// write!(formatter, "Foo({})", self.0)
1756 /// } else {
1757 /// write!(formatter, "{}", self.0)
1758 /// }
1759 /// }
1760 /// }
1761 ///
1762 /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)");
1763 /// assert_eq!(&format!("{}", Foo(23)), "23");
1764 /// ```
1765 #[stable(feature = "fmt_flags", since = "1.5.0")]
1766 pub fn alternate(&self) -> bool {
1767 self.flags & (1 << FlagV1::Alternate as u32) != 0
1768 }
1769
1770 /// Determines if the `0` flag was specified.
1771 ///
1772 /// # Examples
1773 ///
1774 /// ```
1775 /// use std::fmt;
1776 ///
1777 /// struct Foo(i32);
1778 ///
1779 /// impl fmt::Display for Foo {
1780 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1781 /// assert!(formatter.sign_aware_zero_pad());
1782 /// assert_eq!(formatter.width(), Some(4));
1783 /// // We ignore the formatter's options.
1784 /// write!(formatter, "{}", self.0)
1785 /// }
1786 /// }
1787 ///
1788 /// assert_eq!(&format!("{:04}", Foo(23)), "23");
1789 /// ```
1790 #[stable(feature = "fmt_flags", since = "1.5.0")]
1791 pub fn sign_aware_zero_pad(&self) -> bool {
1792 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1793 }
1794
1795 // FIXME: Decide what public API we want for these two flags.
1796 // https://github.com/rust-lang/rust/issues/48584
1797 fn debug_lower_hex(&self) -> bool {
1798 self.flags & (1 << FlagV1::DebugLowerHex as u32) != 0
1799 }
1800
1801 fn debug_upper_hex(&self) -> bool {
1802 self.flags & (1 << FlagV1::DebugUpperHex as u32) != 0
1803 }
1804
1805 /// Creates a [`DebugStruct`] builder designed to assist with creation of
1806 /// [`fmt::Debug`] implementations for structs.
1807 ///
1808 /// [`fmt::Debug`]: self::Debug
1809 ///
1810 /// # Examples
1811 ///
1812 /// ```rust
1813 /// use std::fmt;
1814 /// use std::net::Ipv4Addr;
1815 ///
1816 /// struct Foo {
1817 /// bar: i32,
1818 /// baz: String,
1819 /// addr: Ipv4Addr,
1820 /// }
1821 ///
1822 /// impl fmt::Debug for Foo {
1823 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1824 /// fmt.debug_struct("Foo")
1825 /// .field("bar", &self.bar)
1826 /// .field("baz", &self.baz)
1827 /// .field("addr", &format_args!("{}", self.addr))
1828 /// .finish()
1829 /// }
1830 /// }
1831 ///
1832 /// assert_eq!(
1833 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
1834 /// format!("{:?}", Foo {
1835 /// bar: 10,
1836 /// baz: "Hello World".to_string(),
1837 /// addr: Ipv4Addr::new(127, 0, 0, 1),
1838 /// })
1839 /// );
1840 /// ```
1841 #[stable(feature = "debug_builders", since = "1.2.0")]
1842 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1843 builders::debug_struct_new(self, name)
1844 }
1845
1846 /// Creates a `DebugTuple` builder designed to assist with creation of
1847 /// `fmt::Debug` implementations for tuple structs.
1848 ///
1849 /// # Examples
1850 ///
1851 /// ```rust
1852 /// use std::fmt;
1853 /// use std::marker::PhantomData;
1854 ///
1855 /// struct Foo<T>(i32, String, PhantomData<T>);
1856 ///
1857 /// impl<T> fmt::Debug for Foo<T> {
1858 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1859 /// fmt.debug_tuple("Foo")
1860 /// .field(&self.0)
1861 /// .field(&self.1)
1862 /// .field(&format_args!("_"))
1863 /// .finish()
1864 /// }
1865 /// }
1866 ///
1867 /// assert_eq!(
1868 /// "Foo(10, \"Hello\", _)",
1869 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
1870 /// );
1871 /// ```
1872 #[stable(feature = "debug_builders", since = "1.2.0")]
1873 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1874 builders::debug_tuple_new(self, name)
1875 }
1876
1877 /// Creates a `DebugList` builder designed to assist with creation of
1878 /// `fmt::Debug` implementations for list-like structures.
1879 ///
1880 /// # Examples
1881 ///
1882 /// ```rust
1883 /// use std::fmt;
1884 ///
1885 /// struct Foo(Vec<i32>);
1886 ///
1887 /// impl fmt::Debug for Foo {
1888 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1889 /// fmt.debug_list().entries(self.0.iter()).finish()
1890 /// }
1891 /// }
1892 ///
1893 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
1894 /// ```
1895 #[stable(feature = "debug_builders", since = "1.2.0")]
1896 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1897 builders::debug_list_new(self)
1898 }
1899
1900 /// Creates a `DebugSet` builder designed to assist with creation of
1901 /// `fmt::Debug` implementations for set-like structures.
1902 ///
1903 /// # Examples
1904 ///
1905 /// ```rust
1906 /// use std::fmt;
1907 ///
1908 /// struct Foo(Vec<i32>);
1909 ///
1910 /// impl fmt::Debug for Foo {
1911 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1912 /// fmt.debug_set().entries(self.0.iter()).finish()
1913 /// }
1914 /// }
1915 ///
1916 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
1917 /// ```
1918 ///
1919 /// [`format_args!`]: crate::format_args
1920 ///
1921 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
1922 /// to build a list of match arms:
1923 ///
1924 /// ```rust
1925 /// use std::fmt;
1926 ///
1927 /// struct Arm<'a, L: 'a, R: 'a>(&'a (L, R));
1928 /// struct Table<'a, K: 'a, V: 'a>(&'a [(K, V)], V);
1929 ///
1930 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
1931 /// where
1932 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
1933 /// {
1934 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1935 /// L::fmt(&(self.0).0, fmt)?;
1936 /// fmt.write_str(" => ")?;
1937 /// R::fmt(&(self.0).1, fmt)
1938 /// }
1939 /// }
1940 ///
1941 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
1942 /// where
1943 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
1944 /// {
1945 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1946 /// fmt.debug_set()
1947 /// .entries(self.0.iter().map(Arm))
1948 /// .entry(&Arm(&(format_args!("_"), &self.1)))
1949 /// .finish()
1950 /// }
1951 /// }
1952 /// ```
1953 #[stable(feature = "debug_builders", since = "1.2.0")]
1954 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1955 builders::debug_set_new(self)
1956 }
1957
1958 /// Creates a `DebugMap` builder designed to assist with creation of
1959 /// `fmt::Debug` implementations for map-like structures.
1960 ///
1961 /// # Examples
1962 ///
1963 /// ```rust
1964 /// use std::fmt;
1965 ///
1966 /// struct Foo(Vec<(String, i32)>);
1967 ///
1968 /// impl fmt::Debug for Foo {
1969 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1970 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
1971 /// }
1972 /// }
1973 ///
1974 /// assert_eq!(
1975 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
1976 /// r#"{"A": 10, "B": 11}"#
1977 /// );
1978 /// ```
1979 #[stable(feature = "debug_builders", since = "1.2.0")]
1980 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1981 builders::debug_map_new(self)
1982 }
1983 }
1984
1985 #[stable(since = "1.2.0", feature = "formatter_write")]
1986 impl Write for Formatter<'_> {
1987 fn write_str(&mut self, s: &str) -> Result {
1988 self.buf.write_str(s)
1989 }
1990
1991 fn write_char(&mut self, c: char) -> Result {
1992 self.buf.write_char(c)
1993 }
1994
1995 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
1996 write(self.buf, args)
1997 }
1998 }
1999
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 impl Display for Error {
2002 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2003 Display::fmt("an error occurred when formatting an argument", f)
2004 }
2005 }
2006
2007 // Implementations of the core formatting traits
2008
2009 macro_rules! fmt_refs {
2010 ($($tr:ident),*) => {
2011 $(
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 impl<T: ?Sized + $tr> $tr for &T {
2014 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2015 }
2016 #[stable(feature = "rust1", since = "1.0.0")]
2017 impl<T: ?Sized + $tr> $tr for &mut T {
2018 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2019 }
2020 )*
2021 }
2022 }
2023
2024 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2025
2026 #[unstable(feature = "never_type", issue = "35121")]
2027 impl Debug for ! {
2028 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2029 *self
2030 }
2031 }
2032
2033 #[unstable(feature = "never_type", issue = "35121")]
2034 impl Display for ! {
2035 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2036 *self
2037 }
2038 }
2039
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 impl Debug for bool {
2042 #[inline]
2043 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2044 Display::fmt(self, f)
2045 }
2046 }
2047
2048 #[stable(feature = "rust1", since = "1.0.0")]
2049 impl Display for bool {
2050 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2051 Display::fmt(if *self { "true" } else { "false" }, f)
2052 }
2053 }
2054
2055 #[stable(feature = "rust1", since = "1.0.0")]
2056 impl Debug for str {
2057 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2058 f.write_char('"')?;
2059 let mut from = 0;
2060 for (i, c) in self.char_indices() {
2061 let esc = c.escape_debug();
2062 // If char needs escaping, flush backlog so far and write, else skip
2063 if esc.len() != 1 {
2064 f.write_str(&self[from..i])?;
2065 for c in esc {
2066 f.write_char(c)?;
2067 }
2068 from = i + c.len_utf8();
2069 }
2070 }
2071 f.write_str(&self[from..])?;
2072 f.write_char('"')
2073 }
2074 }
2075
2076 #[stable(feature = "rust1", since = "1.0.0")]
2077 impl Display for str {
2078 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2079 f.pad(self)
2080 }
2081 }
2082
2083 #[stable(feature = "rust1", since = "1.0.0")]
2084 impl Debug for char {
2085 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2086 f.write_char('\'')?;
2087 for c in self.escape_debug() {
2088 f.write_char(c)?
2089 }
2090 f.write_char('\'')
2091 }
2092 }
2093
2094 #[stable(feature = "rust1", since = "1.0.0")]
2095 impl Display for char {
2096 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2097 if f.width.is_none() && f.precision.is_none() {
2098 f.write_char(*self)
2099 } else {
2100 f.pad(self.encode_utf8(&mut [0; 4]))
2101 }
2102 }
2103 }
2104
2105 #[stable(feature = "rust1", since = "1.0.0")]
2106 impl<T: ?Sized> Pointer for *const T {
2107 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2108 let old_width = f.width;
2109 let old_flags = f.flags;
2110
2111 // The alternate flag is already treated by LowerHex as being special-
2112 // it denotes whether to prefix with 0x. We use it to work out whether
2113 // or not to zero extend, and then unconditionally set it to get the
2114 // prefix.
2115 if f.alternate() {
2116 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
2117
2118 if f.width.is_none() {
2119 f.width = Some((usize::BITS / 4) as usize + 2);
2120 }
2121 }
2122 f.flags |= 1 << (FlagV1::Alternate as u32);
2123
2124 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
2125
2126 f.width = old_width;
2127 f.flags = old_flags;
2128
2129 ret
2130 }
2131 }
2132
2133 #[stable(feature = "rust1", since = "1.0.0")]
2134 impl<T: ?Sized> Pointer for *mut T {
2135 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2136 Pointer::fmt(&(*self as *const T), f)
2137 }
2138 }
2139
2140 #[stable(feature = "rust1", since = "1.0.0")]
2141 impl<T: ?Sized> Pointer for &T {
2142 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2143 Pointer::fmt(&(*self as *const T), f)
2144 }
2145 }
2146
2147 #[stable(feature = "rust1", since = "1.0.0")]
2148 impl<T: ?Sized> Pointer for &mut T {
2149 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2150 Pointer::fmt(&(&**self as *const T), f)
2151 }
2152 }
2153
2154 // Implementation of Display/Debug for various core types
2155
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 impl<T: ?Sized> Debug for *const T {
2158 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2159 Pointer::fmt(self, f)
2160 }
2161 }
2162 #[stable(feature = "rust1", since = "1.0.0")]
2163 impl<T: ?Sized> Debug for *mut T {
2164 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2165 Pointer::fmt(self, f)
2166 }
2167 }
2168
2169 macro_rules! peel {
2170 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2171 }
2172
2173 macro_rules! tuple {
2174 () => ();
2175 ( $($name:ident,)+ ) => (
2176 #[stable(feature = "rust1", since = "1.0.0")]
2177 impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2178 #[allow(non_snake_case, unused_assignments)]
2179 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2180 let mut builder = f.debug_tuple("");
2181 let ($(ref $name,)+) = *self;
2182 $(
2183 builder.field(&$name);
2184 )+
2185
2186 builder.finish()
2187 }
2188 }
2189 peel! { $($name,)+ }
2190 )
2191 }
2192
2193 macro_rules! last_type {
2194 ($a:ident,) => { $a };
2195 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2196 }
2197
2198 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
2199
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 impl<T: Debug> Debug for [T] {
2202 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2203 f.debug_list().entries(self.iter()).finish()
2204 }
2205 }
2206
2207 #[stable(feature = "rust1", since = "1.0.0")]
2208 impl Debug for () {
2209 #[inline]
2210 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2211 f.pad("()")
2212 }
2213 }
2214 #[stable(feature = "rust1", since = "1.0.0")]
2215 impl<T: ?Sized> Debug for PhantomData<T> {
2216 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2217 f.pad("PhantomData")
2218 }
2219 }
2220
2221 #[stable(feature = "rust1", since = "1.0.0")]
2222 impl<T: Copy + Debug> Debug for Cell<T> {
2223 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2224 f.debug_struct("Cell").field("value", &self.get()).finish()
2225 }
2226 }
2227
2228 #[stable(feature = "rust1", since = "1.0.0")]
2229 impl<T: ?Sized + Debug> Debug for RefCell<T> {
2230 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2231 match self.try_borrow() {
2232 Ok(borrow) => f.debug_struct("RefCell").field("value", &borrow).finish(),
2233 Err(_) => {
2234 // The RefCell is mutably borrowed so we can't look at its value
2235 // here. Show a placeholder instead.
2236 struct BorrowedPlaceholder;
2237
2238 impl Debug for BorrowedPlaceholder {
2239 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2240 f.write_str("<borrowed>")
2241 }
2242 }
2243
2244 f.debug_struct("RefCell").field("value", &BorrowedPlaceholder).finish()
2245 }
2246 }
2247 }
2248 }
2249
2250 #[stable(feature = "rust1", since = "1.0.0")]
2251 impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2252 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2253 Debug::fmt(&**self, f)
2254 }
2255 }
2256
2257 #[stable(feature = "rust1", since = "1.0.0")]
2258 impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2259 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2260 Debug::fmt(&*(self.deref()), f)
2261 }
2262 }
2263
2264 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2265 impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
2266 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2267 f.pad("UnsafeCell")
2268 }
2269 }
2270
2271 // If you expected tests to be here, look instead at the core/tests/fmt.rs file,
2272 // it's a lot easier than creating all of the rt::Piece structures here.
2273 // There are also tests in the alloc crate, for those that need allocations.