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