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