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