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