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