core/fmt/mod.rs
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, MAX_LEN_UTF8};
7use crate::marker::{PhantomData, PointeeSized};
8use crate::num::fmt as numfmt;
9use crate::ops::Deref;
10use crate::{iter, result, str};
11
12mod builders;
13#[cfg(not(no_fp_fmt_parse))]
14mod float;
15#[cfg(no_fp_fmt_parse)]
16mod nofloat;
17mod num;
18mod num_buffer;
19mod rt;
20
21#[stable(feature = "fmt_flags_align", since = "1.28.0")]
22#[rustc_diagnostic_item = "Alignment"]
23/// Possible alignments returned by `Formatter::align`
24#[derive(Copy, Clone, Debug, PartialEq, Eq)]
25pub enum Alignment {
26 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
27 /// Indication that contents should be left-aligned.
28 Left,
29 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
30 /// Indication that contents should be right-aligned.
31 Right,
32 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
33 /// Indication that contents should be center-aligned.
34 Center,
35}
36
37#[unstable(feature = "int_format_into", issue = "138215")]
38pub use num_buffer::{NumBuffer, NumBufferTrait};
39
40#[stable(feature = "debug_builders", since = "1.2.0")]
41pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
42#[unstable(feature = "debug_closure_helpers", issue = "117729")]
43pub use self::builders::{FromFn, from_fn};
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. This is because, despite the existence of this error,
76/// string formatting is considered an infallible operation.
77/// `fmt()` implementors should not return this `Error` unless they received it from their
78/// [`Formatter`]. The only time your code should create a new instance of this
79/// error is when implementing `fmt::Write`, in order to cancel the formatting operation when
80/// writing to the underlying stream fails.
81///
82/// Any extra information must be arranged to be transmitted through some other means,
83/// such as storing it in a field to be consulted after the formatting operation has been
84/// cancelled. (For example, this is how [`std::io::Write::write_fmt()`] propagates IO errors
85/// during writing.)
86///
87/// This type, `fmt::Error`, should not be
88/// confused with [`std::io::Error`] or [`std::error::Error`], which you may also
89/// have in scope.
90///
91/// [`std::io::Error`]: ../../std/io/struct.Error.html
92/// [`std::io::Write::write_fmt()`]: ../../std/io/trait.Write.html#method.write_fmt
93/// [`std::error::Error`]: ../../std/error/trait.Error.html
94///
95/// # Examples
96///
97/// ```rust
98/// use std::fmt::{self, write};
99///
100/// let mut output = String::new();
101/// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) {
102/// panic!("An error occurred");
103/// }
104/// ```
105#[stable(feature = "rust1", since = "1.0.0")]
106#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
107pub struct Error;
108
109/// A trait for writing or formatting into Unicode-accepting buffers or streams.
110///
111/// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
112/// want to accept Unicode and you don't need flushing, you should implement this trait;
113/// otherwise you should implement [`std::io::Write`].
114///
115/// [`std::io::Write`]: ../../std/io/trait.Write.html
116/// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
117#[stable(feature = "rust1", since = "1.0.0")]
118pub trait Write {
119 /// Writes a string slice into this writer, returning whether the write
120 /// succeeded.
121 ///
122 /// This method can only succeed if the entire string slice was successfully
123 /// written, and this method will not return until all data has been
124 /// written or an error occurs.
125 ///
126 /// # Errors
127 ///
128 /// This function will return an instance of [`std::fmt::Error`][Error] on error.
129 ///
130 /// The purpose of that error is to abort the formatting operation when the underlying
131 /// destination encounters some error preventing it from accepting more text;
132 /// in particular, it does not communicate any information about *what* error occurred.
133 /// It should generally be propagated rather than handled, at least when implementing
134 /// formatting traits.
135 ///
136 /// # Examples
137 ///
138 /// ```
139 /// use std::fmt::{Error, Write};
140 ///
141 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
142 /// f.write_str(s)
143 /// }
144 ///
145 /// let mut buf = String::new();
146 /// writer(&mut buf, "hola")?;
147 /// assert_eq!(&buf, "hola");
148 /// # std::fmt::Result::Ok(())
149 /// ```
150 #[stable(feature = "rust1", since = "1.0.0")]
151 fn write_str(&mut self, s: &str) -> Result;
152
153 /// Writes a [`char`] into this writer, returning whether the write succeeded.
154 ///
155 /// A single [`char`] may be encoded as more than one byte.
156 /// This method can only succeed if the entire byte sequence was successfully
157 /// written, and this method will not return until all data has been
158 /// written or an error occurs.
159 ///
160 /// # Errors
161 ///
162 /// This function will return an instance of [`Error`] on error.
163 ///
164 /// # Examples
165 ///
166 /// ```
167 /// use std::fmt::{Error, Write};
168 ///
169 /// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
170 /// f.write_char(c)
171 /// }
172 ///
173 /// let mut buf = String::new();
174 /// writer(&mut buf, 'a')?;
175 /// writer(&mut buf, 'b')?;
176 /// assert_eq!(&buf, "ab");
177 /// # std::fmt::Result::Ok(())
178 /// ```
179 #[stable(feature = "fmt_write_char", since = "1.1.0")]
180 fn write_char(&mut self, c: char) -> Result {
181 self.write_str(c.encode_utf8(&mut [0; MAX_LEN_UTF8]))
182 }
183
184 /// Glue for usage of the [`write!`] macro with implementors of this trait.
185 ///
186 /// This method should generally not be invoked manually, but rather through
187 /// the [`write!`] macro itself.
188 ///
189 /// # Errors
190 ///
191 /// This function will return an instance of [`Error`] on error. Please see
192 /// [write_str](Write::write_str) for details.
193 ///
194 /// # Examples
195 ///
196 /// ```
197 /// use std::fmt::{Error, Write};
198 ///
199 /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
200 /// f.write_fmt(format_args!("{s}"))
201 /// }
202 ///
203 /// let mut buf = String::new();
204 /// writer(&mut buf, "world")?;
205 /// assert_eq!(&buf, "world");
206 /// # std::fmt::Result::Ok(())
207 /// ```
208 #[stable(feature = "rust1", since = "1.0.0")]
209 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
210 // We use a specialization for `Sized` types to avoid an indirection
211 // through `&mut self`
212 trait SpecWriteFmt {
213 fn spec_write_fmt(self, args: Arguments<'_>) -> Result;
214 }
215
216 impl<W: Write + ?Sized> SpecWriteFmt for &mut W {
217 #[inline]
218 default fn spec_write_fmt(mut self, args: Arguments<'_>) -> Result {
219 if let Some(s) = args.as_statically_known_str() {
220 self.write_str(s)
221 } else {
222 write(&mut self, args)
223 }
224 }
225 }
226
227 impl<W: Write> SpecWriteFmt for &mut W {
228 #[inline]
229 fn spec_write_fmt(self, args: Arguments<'_>) -> Result {
230 if let Some(s) = args.as_statically_known_str() {
231 self.write_str(s)
232 } else {
233 write(self, args)
234 }
235 }
236 }
237
238 self.spec_write_fmt(args)
239 }
240}
241
242#[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
243impl<W: Write + ?Sized> Write for &mut W {
244 fn write_str(&mut self, s: &str) -> Result {
245 (**self).write_str(s)
246 }
247
248 fn write_char(&mut self, c: char) -> Result {
249 (**self).write_char(c)
250 }
251
252 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
253 (**self).write_fmt(args)
254 }
255}
256
257/// The signedness of a [`Formatter`] (or of a [`FormattingOptions`]).
258#[derive(Copy, Clone, Debug, PartialEq, Eq)]
259#[unstable(feature = "formatting_options", issue = "118117")]
260pub enum Sign {
261 /// Represents the `+` flag.
262 Plus,
263 /// Represents the `-` flag.
264 Minus,
265}
266
267/// Specifies whether the [`Debug`] trait should use lower-/upper-case
268/// hexadecimal or normal integers.
269#[derive(Copy, Clone, Debug, PartialEq, Eq)]
270#[unstable(feature = "formatting_options", issue = "118117")]
271pub enum DebugAsHex {
272 /// Use lower-case hexadecimal integers for the `Debug` trait (like [the `x?` type](../../std/fmt/index.html#formatting-traits)).
273 Lower,
274 /// Use upper-case hexadecimal integers for the `Debug` trait (like [the `X?` type](../../std/fmt/index.html#formatting-traits)).
275 Upper,
276}
277
278/// Options for formatting.
279///
280/// `FormattingOptions` is a [`Formatter`] without an attached [`Write`] trait.
281/// It is mainly used to construct `Formatter` instances.
282#[derive(Copy, Clone, Debug, PartialEq, Eq)]
283#[unstable(feature = "formatting_options", issue = "118117")]
284pub struct FormattingOptions {
285 /// Flags, with the following bit fields:
286 ///
287 /// ```text
288 /// 31 30 29 28 27 26 25 24 23 22 21 20 0
289 /// ┌───┬───────┬───┬───┬───┬───┬───┬───┬───┬───┬──────────────────────────────────┐
290 /// │ 1 │ align │ p │ w │ X?│ x?│'0'│ # │ - │ + │ fill │
291 /// └───┴───────┴───┴───┴───┴───┴───┴───┴───┴───┴──────────────────────────────────┘
292 /// │ │ │ │ └─┬───────────────────┘ └─┬──────────────────────────────┘
293 /// │ │ │ │ │ └─ The fill character (21 bits char).
294 /// │ │ │ │ └─ The debug upper/lower hex, zero pad, alternate, and plus/minus flags.
295 /// │ │ │ └─ Whether a width is set. (The value is stored separately.)
296 /// │ │ └─ Whether a precision is set. (The value is stored separately.)
297 /// │ ├─ 0: Align left. (<)
298 /// │ ├─ 1: Align right. (>)
299 /// │ ├─ 2: Align center. (^)
300 /// │ └─ 3: Alignment not set. (default)
301 /// └─ Always set.
302 /// This makes it possible to distinguish formatting flags from
303 /// a &str size when stored in (the upper bits of) the same field.
304 /// (fmt::Arguments will make use of this property in the future.)
305 /// ```
306 // Note: This could use a special niche type with range 0x8000_0000..=0xfdd0ffff.
307 // It's unclear if that's useful, though.
308 flags: u32,
309 /// Width if width flag (bit 27) above is set. Otherwise, always 0.
310 width: u16,
311 /// Precision if precision flag (bit 28) above is set. Otherwise, always 0.
312 precision: u16,
313}
314
315// This needs to match with compiler/rustc_ast_lowering/src/format.rs.
316mod flags {
317 pub(super) const SIGN_PLUS_FLAG: u32 = 1 << 21;
318 pub(super) const SIGN_MINUS_FLAG: u32 = 1 << 22;
319 pub(super) const ALTERNATE_FLAG: u32 = 1 << 23;
320 pub(super) const SIGN_AWARE_ZERO_PAD_FLAG: u32 = 1 << 24;
321 pub(super) const DEBUG_LOWER_HEX_FLAG: u32 = 1 << 25;
322 pub(super) const DEBUG_UPPER_HEX_FLAG: u32 = 1 << 26;
323 pub(super) const WIDTH_FLAG: u32 = 1 << 27;
324 pub(super) const PRECISION_FLAG: u32 = 1 << 28;
325 pub(super) const ALIGN_BITS: u32 = 0b11 << 29;
326 pub(super) const ALIGN_LEFT: u32 = 0 << 29;
327 pub(super) const ALIGN_RIGHT: u32 = 1 << 29;
328 pub(super) const ALIGN_CENTER: u32 = 2 << 29;
329 pub(super) const ALIGN_UNKNOWN: u32 = 3 << 29;
330 pub(super) const ALWAYS_SET: u32 = 1 << 31;
331}
332
333impl FormattingOptions {
334 /// Construct a new `FormatterBuilder` with the supplied `Write` trait
335 /// object for output that is equivalent to the `{}` formatting
336 /// specifier:
337 ///
338 /// - no flags,
339 /// - filled with spaces,
340 /// - no alignment,
341 /// - no width,
342 /// - no precision, and
343 /// - no [`DebugAsHex`] output mode.
344 #[unstable(feature = "formatting_options", issue = "118117")]
345 pub const fn new() -> Self {
346 Self {
347 flags: ' ' as u32 | flags::ALIGN_UNKNOWN | flags::ALWAYS_SET,
348 width: 0,
349 precision: 0,
350 }
351 }
352
353 /// Sets or removes the sign (the `+` or the `-` flag).
354 ///
355 /// - `+`: This is intended for numeric types and indicates that the sign
356 /// should always be printed. By default only the negative sign of signed
357 /// values is printed, and the sign of positive or unsigned values is
358 /// omitted. This flag indicates that the correct sign (+ or -) should
359 /// always be printed.
360 /// - `-`: Currently not used
361 #[unstable(feature = "formatting_options", issue = "118117")]
362 pub fn sign(&mut self, sign: Option<Sign>) -> &mut Self {
363 let sign = match sign {
364 None => 0,
365 Some(Sign::Plus) => flags::SIGN_PLUS_FLAG,
366 Some(Sign::Minus) => flags::SIGN_MINUS_FLAG,
367 };
368 self.flags = self.flags & !(flags::SIGN_PLUS_FLAG | flags::SIGN_MINUS_FLAG) | sign;
369 self
370 }
371 /// Sets or unsets the `0` flag.
372 ///
373 /// This is used to indicate for integer formats that the padding to width should both be done with a 0 character as well as be sign-aware
374 #[unstable(feature = "formatting_options", issue = "118117")]
375 pub fn sign_aware_zero_pad(&mut self, sign_aware_zero_pad: bool) -> &mut Self {
376 if sign_aware_zero_pad {
377 self.flags |= flags::SIGN_AWARE_ZERO_PAD_FLAG;
378 } else {
379 self.flags &= !flags::SIGN_AWARE_ZERO_PAD_FLAG;
380 }
381 self
382 }
383 /// Sets or unsets the `#` flag.
384 ///
385 /// This flag indicates that the "alternate" form of printing should be
386 /// used. The alternate forms are:
387 /// - [`Debug`] : pretty-print the [`Debug`] formatting (adds linebreaks and indentation)
388 /// - [`LowerHex`] as well as [`UpperHex`] - precedes the argument with a `0x`
389 /// - [`Octal`] - precedes the argument with a `0b`
390 /// - [`Binary`] - precedes the argument with a `0o`
391 #[unstable(feature = "formatting_options", issue = "118117")]
392 pub fn alternate(&mut self, alternate: bool) -> &mut Self {
393 if alternate {
394 self.flags |= flags::ALTERNATE_FLAG;
395 } else {
396 self.flags &= !flags::ALTERNATE_FLAG;
397 }
398 self
399 }
400 /// Sets the fill character.
401 ///
402 /// The optional fill character and alignment is provided normally in
403 /// conjunction with the width parameter. This indicates that if the value
404 /// being formatted is smaller than width some extra characters will be
405 /// printed around it.
406 #[unstable(feature = "formatting_options", issue = "118117")]
407 pub fn fill(&mut self, fill: char) -> &mut Self {
408 self.flags = self.flags & (u32::MAX << 21) | fill as u32;
409 self
410 }
411 /// Sets or removes the alignment.
412 ///
413 /// The alignment specifies how the value being formatted should be
414 /// positioned if it is smaller than the width of the formatter.
415 #[unstable(feature = "formatting_options", issue = "118117")]
416 pub fn align(&mut self, align: Option<Alignment>) -> &mut Self {
417 let align: u32 = match align {
418 Some(Alignment::Left) => flags::ALIGN_LEFT,
419 Some(Alignment::Right) => flags::ALIGN_RIGHT,
420 Some(Alignment::Center) => flags::ALIGN_CENTER,
421 None => flags::ALIGN_UNKNOWN,
422 };
423 self.flags = self.flags & !flags::ALIGN_BITS | align;
424 self
425 }
426 /// Sets or removes the width.
427 ///
428 /// This is a parameter for the “minimum width” that the format should take
429 /// up. If the value’s string does not fill up this many characters, then
430 /// the padding specified by [`FormattingOptions::fill`]/[`FormattingOptions::align`]
431 /// will be used to take up the required space.
432 #[unstable(feature = "formatting_options", issue = "118117")]
433 pub fn width(&mut self, width: Option<u16>) -> &mut Self {
434 if let Some(width) = width {
435 self.flags |= flags::WIDTH_FLAG;
436 self.width = width;
437 } else {
438 self.flags &= !flags::WIDTH_FLAG;
439 self.width = 0;
440 }
441 self
442 }
443 /// Sets or removes the precision.
444 ///
445 /// - For non-numeric types, this can be considered a “maximum width”. If
446 /// the resulting string is longer than this width, then it is truncated
447 /// down to this many characters and that truncated value is emitted with
448 /// proper fill, alignment and width if those parameters are set.
449 /// - For integral types, this is ignored.
450 /// - For floating-point types, this indicates how many digits after the
451 /// decimal point should be printed.
452 #[unstable(feature = "formatting_options", issue = "118117")]
453 pub fn precision(&mut self, precision: Option<u16>) -> &mut Self {
454 if let Some(precision) = precision {
455 self.flags |= flags::PRECISION_FLAG;
456 self.precision = precision;
457 } else {
458 self.flags &= !flags::PRECISION_FLAG;
459 self.precision = 0;
460 }
461 self
462 }
463 /// Specifies whether the [`Debug`] trait should use lower-/upper-case
464 /// hexadecimal or normal integers
465 #[unstable(feature = "formatting_options", issue = "118117")]
466 pub fn debug_as_hex(&mut self, debug_as_hex: Option<DebugAsHex>) -> &mut Self {
467 let debug_as_hex = match debug_as_hex {
468 None => 0,
469 Some(DebugAsHex::Lower) => flags::DEBUG_LOWER_HEX_FLAG,
470 Some(DebugAsHex::Upper) => flags::DEBUG_UPPER_HEX_FLAG,
471 };
472 self.flags = self.flags & !(flags::DEBUG_LOWER_HEX_FLAG | flags::DEBUG_UPPER_HEX_FLAG)
473 | debug_as_hex;
474 self
475 }
476
477 /// Returns the current sign (the `+` or the `-` flag).
478 #[unstable(feature = "formatting_options", issue = "118117")]
479 pub const fn get_sign(&self) -> Option<Sign> {
480 if self.flags & flags::SIGN_PLUS_FLAG != 0 {
481 Some(Sign::Plus)
482 } else if self.flags & flags::SIGN_MINUS_FLAG != 0 {
483 Some(Sign::Minus)
484 } else {
485 None
486 }
487 }
488 /// Returns the current `0` flag.
489 #[unstable(feature = "formatting_options", issue = "118117")]
490 pub const fn get_sign_aware_zero_pad(&self) -> bool {
491 self.flags & flags::SIGN_AWARE_ZERO_PAD_FLAG != 0
492 }
493 /// Returns the current `#` flag.
494 #[unstable(feature = "formatting_options", issue = "118117")]
495 pub const fn get_alternate(&self) -> bool {
496 self.flags & flags::ALTERNATE_FLAG != 0
497 }
498 /// Returns the current fill character.
499 #[unstable(feature = "formatting_options", issue = "118117")]
500 pub const fn get_fill(&self) -> char {
501 // SAFETY: We only ever put a valid `char` in the lower 21 bits of the flags field.
502 unsafe { char::from_u32_unchecked(self.flags & 0x1FFFFF) }
503 }
504 /// Returns the current alignment.
505 #[unstable(feature = "formatting_options", issue = "118117")]
506 pub const fn get_align(&self) -> Option<Alignment> {
507 match self.flags & flags::ALIGN_BITS {
508 flags::ALIGN_LEFT => Some(Alignment::Left),
509 flags::ALIGN_RIGHT => Some(Alignment::Right),
510 flags::ALIGN_CENTER => Some(Alignment::Center),
511 _ => None,
512 }
513 }
514 /// Returns the current width.
515 #[unstable(feature = "formatting_options", issue = "118117")]
516 pub const fn get_width(&self) -> Option<u16> {
517 if self.flags & flags::WIDTH_FLAG != 0 { Some(self.width) } else { None }
518 }
519 /// Returns the current precision.
520 #[unstable(feature = "formatting_options", issue = "118117")]
521 pub const fn get_precision(&self) -> Option<u16> {
522 if self.flags & flags::PRECISION_FLAG != 0 { Some(self.precision) } else { None }
523 }
524 /// Returns the current precision.
525 #[unstable(feature = "formatting_options", issue = "118117")]
526 pub const fn get_debug_as_hex(&self) -> Option<DebugAsHex> {
527 if self.flags & flags::DEBUG_LOWER_HEX_FLAG != 0 {
528 Some(DebugAsHex::Lower)
529 } else if self.flags & flags::DEBUG_UPPER_HEX_FLAG != 0 {
530 Some(DebugAsHex::Upper)
531 } else {
532 None
533 }
534 }
535
536 /// Creates a [`Formatter`] that writes its output to the given [`Write`] trait.
537 ///
538 /// You may alternatively use [`Formatter::new()`].
539 #[unstable(feature = "formatting_options", issue = "118117")]
540 pub fn create_formatter<'a>(self, write: &'a mut (dyn Write + 'a)) -> Formatter<'a> {
541 Formatter { options: self, buf: write }
542 }
543}
544
545#[unstable(feature = "formatting_options", issue = "118117")]
546impl Default for FormattingOptions {
547 /// Same as [`FormattingOptions::new()`].
548 fn default() -> Self {
549 // The `#[derive(Default)]` implementation would set `fill` to `\0` instead of space.
550 Self::new()
551 }
552}
553
554/// Configuration for formatting.
555///
556/// A `Formatter` represents various options related to formatting. Users do not
557/// construct `Formatter`s directly; a mutable reference to one is passed to
558/// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
559///
560/// To interact with a `Formatter`, you'll call various methods to change the
561/// various options related to formatting. For examples, please see the
562/// documentation of the methods defined on `Formatter` below.
563#[allow(missing_debug_implementations)]
564#[stable(feature = "rust1", since = "1.0.0")]
565#[rustc_diagnostic_item = "Formatter"]
566pub struct Formatter<'a> {
567 options: FormattingOptions,
568
569 buf: &'a mut (dyn Write + 'a),
570}
571
572impl<'a> Formatter<'a> {
573 /// Creates a new formatter with given [`FormattingOptions`].
574 ///
575 /// If `write` is a reference to a formatter, it is recommended to use
576 /// [`Formatter::with_options`] instead as this can borrow the underlying
577 /// `write`, thereby bypassing one layer of indirection.
578 ///
579 /// You may alternatively use [`FormattingOptions::create_formatter()`].
580 #[unstable(feature = "formatting_options", issue = "118117")]
581 pub fn new(write: &'a mut (dyn Write + 'a), options: FormattingOptions) -> Self {
582 Formatter { options, buf: write }
583 }
584
585 /// Creates a new formatter based on this one with given [`FormattingOptions`].
586 #[unstable(feature = "formatting_options", issue = "118117")]
587 pub fn with_options<'b>(&'b mut self, options: FormattingOptions) -> Formatter<'b> {
588 Formatter { options, buf: self.buf }
589 }
590}
591
592/// This structure represents a safely precompiled version of a format string
593/// and its arguments. This cannot be generated at runtime because it cannot
594/// safely be done, so no constructors are given and the fields are private
595/// to prevent modification.
596///
597/// The [`format_args!`] macro will safely create an instance of this structure.
598/// The macro validates the format string at compile-time so usage of the
599/// [`write()`] and [`format()`] functions can be safely performed.
600///
601/// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
602/// and `Display` contexts as seen below. The example also shows that `Debug`
603/// and `Display` format to the same thing: the interpolated format string
604/// in `format_args!`.
605///
606/// ```rust
607/// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
608/// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
609/// assert_eq!("1 foo 2", display);
610/// assert_eq!(display, debug);
611/// ```
612///
613/// [`format()`]: ../../std/fmt/fn.format.html
614#[lang = "format_arguments"]
615#[stable(feature = "rust1", since = "1.0.0")]
616#[derive(Copy, Clone)]
617pub struct Arguments<'a> {
618 // Format string pieces to print.
619 pieces: &'a [&'static str],
620
621 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
622 fmt: Option<&'a [rt::Placeholder]>,
623
624 // Dynamic arguments for interpolation, to be interleaved with string
625 // pieces. (Every argument is preceded by a string piece.)
626 args: &'a [rt::Argument<'a>],
627}
628
629#[doc(hidden)]
630#[unstable(feature = "fmt_internals", issue = "none")]
631impl<'a> Arguments<'a> {
632 /// Estimates the length of the formatted text.
633 ///
634 /// This is intended to be used for setting initial `String` capacity
635 /// when using `format!`. Note: this is neither the lower nor upper bound.
636 #[inline]
637 pub fn estimated_capacity(&self) -> usize {
638 let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
639
640 if self.args.is_empty() {
641 pieces_length
642 } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
643 // If the format string starts with an argument,
644 // don't preallocate anything, unless length
645 // of pieces is significant.
646 0
647 } else {
648 // There are some arguments, so any additional push
649 // will reallocate the string. To avoid that,
650 // we're "pre-doubling" the capacity here.
651 pieces_length.checked_mul(2).unwrap_or(0)
652 }
653 }
654}
655
656impl<'a> Arguments<'a> {
657 /// Gets the formatted string, if it has no arguments to be formatted at runtime.
658 ///
659 /// This can be used to avoid allocations in some cases.
660 ///
661 /// # Guarantees
662 ///
663 /// For `format_args!("just a literal")`, this function is guaranteed to
664 /// return `Some("just a literal")`.
665 ///
666 /// For most cases with placeholders, this function will return `None`.
667 ///
668 /// However, the compiler may perform optimizations that can cause this
669 /// function to return `Some(_)` even if the format string contains
670 /// placeholders. For example, `format_args!("Hello, {}!", "world")` may be
671 /// optimized to `format_args!("Hello, world!")`, such that `as_str()`
672 /// returns `Some("Hello, world!")`.
673 ///
674 /// The behavior for anything but the trivial case (without placeholders)
675 /// is not guaranteed, and should not be relied upon for anything other
676 /// than optimization.
677 ///
678 /// # Examples
679 ///
680 /// ```rust
681 /// use std::fmt::Arguments;
682 ///
683 /// fn write_str(_: &str) { /* ... */ }
684 ///
685 /// fn write_fmt(args: &Arguments<'_>) {
686 /// if let Some(s) = args.as_str() {
687 /// write_str(s)
688 /// } else {
689 /// write_str(&args.to_string());
690 /// }
691 /// }
692 /// ```
693 ///
694 /// ```rust
695 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
696 /// assert_eq!(format_args!("").as_str(), Some(""));
697 /// assert_eq!(format_args!("{:?}", std::env::current_dir()).as_str(), None);
698 /// ```
699 #[stable(feature = "fmt_as_str", since = "1.52.0")]
700 #[rustc_const_stable(feature = "const_arguments_as_str", since = "1.84.0")]
701 #[must_use]
702 #[inline]
703 pub const fn as_str(&self) -> Option<&'static str> {
704 match (self.pieces, self.args) {
705 ([], []) => Some(""),
706 ([s], []) => Some(s),
707 _ => None,
708 }
709 }
710
711 /// Same as [`Arguments::as_str`], but will only return `Some(s)` if it can be determined at compile time.
712 #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
713 #[must_use]
714 #[inline]
715 #[doc(hidden)]
716 pub fn as_statically_known_str(&self) -> Option<&'static str> {
717 let s = self.as_str();
718 if core::intrinsics::is_val_statically_known(s.is_some()) { s } else { None }
719 }
720}
721
722// Manually implementing these results in better error messages.
723#[stable(feature = "rust1", since = "1.0.0")]
724impl !Send for Arguments<'_> {}
725#[stable(feature = "rust1", since = "1.0.0")]
726impl !Sync for Arguments<'_> {}
727
728#[stable(feature = "rust1", since = "1.0.0")]
729impl Debug for Arguments<'_> {
730 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
731 Display::fmt(self, fmt)
732 }
733}
734
735#[stable(feature = "rust1", since = "1.0.0")]
736impl Display for Arguments<'_> {
737 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
738 write(fmt.buf, *self)
739 }
740}
741
742/// `?` formatting.
743///
744/// `Debug` should format the output in a programmer-facing, debugging context.
745///
746/// Generally speaking, you should just `derive` a `Debug` implementation.
747///
748/// When used with the alternate format specifier `#?`, the output is pretty-printed.
749///
750/// For more information on formatters, see [the module-level documentation][module].
751///
752/// [module]: ../../std/fmt/index.html
753///
754/// This trait can be used with `#[derive]` if all fields implement `Debug`. When
755/// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
756/// comma-separated list of each field's name and `Debug` value, then `}`. For
757/// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
758/// `Debug` values of the fields, then `)`.
759///
760/// # Stability
761///
762/// Derived `Debug` formats are not stable, and so may change with future Rust
763/// versions. Additionally, `Debug` implementations of types provided by the
764/// standard library (`std`, `core`, `alloc`, etc.) are not stable, and
765/// may also change with future Rust versions.
766///
767/// # Examples
768///
769/// Deriving an implementation:
770///
771/// ```
772/// #[derive(Debug)]
773/// struct Point {
774/// x: i32,
775/// y: i32,
776/// }
777///
778/// let origin = Point { x: 0, y: 0 };
779///
780/// assert_eq!(
781/// format!("The origin is: {origin:?}"),
782/// "The origin is: Point { x: 0, y: 0 }",
783/// );
784/// ```
785///
786/// Manually implementing:
787///
788/// ```
789/// use std::fmt;
790///
791/// struct Point {
792/// x: i32,
793/// y: i32,
794/// }
795///
796/// impl fmt::Debug for Point {
797/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
798/// f.debug_struct("Point")
799/// .field("x", &self.x)
800/// .field("y", &self.y)
801/// .finish()
802/// }
803/// }
804///
805/// let origin = Point { x: 0, y: 0 };
806///
807/// assert_eq!(
808/// format!("The origin is: {origin:?}"),
809/// "The origin is: Point { x: 0, y: 0 }",
810/// );
811/// ```
812///
813/// There are a number of helper methods on the [`Formatter`] struct to help you with manual
814/// implementations, such as [`debug_struct`].
815///
816/// [`debug_struct`]: Formatter::debug_struct
817///
818/// Types that do not wish to use the standard suite of debug representations
819/// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
820/// `debug_list`, `debug_set`, `debug_map`) can do something totally custom by
821/// manually writing an arbitrary representation to the `Formatter`.
822///
823/// ```
824/// # use std::fmt;
825/// # struct Point {
826/// # x: i32,
827/// # y: i32,
828/// # }
829/// #
830/// impl fmt::Debug for Point {
831/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
832/// write!(f, "Point [{} {}]", self.x, self.y)
833/// }
834/// }
835/// ```
836///
837/// `Debug` implementations using either `derive` or the debug builder API
838/// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
839///
840/// Pretty-printing with `#?`:
841///
842/// ```
843/// #[derive(Debug)]
844/// struct Point {
845/// x: i32,
846/// y: i32,
847/// }
848///
849/// let origin = Point { x: 0, y: 0 };
850///
851/// let expected = "The origin is: Point {
852/// x: 0,
853/// y: 0,
854/// }";
855/// assert_eq!(format!("The origin is: {origin:#?}"), expected);
856/// ```
857
858#[stable(feature = "rust1", since = "1.0.0")]
859#[rustc_on_unimplemented(
860 on(
861 crate_local,
862 note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {This} for {Self}`"
863 ),
864 on(
865 from_desugaring = "FormatLiteral",
866 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{This}`"
867 ),
868 message = "`{Self}` doesn't implement `{This}`"
869)]
870#[doc(alias = "{:?}")]
871#[rustc_diagnostic_item = "Debug"]
872#[rustc_trivial_field_reads]
873pub trait Debug: PointeeSized {
874 #[doc = include_str!("fmt_trait_method_doc.md")]
875 ///
876 /// # Examples
877 ///
878 /// ```
879 /// use std::fmt;
880 ///
881 /// struct Position {
882 /// longitude: f32,
883 /// latitude: f32,
884 /// }
885 ///
886 /// impl fmt::Debug for Position {
887 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
888 /// f.debug_tuple("")
889 /// .field(&self.longitude)
890 /// .field(&self.latitude)
891 /// .finish()
892 /// }
893 /// }
894 ///
895 /// let position = Position { longitude: 1.987, latitude: 2.983 };
896 /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
897 ///
898 /// assert_eq!(format!("{position:#?}"), "(
899 /// 1.987,
900 /// 2.983,
901 /// )");
902 /// ```
903 #[stable(feature = "rust1", since = "1.0.0")]
904 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
905}
906
907// Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
908pub(crate) mod macros {
909 /// Derive macro generating an impl of the trait `Debug`.
910 #[rustc_builtin_macro]
911 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
912 #[allow_internal_unstable(core_intrinsics, fmt_helpers_for_derive)]
913 pub macro Debug($item:item) {
914 /* compiler built-in */
915 }
916}
917#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
918#[doc(inline)]
919pub use macros::Debug;
920
921/// Format trait for an empty format, `{}`.
922///
923/// Implementing this trait for a type will automatically implement the
924/// [`ToString`][tostring] trait for the type, allowing the usage
925/// of the [`.to_string()`][tostring_function] method. Prefer implementing
926/// the `Display` trait for a type, rather than [`ToString`][tostring].
927///
928/// `Display` is similar to [`Debug`], but `Display` is for user-facing
929/// output, and so cannot be derived.
930///
931/// For more information on formatters, see [the module-level documentation][module].
932///
933/// [module]: ../../std/fmt/index.html
934/// [tostring]: ../../std/string/trait.ToString.html
935/// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
936///
937/// # Completeness and parseability
938///
939/// `Display` for a type might not necessarily be a lossless or complete representation of the type.
940/// It may omit internal state, precision, or other information the type does not consider important
941/// for user-facing output, as determined by the type. As such, the output of `Display` might not be
942/// possible to parse, and even if it is, the result of parsing might not exactly match the original
943/// value.
944///
945/// However, if a type has a lossless `Display` implementation whose output is meant to be
946/// conveniently machine-parseable and not just meant for human consumption, then the type may wish
947/// to accept the same format in `FromStr`, and document that usage. Having both `Display` and
948/// `FromStr` implementations where the result of `Display` cannot be parsed with `FromStr` may
949/// surprise users.
950///
951/// # Internationalization
952///
953/// Because a type can only have one `Display` implementation, it is often preferable
954/// to only implement `Display` when there is a single most "obvious" way that
955/// values can be formatted as text. This could mean formatting according to the
956/// "invariant" culture and "undefined" locale, or it could mean that the type
957/// display is designed for a specific culture/locale, such as developer logs.
958///
959/// If not all values have a justifiably canonical textual format or if you want
960/// to support alternative formats not covered by the standard set of possible
961/// [formatting traits], the most flexible approach is display adapters: methods
962/// like [`str::escape_default`] or [`Path::display`] which create a wrapper
963/// implementing `Display` to output the specific display format.
964///
965/// [formatting traits]: ../../std/fmt/index.html#formatting-traits
966/// [`Path::display`]: ../../std/path/struct.Path.html#method.display
967///
968/// # Examples
969///
970/// Implementing `Display` on a type:
971///
972/// ```
973/// use std::fmt;
974///
975/// struct Point {
976/// x: i32,
977/// y: i32,
978/// }
979///
980/// impl fmt::Display for Point {
981/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
982/// write!(f, "({}, {})", self.x, self.y)
983/// }
984/// }
985///
986/// let origin = Point { x: 0, y: 0 };
987///
988/// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
989/// ```
990#[rustc_on_unimplemented(
991 on(
992 any(Self = "std::path::Path", Self = "std::path::PathBuf"),
993 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
994 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
995 as they may contain non-Unicode data",
996 ),
997 on(
998 from_desugaring = "FormatLiteral",
999 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead",
1000 label = "`{Self}` cannot be formatted with the default formatter",
1001 ),
1002 message = "`{Self}` doesn't implement `{This}`"
1003)]
1004#[doc(alias = "{}")]
1005#[rustc_diagnostic_item = "Display"]
1006#[stable(feature = "rust1", since = "1.0.0")]
1007pub trait Display: PointeeSized {
1008 #[doc = include_str!("fmt_trait_method_doc.md")]
1009 ///
1010 /// # Examples
1011 ///
1012 /// ```
1013 /// use std::fmt;
1014 ///
1015 /// struct Position {
1016 /// longitude: f32,
1017 /// latitude: f32,
1018 /// }
1019 ///
1020 /// impl fmt::Display for Position {
1021 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1022 /// write!(f, "({}, {})", self.longitude, self.latitude)
1023 /// }
1024 /// }
1025 ///
1026 /// assert_eq!(
1027 /// "(1.987, 2.983)",
1028 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }),
1029 /// );
1030 /// ```
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1033}
1034
1035/// `o` formatting.
1036///
1037/// The `Octal` trait should format its output as a number in base-8.
1038///
1039/// For primitive signed integers (`i8` to `i128`, and `isize`),
1040/// negative values are formatted as the two’s complement representation.
1041///
1042/// The alternate flag, `#`, adds a `0o` in front of the output.
1043///
1044/// For more information on formatters, see [the module-level documentation][module].
1045///
1046/// [module]: ../../std/fmt/index.html
1047///
1048/// # Examples
1049///
1050/// Basic usage with `i32`:
1051///
1052/// ```
1053/// let x = 42; // 42 is '52' in octal
1054///
1055/// assert_eq!(format!("{x:o}"), "52");
1056/// assert_eq!(format!("{x:#o}"), "0o52");
1057///
1058/// assert_eq!(format!("{:o}", -16), "37777777760");
1059/// ```
1060///
1061/// Implementing `Octal` on a type:
1062///
1063/// ```
1064/// use std::fmt;
1065///
1066/// struct Length(i32);
1067///
1068/// impl fmt::Octal for Length {
1069/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1070/// let val = self.0;
1071///
1072/// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
1073/// }
1074/// }
1075///
1076/// let l = Length(9);
1077///
1078/// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
1079///
1080/// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
1081/// ```
1082#[stable(feature = "rust1", since = "1.0.0")]
1083pub trait Octal: PointeeSized {
1084 #[doc = include_str!("fmt_trait_method_doc.md")]
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1087}
1088
1089/// `b` formatting.
1090///
1091/// The `Binary` trait should format its output as a number in binary.
1092///
1093/// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
1094/// negative values are formatted as the two’s complement representation.
1095///
1096/// The alternate flag, `#`, adds a `0b` in front of the output.
1097///
1098/// For more information on formatters, see [the module-level documentation][module].
1099///
1100/// [module]: ../../std/fmt/index.html
1101///
1102/// # Examples
1103///
1104/// Basic usage with [`i32`]:
1105///
1106/// ```
1107/// let x = 42; // 42 is '101010' in binary
1108///
1109/// assert_eq!(format!("{x:b}"), "101010");
1110/// assert_eq!(format!("{x:#b}"), "0b101010");
1111///
1112/// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
1113/// ```
1114///
1115/// Implementing `Binary` on a type:
1116///
1117/// ```
1118/// use std::fmt;
1119///
1120/// struct Length(i32);
1121///
1122/// impl fmt::Binary for Length {
1123/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1124/// let val = self.0;
1125///
1126/// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
1127/// }
1128/// }
1129///
1130/// let l = Length(107);
1131///
1132/// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
1133///
1134/// assert_eq!(
1135/// // Note that the `0b` prefix added by `#` is included in the total width, so we
1136/// // need to add two to correctly display all 32 bits.
1137/// format!("l as binary is: {l:#034b}"),
1138/// "l as binary is: 0b00000000000000000000000001101011"
1139/// );
1140/// ```
1141#[stable(feature = "rust1", since = "1.0.0")]
1142pub trait Binary: PointeeSized {
1143 #[doc = include_str!("fmt_trait_method_doc.md")]
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1146}
1147
1148/// `x` formatting.
1149///
1150/// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
1151/// in lower case.
1152///
1153/// For primitive signed integers (`i8` to `i128`, and `isize`),
1154/// negative values are formatted as the two’s complement representation.
1155///
1156/// The alternate flag, `#`, adds a `0x` in front of the output.
1157///
1158/// For more information on formatters, see [the module-level documentation][module].
1159///
1160/// [module]: ../../std/fmt/index.html
1161///
1162/// # Examples
1163///
1164/// Basic usage with `i32`:
1165///
1166/// ```
1167/// let y = 42; // 42 is '2a' in hex
1168///
1169/// assert_eq!(format!("{y:x}"), "2a");
1170/// assert_eq!(format!("{y:#x}"), "0x2a");
1171///
1172/// assert_eq!(format!("{:x}", -16), "fffffff0");
1173/// ```
1174///
1175/// Implementing `LowerHex` on a type:
1176///
1177/// ```
1178/// use std::fmt;
1179///
1180/// struct Length(i32);
1181///
1182/// impl fmt::LowerHex for Length {
1183/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1184/// let val = self.0;
1185///
1186/// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
1187/// }
1188/// }
1189///
1190/// let l = Length(9);
1191///
1192/// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
1193///
1194/// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
1195/// ```
1196#[stable(feature = "rust1", since = "1.0.0")]
1197pub trait LowerHex: PointeeSized {
1198 #[doc = include_str!("fmt_trait_method_doc.md")]
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1201}
1202
1203/// `X` formatting.
1204///
1205/// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
1206/// in upper case.
1207///
1208/// For primitive signed integers (`i8` to `i128`, and `isize`),
1209/// negative values are formatted as the two’s complement representation.
1210///
1211/// The alternate flag, `#`, adds a `0x` in front of the output.
1212///
1213/// For more information on formatters, see [the module-level documentation][module].
1214///
1215/// [module]: ../../std/fmt/index.html
1216///
1217/// # Examples
1218///
1219/// Basic usage with `i32`:
1220///
1221/// ```
1222/// let y = 42; // 42 is '2A' in hex
1223///
1224/// assert_eq!(format!("{y:X}"), "2A");
1225/// assert_eq!(format!("{y:#X}"), "0x2A");
1226///
1227/// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
1228/// ```
1229///
1230/// Implementing `UpperHex` on a type:
1231///
1232/// ```
1233/// use std::fmt;
1234///
1235/// struct Length(i32);
1236///
1237/// impl fmt::UpperHex for Length {
1238/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1239/// let val = self.0;
1240///
1241/// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
1242/// }
1243/// }
1244///
1245/// let l = Length(i32::MAX);
1246///
1247/// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
1248///
1249/// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
1250/// ```
1251#[stable(feature = "rust1", since = "1.0.0")]
1252pub trait UpperHex: PointeeSized {
1253 #[doc = include_str!("fmt_trait_method_doc.md")]
1254 #[stable(feature = "rust1", since = "1.0.0")]
1255 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1256}
1257
1258/// `p` formatting.
1259///
1260/// The `Pointer` trait should format its output as a memory location. This is commonly presented
1261/// as hexadecimal. For more information on formatters, see [the module-level documentation][module].
1262///
1263/// Printing of pointers is not a reliable way to discover how Rust programs are implemented.
1264/// The act of reading an address changes the program itself, and may change how the data is represented
1265/// in memory, and may affect which optimizations are applied to the code.
1266///
1267/// The printed pointer values are not guaranteed to be stable nor unique identifiers of objects.
1268/// Rust allows moving values to different memory locations, and may reuse the same memory locations
1269/// for different purposes.
1270///
1271/// There is no guarantee that the printed value can be converted back to a pointer.
1272///
1273/// [module]: ../../std/fmt/index.html
1274///
1275/// # Examples
1276///
1277/// Basic usage with `&i32`:
1278///
1279/// ```
1280/// let x = &42;
1281///
1282/// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
1283/// ```
1284///
1285/// Implementing `Pointer` on a type:
1286///
1287/// ```
1288/// use std::fmt;
1289///
1290/// struct Length(i32);
1291///
1292/// impl fmt::Pointer for Length {
1293/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1294/// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
1295///
1296/// let ptr = self as *const Self;
1297/// fmt::Pointer::fmt(&ptr, f)
1298/// }
1299/// }
1300///
1301/// let l = Length(42);
1302///
1303/// println!("l is in memory here: {l:p}");
1304///
1305/// let l_ptr = format!("{l:018p}");
1306/// assert_eq!(l_ptr.len(), 18);
1307/// assert_eq!(&l_ptr[..2], "0x");
1308/// ```
1309#[stable(feature = "rust1", since = "1.0.0")]
1310#[rustc_diagnostic_item = "Pointer"]
1311pub trait Pointer: PointeeSized {
1312 #[doc = include_str!("fmt_trait_method_doc.md")]
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1315}
1316
1317/// `e` formatting.
1318///
1319/// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1320///
1321/// For more information on formatters, see [the module-level documentation][module].
1322///
1323/// [module]: ../../std/fmt/index.html
1324///
1325/// # Examples
1326///
1327/// Basic usage with `f64`:
1328///
1329/// ```
1330/// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1331///
1332/// assert_eq!(format!("{x:e}"), "4.2e1");
1333/// ```
1334///
1335/// Implementing `LowerExp` on a type:
1336///
1337/// ```
1338/// use std::fmt;
1339///
1340/// struct Length(i32);
1341///
1342/// impl fmt::LowerExp for Length {
1343/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1344/// let val = f64::from(self.0);
1345/// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1346/// }
1347/// }
1348///
1349/// let l = Length(100);
1350///
1351/// assert_eq!(
1352/// format!("l in scientific notation is: {l:e}"),
1353/// "l in scientific notation is: 1e2"
1354/// );
1355///
1356/// assert_eq!(
1357/// format!("l in scientific notation is: {l:05e}"),
1358/// "l in scientific notation is: 001e2"
1359/// );
1360/// ```
1361#[stable(feature = "rust1", since = "1.0.0")]
1362pub trait LowerExp: PointeeSized {
1363 #[doc = include_str!("fmt_trait_method_doc.md")]
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1366}
1367
1368/// `E` formatting.
1369///
1370/// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1371///
1372/// For more information on formatters, see [the module-level documentation][module].
1373///
1374/// [module]: ../../std/fmt/index.html
1375///
1376/// # Examples
1377///
1378/// Basic usage with `f64`:
1379///
1380/// ```
1381/// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1382///
1383/// assert_eq!(format!("{x:E}"), "4.2E1");
1384/// ```
1385///
1386/// Implementing `UpperExp` on a type:
1387///
1388/// ```
1389/// use std::fmt;
1390///
1391/// struct Length(i32);
1392///
1393/// impl fmt::UpperExp for Length {
1394/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1395/// let val = f64::from(self.0);
1396/// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1397/// }
1398/// }
1399///
1400/// let l = Length(100);
1401///
1402/// assert_eq!(
1403/// format!("l in scientific notation is: {l:E}"),
1404/// "l in scientific notation is: 1E2"
1405/// );
1406///
1407/// assert_eq!(
1408/// format!("l in scientific notation is: {l:05E}"),
1409/// "l in scientific notation is: 001E2"
1410/// );
1411/// ```
1412#[stable(feature = "rust1", since = "1.0.0")]
1413pub trait UpperExp: PointeeSized {
1414 #[doc = include_str!("fmt_trait_method_doc.md")]
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1417}
1418
1419/// Takes an output stream and an `Arguments` struct that can be precompiled with
1420/// the `format_args!` macro.
1421///
1422/// The arguments will be formatted according to the specified format string
1423/// into the output stream provided.
1424///
1425/// # Examples
1426///
1427/// Basic usage:
1428///
1429/// ```
1430/// use std::fmt;
1431///
1432/// let mut output = String::new();
1433/// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1434/// .expect("Error occurred while trying to write in String");
1435/// assert_eq!(output, "Hello world!");
1436/// ```
1437///
1438/// Please note that using [`write!`] might be preferable. Example:
1439///
1440/// ```
1441/// use std::fmt::Write;
1442///
1443/// let mut output = String::new();
1444/// write!(&mut output, "Hello {}!", "world")
1445/// .expect("Error occurred while trying to write in String");
1446/// assert_eq!(output, "Hello world!");
1447/// ```
1448///
1449/// [`write!`]: crate::write!
1450#[stable(feature = "rust1", since = "1.0.0")]
1451pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1452 let mut formatter = Formatter::new(output, FormattingOptions::new());
1453 let mut idx = 0;
1454
1455 match args.fmt {
1456 None => {
1457 // We can use default formatting parameters for all arguments.
1458 for (i, arg) in args.args.iter().enumerate() {
1459 // SAFETY: args.args and args.pieces come from the same Arguments,
1460 // which guarantees the indexes are always within bounds.
1461 let piece = unsafe { args.pieces.get_unchecked(i) };
1462 if !piece.is_empty() {
1463 formatter.buf.write_str(*piece)?;
1464 }
1465
1466 // SAFETY: There are no formatting parameters and hence no
1467 // count arguments.
1468 unsafe {
1469 arg.fmt(&mut formatter)?;
1470 }
1471 idx += 1;
1472 }
1473 }
1474 Some(fmt) => {
1475 // Every spec has a corresponding argument that is preceded by
1476 // a string piece.
1477 for (i, arg) in fmt.iter().enumerate() {
1478 // SAFETY: fmt and args.pieces come from the same Arguments,
1479 // which guarantees the indexes are always within bounds.
1480 let piece = unsafe { args.pieces.get_unchecked(i) };
1481 if !piece.is_empty() {
1482 formatter.buf.write_str(*piece)?;
1483 }
1484 // SAFETY: arg and args.args come from the same Arguments,
1485 // which guarantees the indexes are always within bounds.
1486 unsafe { run(&mut formatter, arg, args.args) }?;
1487 idx += 1;
1488 }
1489 }
1490 }
1491
1492 // There can be only one trailing string piece left.
1493 if let Some(piece) = args.pieces.get(idx) {
1494 formatter.buf.write_str(*piece)?;
1495 }
1496
1497 Ok(())
1498}
1499
1500unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::Placeholder, args: &[rt::Argument<'_>]) -> Result {
1501 let (width, precision) =
1502 // SAFETY: arg and args come from the same Arguments,
1503 // which guarantees the indexes are always within bounds.
1504 unsafe { (getcount(args, &arg.width), getcount(args, &arg.precision)) };
1505
1506 let options = FormattingOptions { flags: arg.flags, width, precision };
1507
1508 // Extract the correct argument
1509 debug_assert!(arg.position < args.len());
1510 // SAFETY: arg and args come from the same Arguments,
1511 // which guarantees its index is always within bounds.
1512 let value = unsafe { args.get_unchecked(arg.position) };
1513
1514 // Set all the formatting options.
1515 fmt.options = options;
1516
1517 // Then actually do some printing
1518 // SAFETY: this is a placeholder argument.
1519 unsafe { value.fmt(fmt) }
1520}
1521
1522unsafe fn getcount(args: &[rt::Argument<'_>], cnt: &rt::Count) -> u16 {
1523 match *cnt {
1524 rt::Count::Is(n) => n,
1525 rt::Count::Implied => 0,
1526 rt::Count::Param(i) => {
1527 debug_assert!(i < args.len());
1528 // SAFETY: cnt and args come from the same Arguments,
1529 // which guarantees this index is always within bounds.
1530 unsafe { args.get_unchecked(i).as_u16().unwrap_unchecked() }
1531 }
1532 }
1533}
1534
1535/// Padding after the end of something. Returned by `Formatter::padding`.
1536#[must_use = "don't forget to write the post padding"]
1537pub(crate) struct PostPadding {
1538 fill: char,
1539 padding: u16,
1540}
1541
1542impl PostPadding {
1543 fn new(fill: char, padding: u16) -> PostPadding {
1544 PostPadding { fill, padding }
1545 }
1546
1547 /// Writes this post padding.
1548 pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1549 for _ in 0..self.padding {
1550 f.buf.write_char(self.fill)?;
1551 }
1552 Ok(())
1553 }
1554}
1555
1556impl<'a> Formatter<'a> {
1557 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1558 where
1559 'b: 'c,
1560 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1561 {
1562 Formatter {
1563 // We want to change this
1564 buf: wrap(self.buf),
1565
1566 // And preserve these
1567 options: self.options,
1568 }
1569 }
1570
1571 // Helper methods used for padding and processing formatting arguments that
1572 // all formatting traits can use.
1573
1574 /// Performs the correct padding for an integer which has already been
1575 /// emitted into a str. The str should *not* contain the sign for the
1576 /// integer, that will be added by this method.
1577 ///
1578 /// # Arguments
1579 ///
1580 /// * is_nonnegative - whether the original integer was either positive or zero.
1581 /// * prefix - if the '#' character (Alternate) is provided, this
1582 /// is the prefix to put in front of the number.
1583 /// * buf - the byte array that the number has been formatted into
1584 ///
1585 /// This function will correctly account for the flags provided as well as
1586 /// the minimum width. It will not take precision into account.
1587 ///
1588 /// # Examples
1589 ///
1590 /// ```
1591 /// use std::fmt;
1592 ///
1593 /// struct Foo { nb: i32 }
1594 ///
1595 /// impl Foo {
1596 /// fn new(nb: i32) -> Foo {
1597 /// Foo {
1598 /// nb,
1599 /// }
1600 /// }
1601 /// }
1602 ///
1603 /// impl fmt::Display for Foo {
1604 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1605 /// // We need to remove "-" from the number output.
1606 /// let tmp = self.nb.abs().to_string();
1607 ///
1608 /// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1609 /// }
1610 /// }
1611 ///
1612 /// assert_eq!(format!("{}", Foo::new(2)), "2");
1613 /// assert_eq!(format!("{}", Foo::new(-1)), "-1");
1614 /// assert_eq!(format!("{}", Foo::new(0)), "0");
1615 /// assert_eq!(format!("{:#}", Foo::new(-1)), "-Foo 1");
1616 /// assert_eq!(format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1617 /// ```
1618 #[stable(feature = "rust1", since = "1.0.0")]
1619 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1620 let mut width = buf.len();
1621
1622 let mut sign = None;
1623 if !is_nonnegative {
1624 sign = Some('-');
1625 width += 1;
1626 } else if self.sign_plus() {
1627 sign = Some('+');
1628 width += 1;
1629 }
1630
1631 let prefix = if self.alternate() {
1632 width += prefix.chars().count();
1633 Some(prefix)
1634 } else {
1635 None
1636 };
1637
1638 // Writes the sign if it exists, and then the prefix if it was requested
1639 #[inline(never)]
1640 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1641 if let Some(c) = sign {
1642 f.buf.write_char(c)?;
1643 }
1644 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1645 }
1646
1647 // The `width` field is more of a `min-width` parameter at this point.
1648 let min = self.options.width;
1649 if width >= usize::from(min) {
1650 // We're over the minimum width, so then we can just write the bytes.
1651 write_prefix(self, sign, prefix)?;
1652 self.buf.write_str(buf)
1653 } else if self.sign_aware_zero_pad() {
1654 // The sign and prefix goes before the padding if the fill character
1655 // is zero
1656 let old_options = self.options;
1657 self.options.fill('0').align(Some(Alignment::Right));
1658 write_prefix(self, sign, prefix)?;
1659 let post_padding = self.padding(min - width as u16, Alignment::Right)?;
1660 self.buf.write_str(buf)?;
1661 post_padding.write(self)?;
1662 self.options = old_options;
1663 Ok(())
1664 } else {
1665 // Otherwise, the sign and prefix goes after the padding
1666 let post_padding = self.padding(min - width as u16, Alignment::Right)?;
1667 write_prefix(self, sign, prefix)?;
1668 self.buf.write_str(buf)?;
1669 post_padding.write(self)
1670 }
1671 }
1672
1673 /// Takes a string slice and emits it to the internal buffer after applying
1674 /// the relevant formatting flags specified.
1675 ///
1676 /// The flags recognized for generic strings are:
1677 ///
1678 /// * width - the minimum width of what to emit
1679 /// * fill/align - what to emit and where to emit it if the string
1680 /// provided needs to be padded
1681 /// * precision - the maximum length to emit, the string is truncated if it
1682 /// is longer than this length
1683 ///
1684 /// Notably this function ignores the `flag` parameters.
1685 ///
1686 /// # Examples
1687 ///
1688 /// ```
1689 /// use std::fmt;
1690 ///
1691 /// struct Foo;
1692 ///
1693 /// impl fmt::Display for Foo {
1694 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1695 /// formatter.pad("Foo")
1696 /// }
1697 /// }
1698 ///
1699 /// assert_eq!(format!("{Foo:<4}"), "Foo ");
1700 /// assert_eq!(format!("{Foo:0>4}"), "0Foo");
1701 /// ```
1702 #[stable(feature = "rust1", since = "1.0.0")]
1703 pub fn pad(&mut self, s: &str) -> Result {
1704 // Make sure there's a fast path up front.
1705 if self.options.flags & (flags::WIDTH_FLAG | flags::PRECISION_FLAG) == 0 {
1706 return self.buf.write_str(s);
1707 }
1708
1709 // The `precision` field can be interpreted as a maximum width for the
1710 // string being formatted.
1711 let (s, char_count) = if let Some(max_char_count) = self.options.get_precision() {
1712 let mut iter = s.char_indices();
1713 let remaining = match iter.advance_by(usize::from(max_char_count)) {
1714 Ok(()) => 0,
1715 Err(remaining) => remaining.get(),
1716 };
1717 // SAFETY: The offset of `.char_indices()` is guaranteed to be
1718 // in-bounds and between character boundaries.
1719 let truncated = unsafe { s.get_unchecked(..iter.offset()) };
1720 (truncated, usize::from(max_char_count) - remaining)
1721 } else {
1722 // Use the optimized char counting algorithm for the full string.
1723 (s, s.chars().count())
1724 };
1725
1726 // The `width` field is more of a minimum width parameter at this point.
1727 if char_count < usize::from(self.options.width) {
1728 // If we're under the minimum width, then fill up the minimum width
1729 // with the specified string + some alignment.
1730 let post_padding =
1731 self.padding(self.options.width - char_count as u16, Alignment::Left)?;
1732 self.buf.write_str(s)?;
1733 post_padding.write(self)
1734 } else {
1735 // If we're over the minimum width or there is no minimum width, we
1736 // can just emit the string.
1737 self.buf.write_str(s)
1738 }
1739 }
1740
1741 /// Writes the pre-padding and returns the unwritten post-padding.
1742 ///
1743 /// Callers are responsible for ensuring post-padding is written after the
1744 /// thing that is being padded.
1745 pub(crate) fn padding(
1746 &mut self,
1747 padding: u16,
1748 default: Alignment,
1749 ) -> result::Result<PostPadding, Error> {
1750 let align = self.options.get_align().unwrap_or(default);
1751 let fill = self.options.get_fill();
1752
1753 let padding_left = match align {
1754 Alignment::Left => 0,
1755 Alignment::Right => padding,
1756 Alignment::Center => padding / 2,
1757 };
1758
1759 for _ in 0..padding_left {
1760 self.buf.write_char(fill)?;
1761 }
1762
1763 Ok(PostPadding::new(fill, padding - padding_left))
1764 }
1765
1766 /// Takes the formatted parts and applies the padding.
1767 ///
1768 /// Assumes that the caller already has rendered the parts with required precision,
1769 /// so that `self.precision` can be ignored.
1770 ///
1771 /// # Safety
1772 ///
1773 /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
1774 unsafe fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1775 if self.options.width == 0 {
1776 // this is the common case and we take a shortcut
1777 // SAFETY: Per the precondition.
1778 unsafe { self.write_formatted_parts(formatted) }
1779 } else {
1780 // for the sign-aware zero padding, we render the sign first and
1781 // behave as if we had no sign from the beginning.
1782 let mut formatted = formatted.clone();
1783 let mut width = self.options.width;
1784 let old_options = self.options;
1785 if self.sign_aware_zero_pad() {
1786 // a sign always goes first
1787 let sign = formatted.sign;
1788 self.buf.write_str(sign)?;
1789
1790 // remove the sign from the formatted parts
1791 formatted.sign = "";
1792 width = width.saturating_sub(sign.len() as u16);
1793 self.options.fill('0').align(Some(Alignment::Right));
1794 }
1795
1796 // remaining parts go through the ordinary padding process.
1797 let len = formatted.len();
1798 let ret = if usize::from(width) <= len {
1799 // no padding
1800 // SAFETY: Per the precondition.
1801 unsafe { self.write_formatted_parts(&formatted) }
1802 } else {
1803 let post_padding = self.padding(width - len as u16, Alignment::Right)?;
1804 // SAFETY: Per the precondition.
1805 unsafe {
1806 self.write_formatted_parts(&formatted)?;
1807 }
1808 post_padding.write(self)
1809 };
1810 self.options = old_options;
1811 ret
1812 }
1813 }
1814
1815 /// # Safety
1816 ///
1817 /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
1818 unsafe fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1819 unsafe fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1820 // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1821 // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1822 // `b'0'` and `b'9'`, which means `s` is valid UTF-8. It's safe to use for
1823 // `numfmt::Part::Copy` due to this function's precondition.
1824 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1825 }
1826
1827 if !formatted.sign.is_empty() {
1828 self.buf.write_str(formatted.sign)?;
1829 }
1830 for part in formatted.parts {
1831 match *part {
1832 numfmt::Part::Zero(mut nzeroes) => {
1833 const ZEROES: &str = // 64 zeroes
1834 "0000000000000000000000000000000000000000000000000000000000000000";
1835 while nzeroes > ZEROES.len() {
1836 self.buf.write_str(ZEROES)?;
1837 nzeroes -= ZEROES.len();
1838 }
1839 if nzeroes > 0 {
1840 self.buf.write_str(&ZEROES[..nzeroes])?;
1841 }
1842 }
1843 numfmt::Part::Num(mut v) => {
1844 let mut s = [0; 5];
1845 let len = part.len();
1846 for c in s[..len].iter_mut().rev() {
1847 *c = b'0' + (v % 10) as u8;
1848 v /= 10;
1849 }
1850 // SAFETY: Per the precondition.
1851 unsafe {
1852 write_bytes(self.buf, &s[..len])?;
1853 }
1854 }
1855 // SAFETY: Per the precondition.
1856 numfmt::Part::Copy(buf) => unsafe {
1857 write_bytes(self.buf, buf)?;
1858 },
1859 }
1860 }
1861 Ok(())
1862 }
1863
1864 /// Writes some data to the underlying buffer contained within this
1865 /// formatter.
1866 ///
1867 /// # Examples
1868 ///
1869 /// ```
1870 /// use std::fmt;
1871 ///
1872 /// struct Foo;
1873 ///
1874 /// impl fmt::Display for Foo {
1875 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1876 /// formatter.write_str("Foo")
1877 /// // This is equivalent to:
1878 /// // write!(formatter, "Foo")
1879 /// }
1880 /// }
1881 ///
1882 /// assert_eq!(format!("{Foo}"), "Foo");
1883 /// assert_eq!(format!("{Foo:0>8}"), "Foo");
1884 /// ```
1885 #[stable(feature = "rust1", since = "1.0.0")]
1886 pub fn write_str(&mut self, data: &str) -> Result {
1887 self.buf.write_str(data)
1888 }
1889
1890 /// Glue for usage of the [`write!`] macro with implementors of this trait.
1891 ///
1892 /// This method should generally not be invoked manually, but rather through
1893 /// the [`write!`] macro itself.
1894 ///
1895 /// Writes some formatted information into this instance.
1896 ///
1897 /// # Examples
1898 ///
1899 /// ```
1900 /// use std::fmt;
1901 ///
1902 /// struct Foo(i32);
1903 ///
1904 /// impl fmt::Display for Foo {
1905 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1906 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1907 /// }
1908 /// }
1909 ///
1910 /// assert_eq!(format!("{}", Foo(-1)), "Foo -1");
1911 /// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
1912 /// ```
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 #[inline]
1915 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1916 if let Some(s) = fmt.as_statically_known_str() {
1917 self.buf.write_str(s)
1918 } else {
1919 write(self.buf, fmt)
1920 }
1921 }
1922
1923 /// Returns flags for formatting.
1924 #[must_use]
1925 #[stable(feature = "rust1", since = "1.0.0")]
1926 #[deprecated(
1927 since = "1.24.0",
1928 note = "use the `sign_plus`, `sign_minus`, `alternate`, \
1929 or `sign_aware_zero_pad` methods instead"
1930 )]
1931 pub fn flags(&self) -> u32 {
1932 // Extract the debug upper/lower hex, zero pad, alternate, and plus/minus flags
1933 // to stay compatible with older versions of Rust.
1934 self.options.flags >> 21 & 0x3F
1935 }
1936
1937 /// Returns the character used as 'fill' whenever there is alignment.
1938 ///
1939 /// # Examples
1940 ///
1941 /// ```
1942 /// use std::fmt;
1943 ///
1944 /// struct Foo;
1945 ///
1946 /// impl fmt::Display for Foo {
1947 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1948 /// let c = formatter.fill();
1949 /// if let Some(width) = formatter.width() {
1950 /// for _ in 0..width {
1951 /// write!(formatter, "{c}")?;
1952 /// }
1953 /// Ok(())
1954 /// } else {
1955 /// write!(formatter, "{c}")
1956 /// }
1957 /// }
1958 /// }
1959 ///
1960 /// // We set alignment to the right with ">".
1961 /// assert_eq!(format!("{Foo:G>3}"), "GGG");
1962 /// assert_eq!(format!("{Foo:t>6}"), "tttttt");
1963 /// ```
1964 #[must_use]
1965 #[stable(feature = "fmt_flags", since = "1.5.0")]
1966 pub fn fill(&self) -> char {
1967 self.options.get_fill()
1968 }
1969
1970 /// Returns a flag indicating what form of alignment was requested.
1971 ///
1972 /// # Examples
1973 ///
1974 /// ```
1975 /// use std::fmt::{self, Alignment};
1976 ///
1977 /// struct Foo;
1978 ///
1979 /// impl fmt::Display for Foo {
1980 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1981 /// let s = if let Some(s) = formatter.align() {
1982 /// match s {
1983 /// Alignment::Left => "left",
1984 /// Alignment::Right => "right",
1985 /// Alignment::Center => "center",
1986 /// }
1987 /// } else {
1988 /// "into the void"
1989 /// };
1990 /// write!(formatter, "{s}")
1991 /// }
1992 /// }
1993 ///
1994 /// assert_eq!(format!("{Foo:<}"), "left");
1995 /// assert_eq!(format!("{Foo:>}"), "right");
1996 /// assert_eq!(format!("{Foo:^}"), "center");
1997 /// assert_eq!(format!("{Foo}"), "into the void");
1998 /// ```
1999 #[must_use]
2000 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
2001 pub fn align(&self) -> Option<Alignment> {
2002 self.options.get_align()
2003 }
2004
2005 /// Returns the optionally specified integer width that the output should be.
2006 ///
2007 /// # Examples
2008 ///
2009 /// ```
2010 /// use std::fmt;
2011 ///
2012 /// struct Foo(i32);
2013 ///
2014 /// impl fmt::Display for Foo {
2015 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2016 /// if let Some(width) = formatter.width() {
2017 /// // If we received a width, we use it
2018 /// write!(formatter, "{:width$}", format!("Foo({})", self.0), width = width)
2019 /// } else {
2020 /// // Otherwise we do nothing special
2021 /// write!(formatter, "Foo({})", self.0)
2022 /// }
2023 /// }
2024 /// }
2025 ///
2026 /// assert_eq!(format!("{:10}", Foo(23)), "Foo(23) ");
2027 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2028 /// ```
2029 #[must_use]
2030 #[stable(feature = "fmt_flags", since = "1.5.0")]
2031 pub fn width(&self) -> Option<usize> {
2032 if self.options.flags & flags::WIDTH_FLAG == 0 {
2033 None
2034 } else {
2035 Some(self.options.width as usize)
2036 }
2037 }
2038
2039 /// Returns the optionally specified precision for numeric types.
2040 /// Alternatively, the maximum width for string types.
2041 ///
2042 /// # Examples
2043 ///
2044 /// ```
2045 /// use std::fmt;
2046 ///
2047 /// struct Foo(f32);
2048 ///
2049 /// impl fmt::Display for Foo {
2050 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2051 /// if let Some(precision) = formatter.precision() {
2052 /// // If we received a precision, we use it.
2053 /// write!(formatter, "Foo({1:.*})", precision, self.0)
2054 /// } else {
2055 /// // Otherwise we default to 2.
2056 /// write!(formatter, "Foo({:.2})", self.0)
2057 /// }
2058 /// }
2059 /// }
2060 ///
2061 /// assert_eq!(format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
2062 /// assert_eq!(format!("{}", Foo(23.2)), "Foo(23.20)");
2063 /// ```
2064 #[must_use]
2065 #[stable(feature = "fmt_flags", since = "1.5.0")]
2066 pub fn precision(&self) -> Option<usize> {
2067 if self.options.flags & flags::PRECISION_FLAG == 0 {
2068 None
2069 } else {
2070 Some(self.options.precision as usize)
2071 }
2072 }
2073
2074 /// Determines if the `+` flag was specified.
2075 ///
2076 /// # Examples
2077 ///
2078 /// ```
2079 /// use std::fmt;
2080 ///
2081 /// struct Foo(i32);
2082 ///
2083 /// impl fmt::Display for Foo {
2084 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2085 /// if formatter.sign_plus() {
2086 /// write!(formatter,
2087 /// "Foo({}{})",
2088 /// if self.0 < 0 { '-' } else { '+' },
2089 /// self.0.abs())
2090 /// } else {
2091 /// write!(formatter, "Foo({})", self.0)
2092 /// }
2093 /// }
2094 /// }
2095 ///
2096 /// assert_eq!(format!("{:+}", Foo(23)), "Foo(+23)");
2097 /// assert_eq!(format!("{:+}", Foo(-23)), "Foo(-23)");
2098 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2099 /// ```
2100 #[must_use]
2101 #[stable(feature = "fmt_flags", since = "1.5.0")]
2102 pub fn sign_plus(&self) -> bool {
2103 self.options.flags & flags::SIGN_PLUS_FLAG != 0
2104 }
2105
2106 /// Determines if the `-` flag was specified.
2107 ///
2108 /// # Examples
2109 ///
2110 /// ```
2111 /// use std::fmt;
2112 ///
2113 /// struct Foo(i32);
2114 ///
2115 /// impl fmt::Display for Foo {
2116 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2117 /// if formatter.sign_minus() {
2118 /// // You want a minus sign? Have one!
2119 /// write!(formatter, "-Foo({})", self.0)
2120 /// } else {
2121 /// write!(formatter, "Foo({})", self.0)
2122 /// }
2123 /// }
2124 /// }
2125 ///
2126 /// assert_eq!(format!("{:-}", Foo(23)), "-Foo(23)");
2127 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2128 /// ```
2129 #[must_use]
2130 #[stable(feature = "fmt_flags", since = "1.5.0")]
2131 pub fn sign_minus(&self) -> bool {
2132 self.options.flags & flags::SIGN_MINUS_FLAG != 0
2133 }
2134
2135 /// Determines if the `#` flag was specified.
2136 ///
2137 /// # Examples
2138 ///
2139 /// ```
2140 /// use std::fmt;
2141 ///
2142 /// struct Foo(i32);
2143 ///
2144 /// impl fmt::Display for Foo {
2145 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2146 /// if formatter.alternate() {
2147 /// write!(formatter, "Foo({})", self.0)
2148 /// } else {
2149 /// write!(formatter, "{}", self.0)
2150 /// }
2151 /// }
2152 /// }
2153 ///
2154 /// assert_eq!(format!("{:#}", Foo(23)), "Foo(23)");
2155 /// assert_eq!(format!("{}", Foo(23)), "23");
2156 /// ```
2157 #[must_use]
2158 #[stable(feature = "fmt_flags", since = "1.5.0")]
2159 pub fn alternate(&self) -> bool {
2160 self.options.flags & flags::ALTERNATE_FLAG != 0
2161 }
2162
2163 /// Determines if the `0` flag was specified.
2164 ///
2165 /// # Examples
2166 ///
2167 /// ```
2168 /// use std::fmt;
2169 ///
2170 /// struct Foo(i32);
2171 ///
2172 /// impl fmt::Display for Foo {
2173 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2174 /// assert!(formatter.sign_aware_zero_pad());
2175 /// assert_eq!(formatter.width(), Some(4));
2176 /// // We ignore the formatter's options.
2177 /// write!(formatter, "{}", self.0)
2178 /// }
2179 /// }
2180 ///
2181 /// assert_eq!(format!("{:04}", Foo(23)), "23");
2182 /// ```
2183 #[must_use]
2184 #[stable(feature = "fmt_flags", since = "1.5.0")]
2185 pub fn sign_aware_zero_pad(&self) -> bool {
2186 self.options.flags & flags::SIGN_AWARE_ZERO_PAD_FLAG != 0
2187 }
2188
2189 // FIXME: Decide what public API we want for these two flags.
2190 // https://github.com/rust-lang/rust/issues/48584
2191 fn debug_lower_hex(&self) -> bool {
2192 self.options.flags & flags::DEBUG_LOWER_HEX_FLAG != 0
2193 }
2194 fn debug_upper_hex(&self) -> bool {
2195 self.options.flags & flags::DEBUG_UPPER_HEX_FLAG != 0
2196 }
2197
2198 /// Creates a [`DebugStruct`] builder designed to assist with creation of
2199 /// [`fmt::Debug`] implementations for structs.
2200 ///
2201 /// [`fmt::Debug`]: self::Debug
2202 ///
2203 /// # Examples
2204 ///
2205 /// ```rust
2206 /// use std::fmt;
2207 /// use std::net::Ipv4Addr;
2208 ///
2209 /// struct Foo {
2210 /// bar: i32,
2211 /// baz: String,
2212 /// addr: Ipv4Addr,
2213 /// }
2214 ///
2215 /// impl fmt::Debug for Foo {
2216 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2217 /// fmt.debug_struct("Foo")
2218 /// .field("bar", &self.bar)
2219 /// .field("baz", &self.baz)
2220 /// .field("addr", &format_args!("{}", self.addr))
2221 /// .finish()
2222 /// }
2223 /// }
2224 ///
2225 /// assert_eq!(
2226 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
2227 /// format!("{:?}", Foo {
2228 /// bar: 10,
2229 /// baz: "Hello World".to_string(),
2230 /// addr: Ipv4Addr::new(127, 0, 0, 1),
2231 /// })
2232 /// );
2233 /// ```
2234 #[stable(feature = "debug_builders", since = "1.2.0")]
2235 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
2236 builders::debug_struct_new(self, name)
2237 }
2238
2239 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2240 /// binaries. `debug_struct_fields_finish` is more general, but this is
2241 /// faster for 1 field.
2242 #[doc(hidden)]
2243 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2244 pub fn debug_struct_field1_finish<'b>(
2245 &'b mut self,
2246 name: &str,
2247 name1: &str,
2248 value1: &dyn Debug,
2249 ) -> Result {
2250 let mut builder = builders::debug_struct_new(self, name);
2251 builder.field(name1, value1);
2252 builder.finish()
2253 }
2254
2255 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2256 /// binaries. `debug_struct_fields_finish` is more general, but this is
2257 /// faster for 2 fields.
2258 #[doc(hidden)]
2259 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2260 pub fn debug_struct_field2_finish<'b>(
2261 &'b mut self,
2262 name: &str,
2263 name1: &str,
2264 value1: &dyn Debug,
2265 name2: &str,
2266 value2: &dyn Debug,
2267 ) -> Result {
2268 let mut builder = builders::debug_struct_new(self, name);
2269 builder.field(name1, value1);
2270 builder.field(name2, value2);
2271 builder.finish()
2272 }
2273
2274 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2275 /// binaries. `debug_struct_fields_finish` is more general, but this is
2276 /// faster for 3 fields.
2277 #[doc(hidden)]
2278 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2279 pub fn debug_struct_field3_finish<'b>(
2280 &'b mut self,
2281 name: &str,
2282 name1: &str,
2283 value1: &dyn Debug,
2284 name2: &str,
2285 value2: &dyn Debug,
2286 name3: &str,
2287 value3: &dyn Debug,
2288 ) -> Result {
2289 let mut builder = builders::debug_struct_new(self, name);
2290 builder.field(name1, value1);
2291 builder.field(name2, value2);
2292 builder.field(name3, value3);
2293 builder.finish()
2294 }
2295
2296 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2297 /// binaries. `debug_struct_fields_finish` is more general, but this is
2298 /// faster for 4 fields.
2299 #[doc(hidden)]
2300 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2301 pub fn debug_struct_field4_finish<'b>(
2302 &'b mut self,
2303 name: &str,
2304 name1: &str,
2305 value1: &dyn Debug,
2306 name2: &str,
2307 value2: &dyn Debug,
2308 name3: &str,
2309 value3: &dyn Debug,
2310 name4: &str,
2311 value4: &dyn Debug,
2312 ) -> Result {
2313 let mut builder = builders::debug_struct_new(self, name);
2314 builder.field(name1, value1);
2315 builder.field(name2, value2);
2316 builder.field(name3, value3);
2317 builder.field(name4, value4);
2318 builder.finish()
2319 }
2320
2321 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2322 /// binaries. `debug_struct_fields_finish` is more general, but this is
2323 /// faster for 5 fields.
2324 #[doc(hidden)]
2325 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2326 pub fn debug_struct_field5_finish<'b>(
2327 &'b mut self,
2328 name: &str,
2329 name1: &str,
2330 value1: &dyn Debug,
2331 name2: &str,
2332 value2: &dyn Debug,
2333 name3: &str,
2334 value3: &dyn Debug,
2335 name4: &str,
2336 value4: &dyn Debug,
2337 name5: &str,
2338 value5: &dyn Debug,
2339 ) -> Result {
2340 let mut builder = builders::debug_struct_new(self, name);
2341 builder.field(name1, value1);
2342 builder.field(name2, value2);
2343 builder.field(name3, value3);
2344 builder.field(name4, value4);
2345 builder.field(name5, value5);
2346 builder.finish()
2347 }
2348
2349 /// Shrinks `derive(Debug)` code, for faster compilation and smaller binaries.
2350 /// For the cases not covered by `debug_struct_field[12345]_finish`.
2351 #[doc(hidden)]
2352 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2353 pub fn debug_struct_fields_finish<'b>(
2354 &'b mut self,
2355 name: &str,
2356 names: &[&str],
2357 values: &[&dyn Debug],
2358 ) -> Result {
2359 assert_eq!(names.len(), values.len());
2360 let mut builder = builders::debug_struct_new(self, name);
2361 for (name, value) in iter::zip(names, values) {
2362 builder.field(name, value);
2363 }
2364 builder.finish()
2365 }
2366
2367 /// Creates a `DebugTuple` builder designed to assist with creation of
2368 /// `fmt::Debug` implementations for tuple structs.
2369 ///
2370 /// # Examples
2371 ///
2372 /// ```rust
2373 /// use std::fmt;
2374 /// use std::marker::PhantomData;
2375 ///
2376 /// struct Foo<T>(i32, String, PhantomData<T>);
2377 ///
2378 /// impl<T> fmt::Debug for Foo<T> {
2379 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2380 /// fmt.debug_tuple("Foo")
2381 /// .field(&self.0)
2382 /// .field(&self.1)
2383 /// .field(&format_args!("_"))
2384 /// .finish()
2385 /// }
2386 /// }
2387 ///
2388 /// assert_eq!(
2389 /// "Foo(10, \"Hello\", _)",
2390 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
2391 /// );
2392 /// ```
2393 #[stable(feature = "debug_builders", since = "1.2.0")]
2394 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
2395 builders::debug_tuple_new(self, name)
2396 }
2397
2398 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2399 /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2400 /// for 1 field.
2401 #[doc(hidden)]
2402 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2403 pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result {
2404 let mut builder = builders::debug_tuple_new(self, name);
2405 builder.field(value1);
2406 builder.finish()
2407 }
2408
2409 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2410 /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2411 /// for 2 fields.
2412 #[doc(hidden)]
2413 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2414 pub fn debug_tuple_field2_finish<'b>(
2415 &'b mut self,
2416 name: &str,
2417 value1: &dyn Debug,
2418 value2: &dyn Debug,
2419 ) -> Result {
2420 let mut builder = builders::debug_tuple_new(self, name);
2421 builder.field(value1);
2422 builder.field(value2);
2423 builder.finish()
2424 }
2425
2426 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2427 /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2428 /// for 3 fields.
2429 #[doc(hidden)]
2430 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2431 pub fn debug_tuple_field3_finish<'b>(
2432 &'b mut self,
2433 name: &str,
2434 value1: &dyn Debug,
2435 value2: &dyn Debug,
2436 value3: &dyn Debug,
2437 ) -> Result {
2438 let mut builder = builders::debug_tuple_new(self, name);
2439 builder.field(value1);
2440 builder.field(value2);
2441 builder.field(value3);
2442 builder.finish()
2443 }
2444
2445 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2446 /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2447 /// for 4 fields.
2448 #[doc(hidden)]
2449 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2450 pub fn debug_tuple_field4_finish<'b>(
2451 &'b mut self,
2452 name: &str,
2453 value1: &dyn Debug,
2454 value2: &dyn Debug,
2455 value3: &dyn Debug,
2456 value4: &dyn Debug,
2457 ) -> Result {
2458 let mut builder = builders::debug_tuple_new(self, name);
2459 builder.field(value1);
2460 builder.field(value2);
2461 builder.field(value3);
2462 builder.field(value4);
2463 builder.finish()
2464 }
2465
2466 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2467 /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2468 /// for 5 fields.
2469 #[doc(hidden)]
2470 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2471 pub fn debug_tuple_field5_finish<'b>(
2472 &'b mut self,
2473 name: &str,
2474 value1: &dyn Debug,
2475 value2: &dyn Debug,
2476 value3: &dyn Debug,
2477 value4: &dyn Debug,
2478 value5: &dyn Debug,
2479 ) -> Result {
2480 let mut builder = builders::debug_tuple_new(self, name);
2481 builder.field(value1);
2482 builder.field(value2);
2483 builder.field(value3);
2484 builder.field(value4);
2485 builder.field(value5);
2486 builder.finish()
2487 }
2488
2489 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2490 /// binaries. For the cases not covered by `debug_tuple_field[12345]_finish`.
2491 #[doc(hidden)]
2492 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2493 pub fn debug_tuple_fields_finish<'b>(
2494 &'b mut self,
2495 name: &str,
2496 values: &[&dyn Debug],
2497 ) -> Result {
2498 let mut builder = builders::debug_tuple_new(self, name);
2499 for value in values {
2500 builder.field(value);
2501 }
2502 builder.finish()
2503 }
2504
2505 /// Creates a `DebugList` builder designed to assist with creation of
2506 /// `fmt::Debug` implementations for list-like structures.
2507 ///
2508 /// # Examples
2509 ///
2510 /// ```rust
2511 /// use std::fmt;
2512 ///
2513 /// struct Foo(Vec<i32>);
2514 ///
2515 /// impl fmt::Debug for Foo {
2516 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2517 /// fmt.debug_list().entries(self.0.iter()).finish()
2518 /// }
2519 /// }
2520 ///
2521 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2522 /// ```
2523 #[stable(feature = "debug_builders", since = "1.2.0")]
2524 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2525 builders::debug_list_new(self)
2526 }
2527
2528 /// Creates a `DebugSet` builder designed to assist with creation of
2529 /// `fmt::Debug` implementations for set-like structures.
2530 ///
2531 /// # Examples
2532 ///
2533 /// ```rust
2534 /// use std::fmt;
2535 ///
2536 /// struct Foo(Vec<i32>);
2537 ///
2538 /// impl fmt::Debug for Foo {
2539 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2540 /// fmt.debug_set().entries(self.0.iter()).finish()
2541 /// }
2542 /// }
2543 ///
2544 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2545 /// ```
2546 ///
2547 /// [`format_args!`]: crate::format_args
2548 ///
2549 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2550 /// to build a list of match arms:
2551 ///
2552 /// ```rust
2553 /// use std::fmt;
2554 ///
2555 /// struct Arm<'a, L, R>(&'a (L, R));
2556 /// struct Table<'a, K, V>(&'a [(K, V)], V);
2557 ///
2558 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2559 /// where
2560 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
2561 /// {
2562 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2563 /// L::fmt(&(self.0).0, fmt)?;
2564 /// fmt.write_str(" => ")?;
2565 /// R::fmt(&(self.0).1, fmt)
2566 /// }
2567 /// }
2568 ///
2569 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2570 /// where
2571 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
2572 /// {
2573 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2574 /// fmt.debug_set()
2575 /// .entries(self.0.iter().map(Arm))
2576 /// .entry(&Arm(&(format_args!("_"), &self.1)))
2577 /// .finish()
2578 /// }
2579 /// }
2580 /// ```
2581 #[stable(feature = "debug_builders", since = "1.2.0")]
2582 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2583 builders::debug_set_new(self)
2584 }
2585
2586 /// Creates a `DebugMap` builder designed to assist with creation of
2587 /// `fmt::Debug` implementations for map-like structures.
2588 ///
2589 /// # Examples
2590 ///
2591 /// ```rust
2592 /// use std::fmt;
2593 ///
2594 /// struct Foo(Vec<(String, i32)>);
2595 ///
2596 /// impl fmt::Debug for Foo {
2597 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2598 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2599 /// }
2600 /// }
2601 ///
2602 /// assert_eq!(
2603 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2604 /// r#"{"A": 10, "B": 11}"#
2605 /// );
2606 /// ```
2607 #[stable(feature = "debug_builders", since = "1.2.0")]
2608 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2609 builders::debug_map_new(self)
2610 }
2611
2612 /// Returns the sign of this formatter (`+` or `-`).
2613 #[unstable(feature = "formatting_options", issue = "118117")]
2614 pub const fn sign(&self) -> Option<Sign> {
2615 self.options.get_sign()
2616 }
2617
2618 /// Returns the formatting options this formatter corresponds to.
2619 #[unstable(feature = "formatting_options", issue = "118117")]
2620 pub const fn options(&self) -> FormattingOptions {
2621 self.options
2622 }
2623}
2624
2625#[stable(since = "1.2.0", feature = "formatter_write")]
2626impl Write for Formatter<'_> {
2627 fn write_str(&mut self, s: &str) -> Result {
2628 self.buf.write_str(s)
2629 }
2630
2631 fn write_char(&mut self, c: char) -> Result {
2632 self.buf.write_char(c)
2633 }
2634
2635 #[inline]
2636 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2637 if let Some(s) = args.as_statically_known_str() {
2638 self.buf.write_str(s)
2639 } else {
2640 write(self.buf, args)
2641 }
2642 }
2643}
2644
2645#[stable(feature = "rust1", since = "1.0.0")]
2646impl Display for Error {
2647 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2648 Display::fmt("an error occurred when formatting an argument", f)
2649 }
2650}
2651
2652// Implementations of the core formatting traits
2653
2654macro_rules! fmt_refs {
2655 ($($tr:ident),*) => {
2656 $(
2657 #[stable(feature = "rust1", since = "1.0.0")]
2658 impl<T: PointeeSized + $tr> $tr for &T {
2659 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2660 }
2661 #[stable(feature = "rust1", since = "1.0.0")]
2662 impl<T: PointeeSized + $tr> $tr for &mut T {
2663 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2664 }
2665 )*
2666 }
2667}
2668
2669fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2670
2671#[unstable(feature = "never_type", issue = "35121")]
2672impl Debug for ! {
2673 #[inline]
2674 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2675 *self
2676 }
2677}
2678
2679#[unstable(feature = "never_type", issue = "35121")]
2680impl Display for ! {
2681 #[inline]
2682 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2683 *self
2684 }
2685}
2686
2687#[stable(feature = "rust1", since = "1.0.0")]
2688impl Debug for bool {
2689 #[inline]
2690 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2691 Display::fmt(self, f)
2692 }
2693}
2694
2695#[stable(feature = "rust1", since = "1.0.0")]
2696impl Display for bool {
2697 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2698 Display::fmt(if *self { "true" } else { "false" }, f)
2699 }
2700}
2701
2702#[stable(feature = "rust1", since = "1.0.0")]
2703impl Debug for str {
2704 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2705 f.write_char('"')?;
2706
2707 // substring we know is printable
2708 let mut printable_range = 0..0;
2709
2710 fn needs_escape(b: u8) -> bool {
2711 b > 0x7E || b < 0x20 || b == b'\\' || b == b'"'
2712 }
2713
2714 // the loop here first skips over runs of printable ASCII as a fast path.
2715 // other chars (unicode, or ASCII that needs escaping) are then handled per-`char`.
2716 let mut rest = self;
2717 while rest.len() > 0 {
2718 let Some(non_printable_start) = rest.as_bytes().iter().position(|&b| needs_escape(b))
2719 else {
2720 printable_range.end += rest.len();
2721 break;
2722 };
2723
2724 printable_range.end += non_printable_start;
2725 // SAFETY: the position was derived from an iterator, so is known to be within bounds, and at a char boundary
2726 rest = unsafe { rest.get_unchecked(non_printable_start..) };
2727
2728 let mut chars = rest.chars();
2729 if let Some(c) = chars.next() {
2730 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2731 escape_grapheme_extended: true,
2732 escape_single_quote: false,
2733 escape_double_quote: true,
2734 });
2735 if esc.len() != 1 {
2736 f.write_str(&self[printable_range.clone()])?;
2737 Display::fmt(&esc, f)?;
2738 printable_range.start = printable_range.end + c.len_utf8();
2739 }
2740 printable_range.end += c.len_utf8();
2741 }
2742 rest = chars.as_str();
2743 }
2744
2745 f.write_str(&self[printable_range])?;
2746
2747 f.write_char('"')
2748 }
2749}
2750
2751#[stable(feature = "rust1", since = "1.0.0")]
2752impl Display for str {
2753 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2754 f.pad(self)
2755 }
2756}
2757
2758#[stable(feature = "rust1", since = "1.0.0")]
2759impl Debug for char {
2760 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2761 f.write_char('\'')?;
2762 let esc = self.escape_debug_ext(EscapeDebugExtArgs {
2763 escape_grapheme_extended: true,
2764 escape_single_quote: true,
2765 escape_double_quote: false,
2766 });
2767 Display::fmt(&esc, f)?;
2768 f.write_char('\'')
2769 }
2770}
2771
2772#[stable(feature = "rust1", since = "1.0.0")]
2773impl Display for char {
2774 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2775 if f.options.flags & (flags::WIDTH_FLAG | flags::PRECISION_FLAG) == 0 {
2776 f.write_char(*self)
2777 } else {
2778 f.pad(self.encode_utf8(&mut [0; MAX_LEN_UTF8]))
2779 }
2780 }
2781}
2782
2783#[stable(feature = "rust1", since = "1.0.0")]
2784impl<T: PointeeSized> Pointer for *const T {
2785 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2786 if <<T as core::ptr::Pointee>::Metadata as core::unit::IsUnit>::is_unit() {
2787 pointer_fmt_inner(self.expose_provenance(), f)
2788 } else {
2789 f.debug_struct("Pointer")
2790 .field_with("addr", |f| pointer_fmt_inner(self.expose_provenance(), f))
2791 .field("metadata", &core::ptr::metadata(*self))
2792 .finish()
2793 }
2794 }
2795}
2796
2797/// Since the formatting will be identical for all pointer types, uses a
2798/// non-monomorphized implementation for the actual formatting to reduce the
2799/// amount of codegen work needed.
2800///
2801/// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
2802/// `fn(...) -> ...` without using [problematic] "Oxford Casts".
2803///
2804/// [problematic]: https://github.com/rust-lang/rust/issues/95489
2805pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
2806 let old_options = f.options;
2807
2808 // The alternate flag is already treated by LowerHex as being special-
2809 // it denotes whether to prefix with 0x. We use it to work out whether
2810 // or not to zero extend, and then unconditionally set it to get the
2811 // prefix.
2812 if f.options.get_alternate() {
2813 f.options.sign_aware_zero_pad(true);
2814
2815 if f.options.get_width().is_none() {
2816 f.options.width(Some((usize::BITS / 4) as u16 + 2));
2817 }
2818 }
2819 f.options.alternate(true);
2820
2821 let ret = LowerHex::fmt(&ptr_addr, f);
2822
2823 f.options = old_options;
2824
2825 ret
2826}
2827
2828#[stable(feature = "rust1", since = "1.0.0")]
2829impl<T: PointeeSized> Pointer for *mut T {
2830 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2831 Pointer::fmt(&(*self as *const T), f)
2832 }
2833}
2834
2835#[stable(feature = "rust1", since = "1.0.0")]
2836impl<T: PointeeSized> Pointer for &T {
2837 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2838 Pointer::fmt(&(*self as *const T), f)
2839 }
2840}
2841
2842#[stable(feature = "rust1", since = "1.0.0")]
2843impl<T: PointeeSized> Pointer for &mut T {
2844 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2845 Pointer::fmt(&(&**self as *const T), f)
2846 }
2847}
2848
2849// Implementation of Display/Debug for various core types
2850
2851#[stable(feature = "rust1", since = "1.0.0")]
2852impl<T: PointeeSized> Debug for *const T {
2853 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2854 Pointer::fmt(self, f)
2855 }
2856}
2857#[stable(feature = "rust1", since = "1.0.0")]
2858impl<T: PointeeSized> Debug for *mut T {
2859 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2860 Pointer::fmt(self, f)
2861 }
2862}
2863
2864macro_rules! peel {
2865 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2866}
2867
2868macro_rules! tuple {
2869 () => ();
2870 ( $($name:ident,)+ ) => (
2871 maybe_tuple_doc! {
2872 $($name)+ @
2873 #[stable(feature = "rust1", since = "1.0.0")]
2874 impl<$($name:Debug),+> Debug for ($($name,)+) {
2875 #[allow(non_snake_case, unused_assignments)]
2876 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2877 let mut builder = f.debug_tuple("");
2878 let ($(ref $name,)+) = *self;
2879 $(
2880 builder.field(&$name);
2881 )+
2882
2883 builder.finish()
2884 }
2885 }
2886 }
2887 peel! { $($name,)+ }
2888 )
2889}
2890
2891macro_rules! maybe_tuple_doc {
2892 ($a:ident @ #[$meta:meta] $item:item) => {
2893 #[doc(fake_variadic)]
2894 #[doc = "This trait is implemented for tuples up to twelve items long."]
2895 #[$meta]
2896 $item
2897 };
2898 ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
2899 #[doc(hidden)]
2900 #[$meta]
2901 $item
2902 };
2903}
2904
2905tuple! { E, D, C, B, A, Z, Y, X, W, V, U, T, }
2906
2907#[stable(feature = "rust1", since = "1.0.0")]
2908impl<T: Debug> Debug for [T] {
2909 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2910 f.debug_list().entries(self.iter()).finish()
2911 }
2912}
2913
2914#[stable(feature = "rust1", since = "1.0.0")]
2915impl Debug for () {
2916 #[inline]
2917 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2918 f.pad("()")
2919 }
2920}
2921#[stable(feature = "rust1", since = "1.0.0")]
2922impl<T: ?Sized> Debug for PhantomData<T> {
2923 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2924 write!(f, "PhantomData<{}>", crate::any::type_name::<T>())
2925 }
2926}
2927
2928#[stable(feature = "rust1", since = "1.0.0")]
2929impl<T: Copy + Debug> Debug for Cell<T> {
2930 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2931 f.debug_struct("Cell").field("value", &self.get()).finish()
2932 }
2933}
2934
2935#[stable(feature = "rust1", since = "1.0.0")]
2936impl<T: ?Sized + Debug> Debug for RefCell<T> {
2937 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2938 let mut d = f.debug_struct("RefCell");
2939 match self.try_borrow() {
2940 Ok(borrow) => d.field("value", &borrow),
2941 Err(_) => d.field("value", &format_args!("<borrowed>")),
2942 };
2943 d.finish()
2944 }
2945}
2946
2947#[stable(feature = "rust1", since = "1.0.0")]
2948impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2949 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2950 Debug::fmt(&**self, f)
2951 }
2952}
2953
2954#[stable(feature = "rust1", since = "1.0.0")]
2955impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
2956 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2957 Debug::fmt(&*(self.deref()), f)
2958 }
2959}
2960
2961#[stable(feature = "core_impl_debug", since = "1.9.0")]
2962impl<T: ?Sized> Debug for UnsafeCell<T> {
2963 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2964 f.debug_struct("UnsafeCell").finish_non_exhaustive()
2965 }
2966}
2967
2968#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2969impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
2970 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2971 f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
2972 }
2973}
2974
2975// If you expected tests to be here, look instead at coretests/tests/fmt/;
2976// it's a lot easier than creating all of the rt::Piece structures here.
2977// There are also tests in alloctests/tests/fmt.rs, for those that need allocations.