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