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, mem, 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/// Used by the format_args!() macro to create a fmt::Arguments object.
626#[doc(hidden)]
627#[unstable(feature = "fmt_internals", issue = "none")]
628impl<'a> Arguments<'a> {
629 #[inline]
630 pub const fn new_const<const N: usize>(pieces: &'a [&'static str; N]) -> Self {
631 const { assert!(N <= 1) };
632 Arguments { pieces, fmt: None, args: &[] }
633 }
634
635 /// When using the format_args!() macro, this function is used to generate the
636 /// Arguments structure.
637 #[inline]
638 pub const fn new_v1<const P: usize, const A: usize>(
639 pieces: &'a [&'static str; P],
640 args: &'a [rt::Argument<'a>; A],
641 ) -> Arguments<'a> {
642 const { assert!(P >= A && P <= A + 1, "invalid args") }
643 Arguments { pieces, fmt: None, args }
644 }
645
646 /// Specifies nonstandard formatting parameters.
647 ///
648 /// An `rt::UnsafeArg` is required because the following invariants must be held
649 /// in order for this function to be safe:
650 /// 1. The `pieces` slice must be at least as long as `fmt`.
651 /// 2. Every `rt::Placeholder::position` value within `fmt` must be a valid index of `args`.
652 /// 3. Every `rt::Count::Param` within `fmt` must contain a valid index of `args`.
653 #[inline]
654 pub const fn new_v1_formatted(
655 pieces: &'a [&'static str],
656 args: &'a [rt::Argument<'a>],
657 fmt: &'a [rt::Placeholder],
658 _unsafe_arg: rt::UnsafeArg,
659 ) -> Arguments<'a> {
660 Arguments { pieces, fmt: Some(fmt), args }
661 }
662
663 /// Estimates the length of the formatted text.
664 ///
665 /// This is intended to be used for setting initial `String` capacity
666 /// when using `format!`. Note: this is neither the lower nor upper bound.
667 #[inline]
668 pub fn estimated_capacity(&self) -> usize {
669 let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();
670
671 if self.args.is_empty() {
672 pieces_length
673 } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
674 // If the format string starts with an argument,
675 // don't preallocate anything, unless length
676 // of pieces is significant.
677 0
678 } else {
679 // There are some arguments, so any additional push
680 // will reallocate the string. To avoid that,
681 // we're "pre-doubling" the capacity here.
682 pieces_length.checked_mul(2).unwrap_or(0)
683 }
684 }
685}
686
687impl<'a> Arguments<'a> {
688 /// Gets the formatted string, if it has no arguments to be formatted at runtime.
689 ///
690 /// This can be used to avoid allocations in some cases.
691 ///
692 /// # Guarantees
693 ///
694 /// For `format_args!("just a literal")`, this function is guaranteed to
695 /// return `Some("just a literal")`.
696 ///
697 /// For most cases with placeholders, this function will return `None`.
698 ///
699 /// However, the compiler may perform optimizations that can cause this
700 /// function to return `Some(_)` even if the format string contains
701 /// placeholders. For example, `format_args!("Hello, {}!", "world")` may be
702 /// optimized to `format_args!("Hello, world!")`, such that `as_str()`
703 /// returns `Some("Hello, world!")`.
704 ///
705 /// The behavior for anything but the trivial case (without placeholders)
706 /// is not guaranteed, and should not be relied upon for anything other
707 /// than optimization.
708 ///
709 /// # Examples
710 ///
711 /// ```rust
712 /// use std::fmt::Arguments;
713 ///
714 /// fn write_str(_: &str) { /* ... */ }
715 ///
716 /// fn write_fmt(args: &Arguments<'_>) {
717 /// if let Some(s) = args.as_str() {
718 /// write_str(s)
719 /// } else {
720 /// write_str(&args.to_string());
721 /// }
722 /// }
723 /// ```
724 ///
725 /// ```rust
726 /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
727 /// assert_eq!(format_args!("").as_str(), Some(""));
728 /// assert_eq!(format_args!("{:?}", std::env::current_dir()).as_str(), None);
729 /// ```
730 #[stable(feature = "fmt_as_str", since = "1.52.0")]
731 #[rustc_const_stable(feature = "const_arguments_as_str", since = "1.84.0")]
732 #[must_use]
733 #[inline]
734 pub const fn as_str(&self) -> Option<&'static str> {
735 match (self.pieces, self.args) {
736 ([], []) => Some(""),
737 ([s], []) => Some(s),
738 _ => None,
739 }
740 }
741
742 /// Same as [`Arguments::as_str`], but will only return `Some(s)` if it can be determined at compile time.
743 #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")]
744 #[must_use]
745 #[inline]
746 pub fn as_statically_known_str(&self) -> Option<&'static str> {
747 let s = self.as_str();
748 if core::intrinsics::is_val_statically_known(s.is_some()) { s } else { None }
749 }
750}
751
752// Manually implementing these results in better error messages.
753#[stable(feature = "rust1", since = "1.0.0")]
754impl !Send for Arguments<'_> {}
755#[stable(feature = "rust1", since = "1.0.0")]
756impl !Sync for Arguments<'_> {}
757
758#[stable(feature = "rust1", since = "1.0.0")]
759impl Debug for Arguments<'_> {
760 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
761 Display::fmt(self, fmt)
762 }
763}
764
765#[stable(feature = "rust1", since = "1.0.0")]
766impl Display for Arguments<'_> {
767 fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
768 write(fmt.buf, *self)
769 }
770}
771
772/// `?` formatting.
773///
774/// `Debug` should format the output in a programmer-facing, debugging context.
775///
776/// Generally speaking, you should just `derive` a `Debug` implementation.
777///
778/// When used with the alternate format specifier `#?`, the output is pretty-printed.
779///
780/// For more information on formatters, see [the module-level documentation][module].
781///
782/// [module]: ../../std/fmt/index.html
783///
784/// This trait can be used with `#[derive]` if all fields implement `Debug`. When
785/// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
786/// comma-separated list of each field's name and `Debug` value, then `}`. For
787/// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
788/// `Debug` values of the fields, then `)`.
789///
790/// # Stability
791///
792/// Derived `Debug` formats are not stable, and so may change with future Rust
793/// versions. Additionally, `Debug` implementations of types provided by the
794/// standard library (`std`, `core`, `alloc`, etc.) are not stable, and
795/// may also change with future Rust versions.
796///
797/// # Examples
798///
799/// Deriving an implementation:
800///
801/// ```
802/// #[derive(Debug)]
803/// struct Point {
804/// x: i32,
805/// y: i32,
806/// }
807///
808/// let origin = Point { x: 0, y: 0 };
809///
810/// assert_eq!(
811/// format!("The origin is: {origin:?}"),
812/// "The origin is: Point { x: 0, y: 0 }",
813/// );
814/// ```
815///
816/// Manually implementing:
817///
818/// ```
819/// use std::fmt;
820///
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/// f.debug_struct("Point")
829/// .field("x", &self.x)
830/// .field("y", &self.y)
831/// .finish()
832/// }
833/// }
834///
835/// let origin = Point { x: 0, y: 0 };
836///
837/// assert_eq!(
838/// format!("The origin is: {origin:?}"),
839/// "The origin is: Point { x: 0, y: 0 }",
840/// );
841/// ```
842///
843/// There are a number of helper methods on the [`Formatter`] struct to help you with manual
844/// implementations, such as [`debug_struct`].
845///
846/// [`debug_struct`]: Formatter::debug_struct
847///
848/// Types that do not wish to use the standard suite of debug representations
849/// provided by the `Formatter` trait (`debug_struct`, `debug_tuple`,
850/// `debug_list`, `debug_set`, `debug_map`) can do something totally custom by
851/// manually writing an arbitrary representation to the `Formatter`.
852///
853/// ```
854/// # use std::fmt;
855/// # struct Point {
856/// # x: i32,
857/// # y: i32,
858/// # }
859/// #
860/// impl fmt::Debug for Point {
861/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
862/// write!(f, "Point [{} {}]", self.x, self.y)
863/// }
864/// }
865/// ```
866///
867/// `Debug` implementations using either `derive` or the debug builder API
868/// on [`Formatter`] support pretty-printing using the alternate flag: `{:#?}`.
869///
870/// Pretty-printing with `#?`:
871///
872/// ```
873/// #[derive(Debug)]
874/// struct Point {
875/// x: i32,
876/// y: i32,
877/// }
878///
879/// let origin = Point { x: 0, y: 0 };
880///
881/// let expected = "The origin is: Point {
882/// x: 0,
883/// y: 0,
884/// }";
885/// assert_eq!(format!("The origin is: {origin:#?}"), expected);
886/// ```
887
888#[stable(feature = "rust1", since = "1.0.0")]
889#[rustc_on_unimplemented(
890 on(
891 crate_local,
892 label = "`{Self}` cannot be formatted using `{{:?}}`",
893 note = "add `#[derive(Debug)]` to `{Self}` or manually `impl {Debug} for {Self}`"
894 ),
895 message = "`{Self}` doesn't implement `{Debug}`",
896 label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
897)]
898#[doc(alias = "{:?}")]
899#[rustc_diagnostic_item = "Debug"]
900#[rustc_trivial_field_reads]
901pub trait Debug {
902 #[doc = include_str!("fmt_trait_method_doc.md")]
903 ///
904 /// # Examples
905 ///
906 /// ```
907 /// use std::fmt;
908 ///
909 /// struct Position {
910 /// longitude: f32,
911 /// latitude: f32,
912 /// }
913 ///
914 /// impl fmt::Debug for Position {
915 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916 /// f.debug_tuple("")
917 /// .field(&self.longitude)
918 /// .field(&self.latitude)
919 /// .finish()
920 /// }
921 /// }
922 ///
923 /// let position = Position { longitude: 1.987, latitude: 2.983 };
924 /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
925 ///
926 /// assert_eq!(format!("{position:#?}"), "(
927 /// 1.987,
928 /// 2.983,
929 /// )");
930 /// ```
931 #[stable(feature = "rust1", since = "1.0.0")]
932 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
933}
934
935// Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
936pub(crate) mod macros {
937 /// Derive macro generating an impl of the trait `Debug`.
938 #[rustc_builtin_macro]
939 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
940 #[allow_internal_unstable(core_intrinsics, fmt_helpers_for_derive)]
941 pub macro Debug($item:item) {
942 /* compiler built-in */
943 }
944}
945#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
946#[doc(inline)]
947pub use macros::Debug;
948
949/// Format trait for an empty format, `{}`.
950///
951/// Implementing this trait for a type will automatically implement the
952/// [`ToString`][tostring] trait for the type, allowing the usage
953/// of the [`.to_string()`][tostring_function] method. Prefer implementing
954/// the `Display` trait for a type, rather than [`ToString`][tostring].
955///
956/// `Display` is similar to [`Debug`], but `Display` is for user-facing
957/// output, and so cannot be derived.
958///
959/// For more information on formatters, see [the module-level documentation][module].
960///
961/// [module]: ../../std/fmt/index.html
962/// [tostring]: ../../std/string/trait.ToString.html
963/// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
964///
965/// # Internationalization
966///
967/// Because a type can only have one `Display` implementation, it is often preferable
968/// to only implement `Display` when there is a single most "obvious" way that
969/// values can be formatted as text. This could mean formatting according to the
970/// "invariant" culture and "undefined" locale, or it could mean that the type
971/// display is designed for a specific culture/locale, such as developer logs.
972///
973/// If not all values have a justifiably canonical textual format or if you want
974/// to support alternative formats not covered by the standard set of possible
975/// [formatting traits], the most flexible approach is display adapters: methods
976/// like [`str::escape_default`] or [`Path::display`] which create a wrapper
977/// implementing `Display` to output the specific display format.
978///
979/// [formatting traits]: ../../std/fmt/index.html#formatting-traits
980/// [`Path::display`]: ../../std/path/struct.Path.html#method.display
981///
982/// # Examples
983///
984/// Implementing `Display` on a type:
985///
986/// ```
987/// use std::fmt;
988///
989/// struct Point {
990/// x: i32,
991/// y: i32,
992/// }
993///
994/// impl fmt::Display for Point {
995/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
996/// write!(f, "({}, {})", self.x, self.y)
997/// }
998/// }
999///
1000/// let origin = Point { x: 0, y: 0 };
1001///
1002/// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
1003/// ```
1004#[rustc_on_unimplemented(
1005 on(
1006 any(_Self = "std::path::Path", _Self = "std::path::PathBuf"),
1007 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
1008 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
1009 as they may contain non-Unicode data"
1010 ),
1011 message = "`{Self}` doesn't implement `{Display}`",
1012 label = "`{Self}` cannot be formatted with the default formatter",
1013 note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
1014)]
1015#[doc(alias = "{}")]
1016#[rustc_diagnostic_item = "Display"]
1017#[stable(feature = "rust1", since = "1.0.0")]
1018pub trait Display {
1019 #[doc = include_str!("fmt_trait_method_doc.md")]
1020 ///
1021 /// # Examples
1022 ///
1023 /// ```
1024 /// use std::fmt;
1025 ///
1026 /// struct Position {
1027 /// longitude: f32,
1028 /// latitude: f32,
1029 /// }
1030 ///
1031 /// impl fmt::Display for Position {
1032 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1033 /// write!(f, "({}, {})", self.longitude, self.latitude)
1034 /// }
1035 /// }
1036 ///
1037 /// assert_eq!(
1038 /// "(1.987, 2.983)",
1039 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }),
1040 /// );
1041 /// ```
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1044}
1045
1046/// `o` formatting.
1047///
1048/// The `Octal` trait should format its output as a number in base-8.
1049///
1050/// For primitive signed integers (`i8` to `i128`, and `isize`),
1051/// negative values are formatted as the two’s complement representation.
1052///
1053/// The alternate flag, `#`, adds a `0o` in front of the output.
1054///
1055/// For more information on formatters, see [the module-level documentation][module].
1056///
1057/// [module]: ../../std/fmt/index.html
1058///
1059/// # Examples
1060///
1061/// Basic usage with `i32`:
1062///
1063/// ```
1064/// let x = 42; // 42 is '52' in octal
1065///
1066/// assert_eq!(format!("{x:o}"), "52");
1067/// assert_eq!(format!("{x:#o}"), "0o52");
1068///
1069/// assert_eq!(format!("{:o}", -16), "37777777760");
1070/// ```
1071///
1072/// Implementing `Octal` on a type:
1073///
1074/// ```
1075/// use std::fmt;
1076///
1077/// struct Length(i32);
1078///
1079/// impl fmt::Octal for Length {
1080/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1081/// let val = self.0;
1082///
1083/// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
1084/// }
1085/// }
1086///
1087/// let l = Length(9);
1088///
1089/// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
1090///
1091/// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
1092/// ```
1093#[stable(feature = "rust1", since = "1.0.0")]
1094pub trait Octal {
1095 #[doc = include_str!("fmt_trait_method_doc.md")]
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1098}
1099
1100/// `b` formatting.
1101///
1102/// The `Binary` trait should format its output as a number in binary.
1103///
1104/// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
1105/// negative values are formatted as the two’s complement representation.
1106///
1107/// The alternate flag, `#`, adds a `0b` in front of the output.
1108///
1109/// For more information on formatters, see [the module-level documentation][module].
1110///
1111/// [module]: ../../std/fmt/index.html
1112///
1113/// # Examples
1114///
1115/// Basic usage with [`i32`]:
1116///
1117/// ```
1118/// let x = 42; // 42 is '101010' in binary
1119///
1120/// assert_eq!(format!("{x:b}"), "101010");
1121/// assert_eq!(format!("{x:#b}"), "0b101010");
1122///
1123/// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
1124/// ```
1125///
1126/// Implementing `Binary` on a type:
1127///
1128/// ```
1129/// use std::fmt;
1130///
1131/// struct Length(i32);
1132///
1133/// impl fmt::Binary for Length {
1134/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1135/// let val = self.0;
1136///
1137/// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
1138/// }
1139/// }
1140///
1141/// let l = Length(107);
1142///
1143/// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
1144///
1145/// assert_eq!(
1146/// // Note that the `0b` prefix added by `#` is included in the total width, so we
1147/// // need to add two to correctly display all 32 bits.
1148/// format!("l as binary is: {l:#034b}"),
1149/// "l as binary is: 0b00000000000000000000000001101011"
1150/// );
1151/// ```
1152#[stable(feature = "rust1", since = "1.0.0")]
1153pub trait Binary {
1154 #[doc = include_str!("fmt_trait_method_doc.md")]
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1157}
1158
1159/// `x` formatting.
1160///
1161/// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
1162/// in lower case.
1163///
1164/// For primitive signed integers (`i8` to `i128`, and `isize`),
1165/// negative values are formatted as the two’s complement representation.
1166///
1167/// The alternate flag, `#`, adds a `0x` in front of the output.
1168///
1169/// For more information on formatters, see [the module-level documentation][module].
1170///
1171/// [module]: ../../std/fmt/index.html
1172///
1173/// # Examples
1174///
1175/// Basic usage with `i32`:
1176///
1177/// ```
1178/// let y = 42; // 42 is '2a' in hex
1179///
1180/// assert_eq!(format!("{y:x}"), "2a");
1181/// assert_eq!(format!("{y:#x}"), "0x2a");
1182///
1183/// assert_eq!(format!("{:x}", -16), "fffffff0");
1184/// ```
1185///
1186/// Implementing `LowerHex` on a type:
1187///
1188/// ```
1189/// use std::fmt;
1190///
1191/// struct Length(i32);
1192///
1193/// impl fmt::LowerHex for Length {
1194/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1195/// let val = self.0;
1196///
1197/// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
1198/// }
1199/// }
1200///
1201/// let l = Length(9);
1202///
1203/// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
1204///
1205/// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
1206/// ```
1207#[stable(feature = "rust1", since = "1.0.0")]
1208pub trait LowerHex {
1209 #[doc = include_str!("fmt_trait_method_doc.md")]
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1212}
1213
1214/// `X` formatting.
1215///
1216/// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
1217/// in upper case.
1218///
1219/// For primitive signed integers (`i8` to `i128`, and `isize`),
1220/// negative values are formatted as the two’s complement representation.
1221///
1222/// The alternate flag, `#`, adds a `0x` in front of the output.
1223///
1224/// For more information on formatters, see [the module-level documentation][module].
1225///
1226/// [module]: ../../std/fmt/index.html
1227///
1228/// # Examples
1229///
1230/// Basic usage with `i32`:
1231///
1232/// ```
1233/// let y = 42; // 42 is '2A' in hex
1234///
1235/// assert_eq!(format!("{y:X}"), "2A");
1236/// assert_eq!(format!("{y:#X}"), "0x2A");
1237///
1238/// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
1239/// ```
1240///
1241/// Implementing `UpperHex` on a type:
1242///
1243/// ```
1244/// use std::fmt;
1245///
1246/// struct Length(i32);
1247///
1248/// impl fmt::UpperHex for Length {
1249/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1250/// let val = self.0;
1251///
1252/// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
1253/// }
1254/// }
1255///
1256/// let l = Length(i32::MAX);
1257///
1258/// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
1259///
1260/// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
1261/// ```
1262#[stable(feature = "rust1", since = "1.0.0")]
1263pub trait UpperHex {
1264 #[doc = include_str!("fmt_trait_method_doc.md")]
1265 #[stable(feature = "rust1", since = "1.0.0")]
1266 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1267}
1268
1269/// `p` formatting.
1270///
1271/// The `Pointer` trait should format its output as a memory location. This is commonly presented
1272/// as hexadecimal. For more information on formatters, see [the module-level documentation][module].
1273///
1274/// Printing of pointers is not a reliable way to discover how Rust programs are implemented.
1275/// The act of reading an address changes the program itself, and may change how the data is represented
1276/// in memory, and may affect which optimizations are applied to the code.
1277///
1278/// The printed pointer values are not guaranteed to be stable nor unique identifiers of objects.
1279/// Rust allows moving values to different memory locations, and may reuse the same memory locations
1280/// for different purposes.
1281///
1282/// There is no guarantee that the printed value can be converted back to a pointer.
1283///
1284/// [module]: ../../std/fmt/index.html
1285///
1286/// # Examples
1287///
1288/// Basic usage with `&i32`:
1289///
1290/// ```
1291/// let x = &42;
1292///
1293/// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
1294/// ```
1295///
1296/// Implementing `Pointer` on a type:
1297///
1298/// ```
1299/// use std::fmt;
1300///
1301/// struct Length(i32);
1302///
1303/// impl fmt::Pointer for Length {
1304/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1305/// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
1306///
1307/// let ptr = self as *const Self;
1308/// fmt::Pointer::fmt(&ptr, f)
1309/// }
1310/// }
1311///
1312/// let l = Length(42);
1313///
1314/// println!("l is in memory here: {l:p}");
1315///
1316/// let l_ptr = format!("{l:018p}");
1317/// assert_eq!(l_ptr.len(), 18);
1318/// assert_eq!(&l_ptr[..2], "0x");
1319/// ```
1320#[stable(feature = "rust1", since = "1.0.0")]
1321#[rustc_diagnostic_item = "Pointer"]
1322pub trait Pointer {
1323 #[doc = include_str!("fmt_trait_method_doc.md")]
1324 #[stable(feature = "rust1", since = "1.0.0")]
1325 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1326}
1327
1328/// `e` formatting.
1329///
1330/// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1331///
1332/// For more information on formatters, see [the module-level documentation][module].
1333///
1334/// [module]: ../../std/fmt/index.html
1335///
1336/// # Examples
1337///
1338/// Basic usage with `f64`:
1339///
1340/// ```
1341/// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1342///
1343/// assert_eq!(format!("{x:e}"), "4.2e1");
1344/// ```
1345///
1346/// Implementing `LowerExp` on a type:
1347///
1348/// ```
1349/// use std::fmt;
1350///
1351/// struct Length(i32);
1352///
1353/// impl fmt::LowerExp for Length {
1354/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1355/// let val = f64::from(self.0);
1356/// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1357/// }
1358/// }
1359///
1360/// let l = Length(100);
1361///
1362/// assert_eq!(
1363/// format!("l in scientific notation is: {l:e}"),
1364/// "l in scientific notation is: 1e2"
1365/// );
1366///
1367/// assert_eq!(
1368/// format!("l in scientific notation is: {l:05e}"),
1369/// "l in scientific notation is: 001e2"
1370/// );
1371/// ```
1372#[stable(feature = "rust1", since = "1.0.0")]
1373pub trait LowerExp {
1374 #[doc = include_str!("fmt_trait_method_doc.md")]
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1377}
1378
1379/// `E` formatting.
1380///
1381/// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1382///
1383/// For more information on formatters, see [the module-level documentation][module].
1384///
1385/// [module]: ../../std/fmt/index.html
1386///
1387/// # Examples
1388///
1389/// Basic usage with `f64`:
1390///
1391/// ```
1392/// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1393///
1394/// assert_eq!(format!("{x:E}"), "4.2E1");
1395/// ```
1396///
1397/// Implementing `UpperExp` on a type:
1398///
1399/// ```
1400/// use std::fmt;
1401///
1402/// struct Length(i32);
1403///
1404/// impl fmt::UpperExp for Length {
1405/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1406/// let val = f64::from(self.0);
1407/// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1408/// }
1409/// }
1410///
1411/// let l = Length(100);
1412///
1413/// assert_eq!(
1414/// format!("l in scientific notation is: {l:E}"),
1415/// "l in scientific notation is: 1E2"
1416/// );
1417///
1418/// assert_eq!(
1419/// format!("l in scientific notation is: {l:05E}"),
1420/// "l in scientific notation is: 001E2"
1421/// );
1422/// ```
1423#[stable(feature = "rust1", since = "1.0.0")]
1424pub trait UpperExp {
1425 #[doc = include_str!("fmt_trait_method_doc.md")]
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1428}
1429
1430/// Takes an output stream and an `Arguments` struct that can be precompiled with
1431/// the `format_args!` macro.
1432///
1433/// The arguments will be formatted according to the specified format string
1434/// into the output stream provided.
1435///
1436/// # Examples
1437///
1438/// Basic usage:
1439///
1440/// ```
1441/// use std::fmt;
1442///
1443/// let mut output = String::new();
1444/// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1445/// .expect("Error occurred while trying to write in String");
1446/// assert_eq!(output, "Hello world!");
1447/// ```
1448///
1449/// Please note that using [`write!`] might be preferable. Example:
1450///
1451/// ```
1452/// use std::fmt::Write;
1453///
1454/// let mut output = String::new();
1455/// write!(&mut output, "Hello {}!", "world")
1456/// .expect("Error occurred while trying to write in String");
1457/// assert_eq!(output, "Hello world!");
1458/// ```
1459///
1460/// [`write!`]: crate::write!
1461#[stable(feature = "rust1", since = "1.0.0")]
1462pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result {
1463 let mut formatter = Formatter::new(output, FormattingOptions::new());
1464 let mut idx = 0;
1465
1466 match args.fmt {
1467 None => {
1468 // We can use default formatting parameters for all arguments.
1469 for (i, arg) in args.args.iter().enumerate() {
1470 // SAFETY: args.args and args.pieces come from the same Arguments,
1471 // which guarantees the indexes are always within bounds.
1472 let piece = unsafe { args.pieces.get_unchecked(i) };
1473 if !piece.is_empty() {
1474 formatter.buf.write_str(*piece)?;
1475 }
1476
1477 // SAFETY: There are no formatting parameters and hence no
1478 // count arguments.
1479 unsafe {
1480 arg.fmt(&mut formatter)?;
1481 }
1482 idx += 1;
1483 }
1484 }
1485 Some(fmt) => {
1486 // Every spec has a corresponding argument that is preceded by
1487 // a string piece.
1488 for (i, arg) in fmt.iter().enumerate() {
1489 // SAFETY: fmt and args.pieces come from the same Arguments,
1490 // which guarantees the indexes are always within bounds.
1491 let piece = unsafe { args.pieces.get_unchecked(i) };
1492 if !piece.is_empty() {
1493 formatter.buf.write_str(*piece)?;
1494 }
1495 // SAFETY: arg and args.args come from the same Arguments,
1496 // which guarantees the indexes are always within bounds.
1497 unsafe { run(&mut formatter, arg, args.args) }?;
1498 idx += 1;
1499 }
1500 }
1501 }
1502
1503 // There can be only one trailing string piece left.
1504 if let Some(piece) = args.pieces.get(idx) {
1505 formatter.buf.write_str(*piece)?;
1506 }
1507
1508 Ok(())
1509}
1510
1511unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::Placeholder, args: &[rt::Argument<'_>]) -> Result {
1512 let (width, precision) =
1513 // SAFETY: arg and args come from the same Arguments,
1514 // which guarantees the indexes are always within bounds.
1515 unsafe { (getcount(args, &arg.width), getcount(args, &arg.precision)) };
1516
1517 #[cfg(bootstrap)]
1518 let options =
1519 *FormattingOptions { flags: flags::ALWAYS_SET | arg.flags << 21, width: 0, precision: 0 }
1520 .align(match arg.align {
1521 rt::Alignment::Left => Some(Alignment::Left),
1522 rt::Alignment::Right => Some(Alignment::Right),
1523 rt::Alignment::Center => Some(Alignment::Center),
1524 rt::Alignment::Unknown => None,
1525 })
1526 .fill(arg.fill)
1527 .width(width)
1528 .precision(precision);
1529 #[cfg(not(bootstrap))]
1530 let options = FormattingOptions { flags: arg.flags, width, precision };
1531
1532 // Extract the correct argument
1533 debug_assert!(arg.position < args.len());
1534 // SAFETY: arg and args come from the same Arguments,
1535 // which guarantees its index is always within bounds.
1536 let value = unsafe { args.get_unchecked(arg.position) };
1537
1538 // Set all the formatting options.
1539 fmt.options = options;
1540
1541 // Then actually do some printing
1542 // SAFETY: this is a placeholder argument.
1543 unsafe { value.fmt(fmt) }
1544}
1545
1546#[cfg(bootstrap)]
1547unsafe fn getcount(args: &[rt::Argument<'_>], cnt: &rt::Count) -> Option<u16> {
1548 match *cnt {
1549 rt::Count::Is(n) => Some(n as u16),
1550 rt::Count::Implied => None,
1551 rt::Count::Param(i) => {
1552 debug_assert!(i < args.len());
1553 // SAFETY: cnt and args come from the same Arguments,
1554 // which guarantees this index is always within bounds.
1555 unsafe { args.get_unchecked(i).as_u16() }
1556 }
1557 }
1558}
1559
1560#[cfg(not(bootstrap))]
1561unsafe fn getcount(args: &[rt::Argument<'_>], cnt: &rt::Count) -> u16 {
1562 match *cnt {
1563 rt::Count::Is(n) => n,
1564 rt::Count::Implied => 0,
1565 rt::Count::Param(i) => {
1566 debug_assert!(i < args.len());
1567 // SAFETY: cnt and args come from the same Arguments,
1568 // which guarantees this index is always within bounds.
1569 unsafe { args.get_unchecked(i).as_u16().unwrap_unchecked() }
1570 }
1571 }
1572}
1573
1574/// Padding after the end of something. Returned by `Formatter::padding`.
1575#[must_use = "don't forget to write the post padding"]
1576pub(crate) struct PostPadding {
1577 fill: char,
1578 padding: u16,
1579}
1580
1581impl PostPadding {
1582 fn new(fill: char, padding: u16) -> PostPadding {
1583 PostPadding { fill, padding }
1584 }
1585
1586 /// Writes this post padding.
1587 pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1588 for _ in 0..self.padding {
1589 f.buf.write_char(self.fill)?;
1590 }
1591 Ok(())
1592 }
1593}
1594
1595impl<'a> Formatter<'a> {
1596 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1597 where
1598 'b: 'c,
1599 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1600 {
1601 Formatter {
1602 // We want to change this
1603 buf: wrap(self.buf),
1604
1605 // And preserve these
1606 options: self.options,
1607 }
1608 }
1609
1610 // Helper methods used for padding and processing formatting arguments that
1611 // all formatting traits can use.
1612
1613 /// Performs the correct padding for an integer which has already been
1614 /// emitted into a str. The str should *not* contain the sign for the
1615 /// integer, that will be added by this method.
1616 ///
1617 /// # Arguments
1618 ///
1619 /// * is_nonnegative - whether the original integer was either positive or zero.
1620 /// * prefix - if the '#' character (Alternate) is provided, this
1621 /// is the prefix to put in front of the number.
1622 /// * buf - the byte array that the number has been formatted into
1623 ///
1624 /// This function will correctly account for the flags provided as well as
1625 /// the minimum width. It will not take precision into account.
1626 ///
1627 /// # Examples
1628 ///
1629 /// ```
1630 /// use std::fmt;
1631 ///
1632 /// struct Foo { nb: i32 }
1633 ///
1634 /// impl Foo {
1635 /// fn new(nb: i32) -> Foo {
1636 /// Foo {
1637 /// nb,
1638 /// }
1639 /// }
1640 /// }
1641 ///
1642 /// impl fmt::Display for Foo {
1643 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1644 /// // We need to remove "-" from the number output.
1645 /// let tmp = self.nb.abs().to_string();
1646 ///
1647 /// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1648 /// }
1649 /// }
1650 ///
1651 /// assert_eq!(format!("{}", Foo::new(2)), "2");
1652 /// assert_eq!(format!("{}", Foo::new(-1)), "-1");
1653 /// assert_eq!(format!("{}", Foo::new(0)), "0");
1654 /// assert_eq!(format!("{:#}", Foo::new(-1)), "-Foo 1");
1655 /// assert_eq!(format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1656 /// ```
1657 #[stable(feature = "rust1", since = "1.0.0")]
1658 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1659 let mut width = buf.len();
1660
1661 let mut sign = None;
1662 if !is_nonnegative {
1663 sign = Some('-');
1664 width += 1;
1665 } else if self.sign_plus() {
1666 sign = Some('+');
1667 width += 1;
1668 }
1669
1670 let prefix = if self.alternate() {
1671 width += prefix.chars().count();
1672 Some(prefix)
1673 } else {
1674 None
1675 };
1676
1677 // Writes the sign if it exists, and then the prefix if it was requested
1678 #[inline(never)]
1679 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1680 if let Some(c) = sign {
1681 f.buf.write_char(c)?;
1682 }
1683 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1684 }
1685
1686 // The `width` field is more of a `min-width` parameter at this point.
1687 let min = self.options.width;
1688 if width >= usize::from(min) {
1689 // We're over the minimum width, so then we can just write the bytes.
1690 write_prefix(self, sign, prefix)?;
1691 self.buf.write_str(buf)
1692 } else if self.sign_aware_zero_pad() {
1693 // The sign and prefix goes before the padding if the fill character
1694 // is zero
1695 let old_options = self.options;
1696 self.options.fill('0').align(Some(Alignment::Right));
1697 write_prefix(self, sign, prefix)?;
1698 let post_padding = self.padding(min - width as u16, Alignment::Right)?;
1699 self.buf.write_str(buf)?;
1700 post_padding.write(self)?;
1701 self.options = old_options;
1702 Ok(())
1703 } else {
1704 // Otherwise, the sign and prefix goes after the padding
1705 let post_padding = self.padding(min - width as u16, Alignment::Right)?;
1706 write_prefix(self, sign, prefix)?;
1707 self.buf.write_str(buf)?;
1708 post_padding.write(self)
1709 }
1710 }
1711
1712 /// Takes a string slice and emits it to the internal buffer after applying
1713 /// the relevant formatting flags specified.
1714 ///
1715 /// The flags recognized for generic strings are:
1716 ///
1717 /// * width - the minimum width of what to emit
1718 /// * fill/align - what to emit and where to emit it if the string
1719 /// provided needs to be padded
1720 /// * precision - the maximum length to emit, the string is truncated if it
1721 /// is longer than this length
1722 ///
1723 /// Notably this function ignores the `flag` parameters.
1724 ///
1725 /// # Examples
1726 ///
1727 /// ```
1728 /// use std::fmt;
1729 ///
1730 /// struct Foo;
1731 ///
1732 /// impl fmt::Display for Foo {
1733 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1734 /// formatter.pad("Foo")
1735 /// }
1736 /// }
1737 ///
1738 /// assert_eq!(format!("{Foo:<4}"), "Foo ");
1739 /// assert_eq!(format!("{Foo:0>4}"), "0Foo");
1740 /// ```
1741 #[stable(feature = "rust1", since = "1.0.0")]
1742 pub fn pad(&mut self, s: &str) -> Result {
1743 // Make sure there's a fast path up front.
1744 if self.options.flags & (flags::WIDTH_FLAG | flags::PRECISION_FLAG) == 0 {
1745 return self.buf.write_str(s);
1746 }
1747
1748 // The `precision` field can be interpreted as a maximum width for the
1749 // string being formatted.
1750 let (s, char_count) = if let Some(max_char_count) = self.options.get_precision() {
1751 let mut iter = s.char_indices();
1752 let remaining = match iter.advance_by(usize::from(max_char_count)) {
1753 Ok(()) => 0,
1754 Err(remaining) => remaining.get(),
1755 };
1756 // SAFETY: The offset of `.char_indices()` is guaranteed to be
1757 // in-bounds and between character boundaries.
1758 let truncated = unsafe { s.get_unchecked(..iter.offset()) };
1759 (truncated, usize::from(max_char_count) - remaining)
1760 } else {
1761 // Use the optimized char counting algorithm for the full string.
1762 (s, s.chars().count())
1763 };
1764
1765 // The `width` field is more of a minimum width parameter at this point.
1766 if char_count < usize::from(self.options.width) {
1767 // If we're under the minimum width, then fill up the minimum width
1768 // with the specified string + some alignment.
1769 let post_padding =
1770 self.padding(self.options.width - char_count as u16, Alignment::Left)?;
1771 self.buf.write_str(s)?;
1772 post_padding.write(self)
1773 } else {
1774 // If we're over the minimum width or there is no minimum width, we
1775 // can just emit the string.
1776 self.buf.write_str(s)
1777 }
1778 }
1779
1780 /// Writes the pre-padding and returns the unwritten post-padding.
1781 ///
1782 /// Callers are responsible for ensuring post-padding is written after the
1783 /// thing that is being padded.
1784 pub(crate) fn padding(
1785 &mut self,
1786 padding: u16,
1787 default: Alignment,
1788 ) -> result::Result<PostPadding, Error> {
1789 let align = self.options.get_align().unwrap_or(default);
1790 let fill = self.options.get_fill();
1791
1792 let padding_left = match align {
1793 Alignment::Left => 0,
1794 Alignment::Right => padding,
1795 Alignment::Center => padding / 2,
1796 };
1797
1798 for _ in 0..padding_left {
1799 self.buf.write_char(fill)?;
1800 }
1801
1802 Ok(PostPadding::new(fill, padding - padding_left))
1803 }
1804
1805 /// Takes the formatted parts and applies the padding.
1806 ///
1807 /// Assumes that the caller already has rendered the parts with required precision,
1808 /// so that `self.precision` can be ignored.
1809 ///
1810 /// # Safety
1811 ///
1812 /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
1813 unsafe fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1814 if self.options.width == 0 {
1815 // this is the common case and we take a shortcut
1816 // SAFETY: Per the precondition.
1817 unsafe { self.write_formatted_parts(formatted) }
1818 } else {
1819 // for the sign-aware zero padding, we render the sign first and
1820 // behave as if we had no sign from the beginning.
1821 let mut formatted = formatted.clone();
1822 let mut width = self.options.width;
1823 let old_options = self.options;
1824 if self.sign_aware_zero_pad() {
1825 // a sign always goes first
1826 let sign = formatted.sign;
1827 self.buf.write_str(sign)?;
1828
1829 // remove the sign from the formatted parts
1830 formatted.sign = "";
1831 width = width.saturating_sub(sign.len() as u16);
1832 self.options.fill('0').align(Some(Alignment::Right));
1833 }
1834
1835 // remaining parts go through the ordinary padding process.
1836 let len = formatted.len();
1837 let ret = if usize::from(width) <= len {
1838 // no padding
1839 // SAFETY: Per the precondition.
1840 unsafe { self.write_formatted_parts(&formatted) }
1841 } else {
1842 let post_padding = self.padding(width - len as u16, Alignment::Right)?;
1843 // SAFETY: Per the precondition.
1844 unsafe {
1845 self.write_formatted_parts(&formatted)?;
1846 }
1847 post_padding.write(self)
1848 };
1849 self.options = old_options;
1850 ret
1851 }
1852 }
1853
1854 /// # Safety
1855 ///
1856 /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
1857 unsafe fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
1858 unsafe fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
1859 // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
1860 // It's safe to use for `numfmt::Part::Num` since every char `c` is between
1861 // `b'0'` and `b'9'`, which means `s` is valid UTF-8. It's safe to use for
1862 // `numfmt::Part::Copy` due to this function's precondition.
1863 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1864 }
1865
1866 if !formatted.sign.is_empty() {
1867 self.buf.write_str(formatted.sign)?;
1868 }
1869 for part in formatted.parts {
1870 match *part {
1871 numfmt::Part::Zero(mut nzeroes) => {
1872 const ZEROES: &str = // 64 zeroes
1873 "0000000000000000000000000000000000000000000000000000000000000000";
1874 while nzeroes > ZEROES.len() {
1875 self.buf.write_str(ZEROES)?;
1876 nzeroes -= ZEROES.len();
1877 }
1878 if nzeroes > 0 {
1879 self.buf.write_str(&ZEROES[..nzeroes])?;
1880 }
1881 }
1882 numfmt::Part::Num(mut v) => {
1883 let mut s = [0; 5];
1884 let len = part.len();
1885 for c in s[..len].iter_mut().rev() {
1886 *c = b'0' + (v % 10) as u8;
1887 v /= 10;
1888 }
1889 // SAFETY: Per the precondition.
1890 unsafe {
1891 write_bytes(self.buf, &s[..len])?;
1892 }
1893 }
1894 // SAFETY: Per the precondition.
1895 numfmt::Part::Copy(buf) => unsafe {
1896 write_bytes(self.buf, buf)?;
1897 },
1898 }
1899 }
1900 Ok(())
1901 }
1902
1903 /// Writes some data to the underlying buffer contained within this
1904 /// formatter.
1905 ///
1906 /// # Examples
1907 ///
1908 /// ```
1909 /// use std::fmt;
1910 ///
1911 /// struct Foo;
1912 ///
1913 /// impl fmt::Display for Foo {
1914 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1915 /// formatter.write_str("Foo")
1916 /// // This is equivalent to:
1917 /// // write!(formatter, "Foo")
1918 /// }
1919 /// }
1920 ///
1921 /// assert_eq!(format!("{Foo}"), "Foo");
1922 /// assert_eq!(format!("{Foo:0>8}"), "Foo");
1923 /// ```
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 pub fn write_str(&mut self, data: &str) -> Result {
1926 self.buf.write_str(data)
1927 }
1928
1929 /// Glue for usage of the [`write!`] macro with implementors of this trait.
1930 ///
1931 /// This method should generally not be invoked manually, but rather through
1932 /// the [`write!`] macro itself.
1933 ///
1934 /// Writes some formatted information into this instance.
1935 ///
1936 /// # Examples
1937 ///
1938 /// ```
1939 /// use std::fmt;
1940 ///
1941 /// struct Foo(i32);
1942 ///
1943 /// impl fmt::Display for Foo {
1944 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1945 /// formatter.write_fmt(format_args!("Foo {}", self.0))
1946 /// }
1947 /// }
1948 ///
1949 /// assert_eq!(format!("{}", Foo(-1)), "Foo -1");
1950 /// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
1951 /// ```
1952 #[stable(feature = "rust1", since = "1.0.0")]
1953 #[inline]
1954 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1955 if let Some(s) = fmt.as_statically_known_str() {
1956 self.buf.write_str(s)
1957 } else {
1958 write(self.buf, fmt)
1959 }
1960 }
1961
1962 /// Returns flags for formatting.
1963 #[must_use]
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 #[deprecated(
1966 since = "1.24.0",
1967 note = "use the `sign_plus`, `sign_minus`, `alternate`, \
1968 or `sign_aware_zero_pad` methods instead"
1969 )]
1970 pub fn flags(&self) -> u32 {
1971 // Extract the debug upper/lower hex, zero pad, alternate, and plus/minus flags
1972 // to stay compatible with older versions of Rust.
1973 self.options.flags >> 21 & 0x3F
1974 }
1975
1976 /// Returns the character used as 'fill' whenever there is alignment.
1977 ///
1978 /// # Examples
1979 ///
1980 /// ```
1981 /// use std::fmt;
1982 ///
1983 /// struct Foo;
1984 ///
1985 /// impl fmt::Display for Foo {
1986 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1987 /// let c = formatter.fill();
1988 /// if let Some(width) = formatter.width() {
1989 /// for _ in 0..width {
1990 /// write!(formatter, "{c}")?;
1991 /// }
1992 /// Ok(())
1993 /// } else {
1994 /// write!(formatter, "{c}")
1995 /// }
1996 /// }
1997 /// }
1998 ///
1999 /// // We set alignment to the right with ">".
2000 /// assert_eq!(format!("{Foo:G>3}"), "GGG");
2001 /// assert_eq!(format!("{Foo:t>6}"), "tttttt");
2002 /// ```
2003 #[must_use]
2004 #[stable(feature = "fmt_flags", since = "1.5.0")]
2005 pub fn fill(&self) -> char {
2006 self.options.get_fill()
2007 }
2008
2009 /// Returns a flag indicating what form of alignment was requested.
2010 ///
2011 /// # Examples
2012 ///
2013 /// ```
2014 /// use std::fmt::{self, Alignment};
2015 ///
2016 /// struct Foo;
2017 ///
2018 /// impl fmt::Display for Foo {
2019 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2020 /// let s = if let Some(s) = formatter.align() {
2021 /// match s {
2022 /// Alignment::Left => "left",
2023 /// Alignment::Right => "right",
2024 /// Alignment::Center => "center",
2025 /// }
2026 /// } else {
2027 /// "into the void"
2028 /// };
2029 /// write!(formatter, "{s}")
2030 /// }
2031 /// }
2032 ///
2033 /// assert_eq!(format!("{Foo:<}"), "left");
2034 /// assert_eq!(format!("{Foo:>}"), "right");
2035 /// assert_eq!(format!("{Foo:^}"), "center");
2036 /// assert_eq!(format!("{Foo}"), "into the void");
2037 /// ```
2038 #[must_use]
2039 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
2040 pub fn align(&self) -> Option<Alignment> {
2041 self.options.get_align()
2042 }
2043
2044 /// Returns the optionally specified integer width that the output should be.
2045 ///
2046 /// # Examples
2047 ///
2048 /// ```
2049 /// use std::fmt;
2050 ///
2051 /// struct Foo(i32);
2052 ///
2053 /// impl fmt::Display for Foo {
2054 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2055 /// if let Some(width) = formatter.width() {
2056 /// // If we received a width, we use it
2057 /// write!(formatter, "{:width$}", format!("Foo({})", self.0), width = width)
2058 /// } else {
2059 /// // Otherwise we do nothing special
2060 /// write!(formatter, "Foo({})", self.0)
2061 /// }
2062 /// }
2063 /// }
2064 ///
2065 /// assert_eq!(format!("{:10}", Foo(23)), "Foo(23) ");
2066 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2067 /// ```
2068 #[must_use]
2069 #[stable(feature = "fmt_flags", since = "1.5.0")]
2070 pub fn width(&self) -> Option<usize> {
2071 if self.options.flags & flags::WIDTH_FLAG == 0 {
2072 None
2073 } else {
2074 Some(self.options.width as usize)
2075 }
2076 }
2077
2078 /// Returns the optionally specified precision for numeric types.
2079 /// Alternatively, the maximum width for string types.
2080 ///
2081 /// # Examples
2082 ///
2083 /// ```
2084 /// use std::fmt;
2085 ///
2086 /// struct Foo(f32);
2087 ///
2088 /// impl fmt::Display for Foo {
2089 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2090 /// if let Some(precision) = formatter.precision() {
2091 /// // If we received a precision, we use it.
2092 /// write!(formatter, "Foo({1:.*})", precision, self.0)
2093 /// } else {
2094 /// // Otherwise we default to 2.
2095 /// write!(formatter, "Foo({:.2})", self.0)
2096 /// }
2097 /// }
2098 /// }
2099 ///
2100 /// assert_eq!(format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
2101 /// assert_eq!(format!("{}", Foo(23.2)), "Foo(23.20)");
2102 /// ```
2103 #[must_use]
2104 #[stable(feature = "fmt_flags", since = "1.5.0")]
2105 pub fn precision(&self) -> Option<usize> {
2106 if self.options.flags & flags::PRECISION_FLAG == 0 {
2107 None
2108 } else {
2109 Some(self.options.precision as usize)
2110 }
2111 }
2112
2113 /// Determines if the `+` flag was specified.
2114 ///
2115 /// # Examples
2116 ///
2117 /// ```
2118 /// use std::fmt;
2119 ///
2120 /// struct Foo(i32);
2121 ///
2122 /// impl fmt::Display for Foo {
2123 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2124 /// if formatter.sign_plus() {
2125 /// write!(formatter,
2126 /// "Foo({}{})",
2127 /// if self.0 < 0 { '-' } else { '+' },
2128 /// self.0.abs())
2129 /// } else {
2130 /// write!(formatter, "Foo({})", self.0)
2131 /// }
2132 /// }
2133 /// }
2134 ///
2135 /// assert_eq!(format!("{:+}", Foo(23)), "Foo(+23)");
2136 /// assert_eq!(format!("{:+}", Foo(-23)), "Foo(-23)");
2137 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2138 /// ```
2139 #[must_use]
2140 #[stable(feature = "fmt_flags", since = "1.5.0")]
2141 pub fn sign_plus(&self) -> bool {
2142 self.options.flags & flags::SIGN_PLUS_FLAG != 0
2143 }
2144
2145 /// Determines if the `-` flag was specified.
2146 ///
2147 /// # Examples
2148 ///
2149 /// ```
2150 /// use std::fmt;
2151 ///
2152 /// struct Foo(i32);
2153 ///
2154 /// impl fmt::Display for Foo {
2155 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2156 /// if formatter.sign_minus() {
2157 /// // You want a minus sign? Have one!
2158 /// write!(formatter, "-Foo({})", self.0)
2159 /// } else {
2160 /// write!(formatter, "Foo({})", self.0)
2161 /// }
2162 /// }
2163 /// }
2164 ///
2165 /// assert_eq!(format!("{:-}", Foo(23)), "-Foo(23)");
2166 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2167 /// ```
2168 #[must_use]
2169 #[stable(feature = "fmt_flags", since = "1.5.0")]
2170 pub fn sign_minus(&self) -> bool {
2171 self.options.flags & flags::SIGN_MINUS_FLAG != 0
2172 }
2173
2174 /// Determines if the `#` flag was specified.
2175 ///
2176 /// # Examples
2177 ///
2178 /// ```
2179 /// use std::fmt;
2180 ///
2181 /// struct Foo(i32);
2182 ///
2183 /// impl fmt::Display for Foo {
2184 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2185 /// if formatter.alternate() {
2186 /// write!(formatter, "Foo({})", self.0)
2187 /// } else {
2188 /// write!(formatter, "{}", self.0)
2189 /// }
2190 /// }
2191 /// }
2192 ///
2193 /// assert_eq!(format!("{:#}", Foo(23)), "Foo(23)");
2194 /// assert_eq!(format!("{}", Foo(23)), "23");
2195 /// ```
2196 #[must_use]
2197 #[stable(feature = "fmt_flags", since = "1.5.0")]
2198 pub fn alternate(&self) -> bool {
2199 self.options.flags & flags::ALTERNATE_FLAG != 0
2200 }
2201
2202 /// Determines if the `0` flag was specified.
2203 ///
2204 /// # Examples
2205 ///
2206 /// ```
2207 /// use std::fmt;
2208 ///
2209 /// struct Foo(i32);
2210 ///
2211 /// impl fmt::Display for Foo {
2212 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2213 /// assert!(formatter.sign_aware_zero_pad());
2214 /// assert_eq!(formatter.width(), Some(4));
2215 /// // We ignore the formatter's options.
2216 /// write!(formatter, "{}", self.0)
2217 /// }
2218 /// }
2219 ///
2220 /// assert_eq!(format!("{:04}", Foo(23)), "23");
2221 /// ```
2222 #[must_use]
2223 #[stable(feature = "fmt_flags", since = "1.5.0")]
2224 pub fn sign_aware_zero_pad(&self) -> bool {
2225 self.options.flags & flags::SIGN_AWARE_ZERO_PAD_FLAG != 0
2226 }
2227
2228 // FIXME: Decide what public API we want for these two flags.
2229 // https://github.com/rust-lang/rust/issues/48584
2230 fn debug_lower_hex(&self) -> bool {
2231 self.options.flags & flags::DEBUG_LOWER_HEX_FLAG != 0
2232 }
2233 fn debug_upper_hex(&self) -> bool {
2234 self.options.flags & flags::DEBUG_UPPER_HEX_FLAG != 0
2235 }
2236
2237 /// Creates a [`DebugStruct`] builder designed to assist with creation of
2238 /// [`fmt::Debug`] implementations for structs.
2239 ///
2240 /// [`fmt::Debug`]: self::Debug
2241 ///
2242 /// # Examples
2243 ///
2244 /// ```rust
2245 /// use std::fmt;
2246 /// use std::net::Ipv4Addr;
2247 ///
2248 /// struct Foo {
2249 /// bar: i32,
2250 /// baz: String,
2251 /// addr: Ipv4Addr,
2252 /// }
2253 ///
2254 /// impl fmt::Debug for Foo {
2255 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2256 /// fmt.debug_struct("Foo")
2257 /// .field("bar", &self.bar)
2258 /// .field("baz", &self.baz)
2259 /// .field("addr", &format_args!("{}", self.addr))
2260 /// .finish()
2261 /// }
2262 /// }
2263 ///
2264 /// assert_eq!(
2265 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
2266 /// format!("{:?}", Foo {
2267 /// bar: 10,
2268 /// baz: "Hello World".to_string(),
2269 /// addr: Ipv4Addr::new(127, 0, 0, 1),
2270 /// })
2271 /// );
2272 /// ```
2273 #[stable(feature = "debug_builders", since = "1.2.0")]
2274 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
2275 builders::debug_struct_new(self, name)
2276 }
2277
2278 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2279 /// binaries. `debug_struct_fields_finish` is more general, but this is
2280 /// faster for 1 field.
2281 #[doc(hidden)]
2282 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2283 pub fn debug_struct_field1_finish<'b>(
2284 &'b mut self,
2285 name: &str,
2286 name1: &str,
2287 value1: &dyn Debug,
2288 ) -> Result {
2289 let mut builder = builders::debug_struct_new(self, name);
2290 builder.field(name1, value1);
2291 builder.finish()
2292 }
2293
2294 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2295 /// binaries. `debug_struct_fields_finish` is more general, but this is
2296 /// faster for 2 fields.
2297 #[doc(hidden)]
2298 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2299 pub fn debug_struct_field2_finish<'b>(
2300 &'b mut self,
2301 name: &str,
2302 name1: &str,
2303 value1: &dyn Debug,
2304 name2: &str,
2305 value2: &dyn Debug,
2306 ) -> Result {
2307 let mut builder = builders::debug_struct_new(self, name);
2308 builder.field(name1, value1);
2309 builder.field(name2, value2);
2310 builder.finish()
2311 }
2312
2313 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2314 /// binaries. `debug_struct_fields_finish` is more general, but this is
2315 /// faster for 3 fields.
2316 #[doc(hidden)]
2317 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2318 pub fn debug_struct_field3_finish<'b>(
2319 &'b mut self,
2320 name: &str,
2321 name1: &str,
2322 value1: &dyn Debug,
2323 name2: &str,
2324 value2: &dyn Debug,
2325 name3: &str,
2326 value3: &dyn Debug,
2327 ) -> Result {
2328 let mut builder = builders::debug_struct_new(self, name);
2329 builder.field(name1, value1);
2330 builder.field(name2, value2);
2331 builder.field(name3, value3);
2332 builder.finish()
2333 }
2334
2335 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2336 /// binaries. `debug_struct_fields_finish` is more general, but this is
2337 /// faster for 4 fields.
2338 #[doc(hidden)]
2339 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2340 pub fn debug_struct_field4_finish<'b>(
2341 &'b mut self,
2342 name: &str,
2343 name1: &str,
2344 value1: &dyn Debug,
2345 name2: &str,
2346 value2: &dyn Debug,
2347 name3: &str,
2348 value3: &dyn Debug,
2349 name4: &str,
2350 value4: &dyn Debug,
2351 ) -> Result {
2352 let mut builder = builders::debug_struct_new(self, name);
2353 builder.field(name1, value1);
2354 builder.field(name2, value2);
2355 builder.field(name3, value3);
2356 builder.field(name4, value4);
2357 builder.finish()
2358 }
2359
2360 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2361 /// binaries. `debug_struct_fields_finish` is more general, but this is
2362 /// faster for 5 fields.
2363 #[doc(hidden)]
2364 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2365 pub fn debug_struct_field5_finish<'b>(
2366 &'b mut self,
2367 name: &str,
2368 name1: &str,
2369 value1: &dyn Debug,
2370 name2: &str,
2371 value2: &dyn Debug,
2372 name3: &str,
2373 value3: &dyn Debug,
2374 name4: &str,
2375 value4: &dyn Debug,
2376 name5: &str,
2377 value5: &dyn Debug,
2378 ) -> Result {
2379 let mut builder = builders::debug_struct_new(self, name);
2380 builder.field(name1, value1);
2381 builder.field(name2, value2);
2382 builder.field(name3, value3);
2383 builder.field(name4, value4);
2384 builder.field(name5, value5);
2385 builder.finish()
2386 }
2387
2388 /// Shrinks `derive(Debug)` code, for faster compilation and smaller binaries.
2389 /// For the cases not covered by `debug_struct_field[12345]_finish`.
2390 #[doc(hidden)]
2391 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2392 pub fn debug_struct_fields_finish<'b>(
2393 &'b mut self,
2394 name: &str,
2395 names: &[&str],
2396 values: &[&dyn Debug],
2397 ) -> Result {
2398 assert_eq!(names.len(), values.len());
2399 let mut builder = builders::debug_struct_new(self, name);
2400 for (name, value) in iter::zip(names, values) {
2401 builder.field(name, value);
2402 }
2403 builder.finish()
2404 }
2405
2406 /// Creates a `DebugTuple` builder designed to assist with creation of
2407 /// `fmt::Debug` implementations for tuple structs.
2408 ///
2409 /// # Examples
2410 ///
2411 /// ```rust
2412 /// use std::fmt;
2413 /// use std::marker::PhantomData;
2414 ///
2415 /// struct Foo<T>(i32, String, PhantomData<T>);
2416 ///
2417 /// impl<T> fmt::Debug for Foo<T> {
2418 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2419 /// fmt.debug_tuple("Foo")
2420 /// .field(&self.0)
2421 /// .field(&self.1)
2422 /// .field(&format_args!("_"))
2423 /// .finish()
2424 /// }
2425 /// }
2426 ///
2427 /// assert_eq!(
2428 /// "Foo(10, \"Hello\", _)",
2429 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
2430 /// );
2431 /// ```
2432 #[stable(feature = "debug_builders", since = "1.2.0")]
2433 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
2434 builders::debug_tuple_new(self, name)
2435 }
2436
2437 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2438 /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2439 /// for 1 field.
2440 #[doc(hidden)]
2441 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2442 pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result {
2443 let mut builder = builders::debug_tuple_new(self, name);
2444 builder.field(value1);
2445 builder.finish()
2446 }
2447
2448 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2449 /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2450 /// for 2 fields.
2451 #[doc(hidden)]
2452 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2453 pub fn debug_tuple_field2_finish<'b>(
2454 &'b mut self,
2455 name: &str,
2456 value1: &dyn Debug,
2457 value2: &dyn Debug,
2458 ) -> Result {
2459 let mut builder = builders::debug_tuple_new(self, name);
2460 builder.field(value1);
2461 builder.field(value2);
2462 builder.finish()
2463 }
2464
2465 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2466 /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2467 /// for 3 fields.
2468 #[doc(hidden)]
2469 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2470 pub fn debug_tuple_field3_finish<'b>(
2471 &'b mut self,
2472 name: &str,
2473 value1: &dyn Debug,
2474 value2: &dyn Debug,
2475 value3: &dyn Debug,
2476 ) -> Result {
2477 let mut builder = builders::debug_tuple_new(self, name);
2478 builder.field(value1);
2479 builder.field(value2);
2480 builder.field(value3);
2481 builder.finish()
2482 }
2483
2484 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2485 /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2486 /// for 4 fields.
2487 #[doc(hidden)]
2488 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2489 pub fn debug_tuple_field4_finish<'b>(
2490 &'b mut self,
2491 name: &str,
2492 value1: &dyn Debug,
2493 value2: &dyn Debug,
2494 value3: &dyn Debug,
2495 value4: &dyn Debug,
2496 ) -> Result {
2497 let mut builder = builders::debug_tuple_new(self, name);
2498 builder.field(value1);
2499 builder.field(value2);
2500 builder.field(value3);
2501 builder.field(value4);
2502 builder.finish()
2503 }
2504
2505 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2506 /// binaries. `debug_tuple_fields_finish` is more general, but this is faster
2507 /// for 5 fields.
2508 #[doc(hidden)]
2509 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2510 pub fn debug_tuple_field5_finish<'b>(
2511 &'b mut self,
2512 name: &str,
2513 value1: &dyn Debug,
2514 value2: &dyn Debug,
2515 value3: &dyn Debug,
2516 value4: &dyn Debug,
2517 value5: &dyn Debug,
2518 ) -> Result {
2519 let mut builder = builders::debug_tuple_new(self, name);
2520 builder.field(value1);
2521 builder.field(value2);
2522 builder.field(value3);
2523 builder.field(value4);
2524 builder.field(value5);
2525 builder.finish()
2526 }
2527
2528 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2529 /// binaries. For the cases not covered by `debug_tuple_field[12345]_finish`.
2530 #[doc(hidden)]
2531 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2532 pub fn debug_tuple_fields_finish<'b>(
2533 &'b mut self,
2534 name: &str,
2535 values: &[&dyn Debug],
2536 ) -> Result {
2537 let mut builder = builders::debug_tuple_new(self, name);
2538 for value in values {
2539 builder.field(value);
2540 }
2541 builder.finish()
2542 }
2543
2544 /// Creates a `DebugList` builder designed to assist with creation of
2545 /// `fmt::Debug` implementations for list-like structures.
2546 ///
2547 /// # Examples
2548 ///
2549 /// ```rust
2550 /// use std::fmt;
2551 ///
2552 /// struct Foo(Vec<i32>);
2553 ///
2554 /// impl fmt::Debug for Foo {
2555 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2556 /// fmt.debug_list().entries(self.0.iter()).finish()
2557 /// }
2558 /// }
2559 ///
2560 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2561 /// ```
2562 #[stable(feature = "debug_builders", since = "1.2.0")]
2563 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2564 builders::debug_list_new(self)
2565 }
2566
2567 /// Creates a `DebugSet` builder designed to assist with creation of
2568 /// `fmt::Debug` implementations for set-like structures.
2569 ///
2570 /// # Examples
2571 ///
2572 /// ```rust
2573 /// use std::fmt;
2574 ///
2575 /// struct Foo(Vec<i32>);
2576 ///
2577 /// impl fmt::Debug for Foo {
2578 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2579 /// fmt.debug_set().entries(self.0.iter()).finish()
2580 /// }
2581 /// }
2582 ///
2583 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2584 /// ```
2585 ///
2586 /// [`format_args!`]: crate::format_args
2587 ///
2588 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2589 /// to build a list of match arms:
2590 ///
2591 /// ```rust
2592 /// use std::fmt;
2593 ///
2594 /// struct Arm<'a, L, R>(&'a (L, R));
2595 /// struct Table<'a, K, V>(&'a [(K, V)], V);
2596 ///
2597 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2598 /// where
2599 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
2600 /// {
2601 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2602 /// L::fmt(&(self.0).0, fmt)?;
2603 /// fmt.write_str(" => ")?;
2604 /// R::fmt(&(self.0).1, fmt)
2605 /// }
2606 /// }
2607 ///
2608 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2609 /// where
2610 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
2611 /// {
2612 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2613 /// fmt.debug_set()
2614 /// .entries(self.0.iter().map(Arm))
2615 /// .entry(&Arm(&(format_args!("_"), &self.1)))
2616 /// .finish()
2617 /// }
2618 /// }
2619 /// ```
2620 #[stable(feature = "debug_builders", since = "1.2.0")]
2621 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2622 builders::debug_set_new(self)
2623 }
2624
2625 /// Creates a `DebugMap` builder designed to assist with creation of
2626 /// `fmt::Debug` implementations for map-like structures.
2627 ///
2628 /// # Examples
2629 ///
2630 /// ```rust
2631 /// use std::fmt;
2632 ///
2633 /// struct Foo(Vec<(String, i32)>);
2634 ///
2635 /// impl fmt::Debug for Foo {
2636 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2637 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2638 /// }
2639 /// }
2640 ///
2641 /// assert_eq!(
2642 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2643 /// r#"{"A": 10, "B": 11}"#
2644 /// );
2645 /// ```
2646 #[stable(feature = "debug_builders", since = "1.2.0")]
2647 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2648 builders::debug_map_new(self)
2649 }
2650
2651 /// Returns the sign of this formatter (`+` or `-`).
2652 #[unstable(feature = "formatting_options", issue = "118117")]
2653 pub const fn sign(&self) -> Option<Sign> {
2654 self.options.get_sign()
2655 }
2656
2657 /// Returns the formatting options this formatter corresponds to.
2658 #[unstable(feature = "formatting_options", issue = "118117")]
2659 pub const fn options(&self) -> FormattingOptions {
2660 self.options
2661 }
2662}
2663
2664#[stable(since = "1.2.0", feature = "formatter_write")]
2665impl Write for Formatter<'_> {
2666 fn write_str(&mut self, s: &str) -> Result {
2667 self.buf.write_str(s)
2668 }
2669
2670 fn write_char(&mut self, c: char) -> Result {
2671 self.buf.write_char(c)
2672 }
2673
2674 #[inline]
2675 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2676 if let Some(s) = args.as_statically_known_str() {
2677 self.buf.write_str(s)
2678 } else {
2679 write(self.buf, args)
2680 }
2681 }
2682}
2683
2684#[stable(feature = "rust1", since = "1.0.0")]
2685impl Display for Error {
2686 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2687 Display::fmt("an error occurred when formatting an argument", f)
2688 }
2689}
2690
2691// Implementations of the core formatting traits
2692
2693macro_rules! fmt_refs {
2694 ($($tr:ident),*) => {
2695 $(
2696 #[stable(feature = "rust1", since = "1.0.0")]
2697 impl<T: ?Sized + $tr> $tr for &T {
2698 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2699 }
2700 #[stable(feature = "rust1", since = "1.0.0")]
2701 impl<T: ?Sized + $tr> $tr for &mut T {
2702 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2703 }
2704 )*
2705 }
2706}
2707
2708fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2709
2710#[unstable(feature = "never_type", issue = "35121")]
2711impl Debug for ! {
2712 #[inline]
2713 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2714 *self
2715 }
2716}
2717
2718#[unstable(feature = "never_type", issue = "35121")]
2719impl Display for ! {
2720 #[inline]
2721 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2722 *self
2723 }
2724}
2725
2726#[stable(feature = "rust1", since = "1.0.0")]
2727impl Debug for bool {
2728 #[inline]
2729 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2730 Display::fmt(self, f)
2731 }
2732}
2733
2734#[stable(feature = "rust1", since = "1.0.0")]
2735impl Display for bool {
2736 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2737 Display::fmt(if *self { "true" } else { "false" }, f)
2738 }
2739}
2740
2741#[stable(feature = "rust1", since = "1.0.0")]
2742impl Debug for str {
2743 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2744 f.write_char('"')?;
2745
2746 // substring we know is printable
2747 let mut printable_range = 0..0;
2748
2749 fn needs_escape(b: u8) -> bool {
2750 b > 0x7E || b < 0x20 || b == b'\\' || b == b'"'
2751 }
2752
2753 // the loop here first skips over runs of printable ASCII as a fast path.
2754 // other chars (unicode, or ASCII that needs escaping) are then handled per-`char`.
2755 let mut rest = self;
2756 while rest.len() > 0 {
2757 let Some(non_printable_start) = rest.as_bytes().iter().position(|&b| needs_escape(b))
2758 else {
2759 printable_range.end += rest.len();
2760 break;
2761 };
2762
2763 printable_range.end += non_printable_start;
2764 // SAFETY: the position was derived from an iterator, so is known to be within bounds, and at a char boundary
2765 rest = unsafe { rest.get_unchecked(non_printable_start..) };
2766
2767 let mut chars = rest.chars();
2768 if let Some(c) = chars.next() {
2769 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2770 escape_grapheme_extended: true,
2771 escape_single_quote: false,
2772 escape_double_quote: true,
2773 });
2774 if esc.len() != 1 {
2775 f.write_str(&self[printable_range.clone()])?;
2776 Display::fmt(&esc, f)?;
2777 printable_range.start = printable_range.end + c.len_utf8();
2778 }
2779 printable_range.end += c.len_utf8();
2780 }
2781 rest = chars.as_str();
2782 }
2783
2784 f.write_str(&self[printable_range])?;
2785
2786 f.write_char('"')
2787 }
2788}
2789
2790#[stable(feature = "rust1", since = "1.0.0")]
2791impl Display for str {
2792 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2793 f.pad(self)
2794 }
2795}
2796
2797#[stable(feature = "rust1", since = "1.0.0")]
2798impl Debug for char {
2799 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2800 f.write_char('\'')?;
2801 let esc = self.escape_debug_ext(EscapeDebugExtArgs {
2802 escape_grapheme_extended: true,
2803 escape_single_quote: true,
2804 escape_double_quote: false,
2805 });
2806 Display::fmt(&esc, f)?;
2807 f.write_char('\'')
2808 }
2809}
2810
2811#[stable(feature = "rust1", since = "1.0.0")]
2812impl Display for char {
2813 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2814 if f.options.flags & (flags::WIDTH_FLAG | flags::PRECISION_FLAG) == 0 {
2815 f.write_char(*self)
2816 } else {
2817 f.pad(self.encode_utf8(&mut [0; MAX_LEN_UTF8]))
2818 }
2819 }
2820}
2821
2822#[stable(feature = "rust1", since = "1.0.0")]
2823impl<T: ?Sized> Pointer for *const T {
2824 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2825 if <<T as core::ptr::Pointee>::Metadata as core::unit::IsUnit>::is_unit() {
2826 pointer_fmt_inner(self.expose_provenance(), f)
2827 } else {
2828 f.debug_struct("Pointer")
2829 .field_with("addr", |f| pointer_fmt_inner(self.expose_provenance(), f))
2830 .field("metadata", &core::ptr::metadata(*self))
2831 .finish()
2832 }
2833 }
2834}
2835
2836/// Since the formatting will be identical for all pointer types, uses a
2837/// non-monomorphized implementation for the actual formatting to reduce the
2838/// amount of codegen work needed.
2839///
2840/// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
2841/// `fn(...) -> ...` without using [problematic] "Oxford Casts".
2842///
2843/// [problematic]: https://github.com/rust-lang/rust/issues/95489
2844pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
2845 let old_options = f.options;
2846
2847 // The alternate flag is already treated by LowerHex as being special-
2848 // it denotes whether to prefix with 0x. We use it to work out whether
2849 // or not to zero extend, and then unconditionally set it to get the
2850 // prefix.
2851 if f.options.get_alternate() {
2852 f.options.sign_aware_zero_pad(true);
2853
2854 if f.options.get_width().is_none() {
2855 f.options.width(Some((usize::BITS / 4) as u16 + 2));
2856 }
2857 }
2858 f.options.alternate(true);
2859
2860 let ret = LowerHex::fmt(&ptr_addr, f);
2861
2862 f.options = old_options;
2863
2864 ret
2865}
2866
2867#[stable(feature = "rust1", since = "1.0.0")]
2868impl<T: ?Sized> Pointer for *mut T {
2869 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2870 Pointer::fmt(&(*self as *const T), f)
2871 }
2872}
2873
2874#[stable(feature = "rust1", since = "1.0.0")]
2875impl<T: ?Sized> Pointer for &T {
2876 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2877 Pointer::fmt(&(*self as *const T), f)
2878 }
2879}
2880
2881#[stable(feature = "rust1", since = "1.0.0")]
2882impl<T: ?Sized> Pointer for &mut T {
2883 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2884 Pointer::fmt(&(&**self as *const T), f)
2885 }
2886}
2887
2888// Implementation of Display/Debug for various core types
2889
2890#[stable(feature = "rust1", since = "1.0.0")]
2891impl<T: ?Sized> Debug for *const T {
2892 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2893 Pointer::fmt(self, f)
2894 }
2895}
2896#[stable(feature = "rust1", since = "1.0.0")]
2897impl<T: ?Sized> Debug for *mut T {
2898 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2899 Pointer::fmt(self, f)
2900 }
2901}
2902
2903macro_rules! peel {
2904 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
2905}
2906
2907macro_rules! tuple {
2908 () => ();
2909 ( $($name:ident,)+ ) => (
2910 maybe_tuple_doc! {
2911 $($name)+ @
2912 #[stable(feature = "rust1", since = "1.0.0")]
2913 impl<$($name:Debug),+> Debug for ($($name,)+) where last_type!($($name,)+): ?Sized {
2914 #[allow(non_snake_case, unused_assignments)]
2915 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2916 let mut builder = f.debug_tuple("");
2917 let ($(ref $name,)+) = *self;
2918 $(
2919 builder.field(&$name);
2920 )+
2921
2922 builder.finish()
2923 }
2924 }
2925 }
2926 peel! { $($name,)+ }
2927 )
2928}
2929
2930macro_rules! maybe_tuple_doc {
2931 ($a:ident @ #[$meta:meta] $item:item) => {
2932 #[doc(fake_variadic)]
2933 #[doc = "This trait is implemented for tuples up to twelve items long."]
2934 #[$meta]
2935 $item
2936 };
2937 ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
2938 #[doc(hidden)]
2939 #[$meta]
2940 $item
2941 };
2942}
2943
2944macro_rules! last_type {
2945 ($a:ident,) => { $a };
2946 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
2947}
2948
2949tuple! { E, D, C, B, A, Z, Y, X, W, V, U, T, }
2950
2951#[stable(feature = "rust1", since = "1.0.0")]
2952impl<T: Debug> Debug for [T] {
2953 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2954 f.debug_list().entries(self.iter()).finish()
2955 }
2956}
2957
2958#[stable(feature = "rust1", since = "1.0.0")]
2959impl Debug for () {
2960 #[inline]
2961 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2962 f.pad("()")
2963 }
2964}
2965#[stable(feature = "rust1", since = "1.0.0")]
2966impl<T: ?Sized> Debug for PhantomData<T> {
2967 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2968 write!(f, "PhantomData<{}>", crate::any::type_name::<T>())
2969 }
2970}
2971
2972#[stable(feature = "rust1", since = "1.0.0")]
2973impl<T: Copy + Debug> Debug for Cell<T> {
2974 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2975 f.debug_struct("Cell").field("value", &self.get()).finish()
2976 }
2977}
2978
2979#[stable(feature = "rust1", since = "1.0.0")]
2980impl<T: ?Sized + Debug> Debug for RefCell<T> {
2981 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2982 let mut d = f.debug_struct("RefCell");
2983 match self.try_borrow() {
2984 Ok(borrow) => d.field("value", &borrow),
2985 Err(_) => d.field("value", &format_args!("<borrowed>")),
2986 };
2987 d.finish()
2988 }
2989}
2990
2991#[stable(feature = "rust1", since = "1.0.0")]
2992impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
2993 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2994 Debug::fmt(&**self, f)
2995 }
2996}
2997
2998#[stable(feature = "rust1", since = "1.0.0")]
2999impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
3000 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3001 Debug::fmt(&*(self.deref()), f)
3002 }
3003}
3004
3005#[stable(feature = "core_impl_debug", since = "1.9.0")]
3006impl<T: ?Sized> Debug for UnsafeCell<T> {
3007 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3008 f.debug_struct("UnsafeCell").finish_non_exhaustive()
3009 }
3010}
3011
3012#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
3013impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
3014 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3015 f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
3016 }
3017}
3018
3019// If you expected tests to be here, look instead at the core/tests/fmt.rs file,
3020// it's a lot easier than creating all of the rt::Piece structures here.
3021// There are also tests in the alloc crate, for those that need allocations.