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