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