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