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