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