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