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::{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"]
1095pub trait Debug: PointeeSized {
1096 #[doc = include_str!("fmt_trait_method_doc.md")]
1097 ///
1098 /// # Examples
1099 ///
1100 /// ```
1101 /// use std::fmt;
1102 ///
1103 /// struct Position {
1104 /// longitude: f32,
1105 /// latitude: f32,
1106 /// }
1107 ///
1108 /// impl fmt::Debug for Position {
1109 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1110 /// f.debug_tuple("")
1111 /// .field(&self.longitude)
1112 /// .field(&self.latitude)
1113 /// .finish()
1114 /// }
1115 /// }
1116 ///
1117 /// let position = Position { longitude: 1.987, latitude: 2.983 };
1118 /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
1119 ///
1120 /// assert_eq!(format!("{position:#?}"), "(
1121 /// 1.987,
1122 /// 2.983,
1123 /// )");
1124 /// ```
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1127}
1128
1129// Separate module to reexport the macro `Debug` from prelude without the trait `Debug`.
1130pub(crate) mod macros {
1131 /// Derive macro generating an impl of the trait `Debug`.
1132 #[rustc_builtin_macro]
1133 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1134 #[allow_internal_unstable(core_intrinsics, fmt_helpers_for_derive)]
1135 pub macro Debug($item:item) {
1136 /* compiler built-in */
1137 }
1138}
1139#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1140#[doc(inline)]
1141pub use macros::Debug;
1142
1143/// Format trait for an empty format, `{}`.
1144///
1145/// Implementing this trait for a type will automatically implement the
1146/// [`ToString`][tostring] trait for the type, allowing the usage
1147/// of the [`.to_string()`][tostring_function] method. Prefer implementing
1148/// the `Display` trait for a type, rather than [`ToString`][tostring].
1149///
1150/// `Display` is similar to [`Debug`], but `Display` is for user-facing
1151/// output, and so cannot be derived.
1152///
1153/// For more information on formatters, see [the module-level documentation][module].
1154///
1155/// [module]: ../../std/fmt/index.html
1156/// [tostring]: ../../std/string/trait.ToString.html
1157/// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
1158///
1159/// # Completeness and parseability
1160///
1161/// `Display` for a type might not necessarily be a lossless or complete representation of the type.
1162/// It may omit internal state, precision, or other information the type does not consider important
1163/// for user-facing output, as determined by the type. As such, the output of `Display` might not be
1164/// possible to parse, and even if it is, the result of parsing might not exactly match the original
1165/// value.
1166///
1167/// However, if a type has a lossless `Display` implementation whose output is meant to be
1168/// conveniently machine-parseable and not just meant for human consumption, then the type may wish
1169/// to accept the same format in `FromStr`, and document that usage. Having both `Display` and
1170/// `FromStr` implementations where the result of `Display` cannot be parsed with `FromStr` may
1171/// surprise users.
1172///
1173/// # Internationalization
1174///
1175/// Because a type can only have one `Display` implementation, it is often preferable
1176/// to only implement `Display` when there is a single most "obvious" way that
1177/// values can be formatted as text. This could mean formatting according to the
1178/// "invariant" culture and "undefined" locale, or it could mean that the type
1179/// display is designed for a specific culture/locale, such as developer logs.
1180///
1181/// If not all values have a justifiably canonical textual format or if you want
1182/// to support alternative formats not covered by the standard set of possible
1183/// [formatting traits], the most flexible approach is display adapters: methods
1184/// like [`str::escape_default`] or [`Path::display`] which create a wrapper
1185/// implementing `Display` to output the specific display format.
1186///
1187/// [formatting traits]: ../../std/fmt/index.html#formatting-traits
1188/// [`Path::display`]: ../../std/path/struct.Path.html#method.display
1189///
1190/// # Examples
1191///
1192/// Implementing `Display` on a type:
1193///
1194/// ```
1195/// use std::fmt;
1196///
1197/// struct Point {
1198/// x: i32,
1199/// y: i32,
1200/// }
1201///
1202/// impl fmt::Display for Point {
1203/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1204/// write!(f, "({}, {})", self.x, self.y)
1205/// }
1206/// }
1207///
1208/// let origin = Point { x: 0, y: 0 };
1209///
1210/// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
1211/// ```
1212#[rustc_on_unimplemented(
1213 on(
1214 any(Self = "std::path::Path", Self = "std::path::PathBuf"),
1215 label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
1216 note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
1217 as they may contain non-Unicode data",
1218 ),
1219 on(
1220 from_desugaring = "FormatLiteral",
1221 note = "in format strings you may be able to use `{{:?}}` (or `{{:#?}}` for pretty-print) instead",
1222 label = "`{Self}` cannot be formatted with the default formatter",
1223 ),
1224 message = "`{Self}` doesn't implement `{this}`"
1225)]
1226#[doc(alias = "{}")]
1227#[rustc_diagnostic_item = "Display"]
1228#[stable(feature = "rust1", since = "1.0.0")]
1229pub trait Display: PointeeSized {
1230 #[doc = include_str!("fmt_trait_method_doc.md")]
1231 ///
1232 /// # Examples
1233 ///
1234 /// ```
1235 /// use std::fmt;
1236 ///
1237 /// struct Position {
1238 /// longitude: f32,
1239 /// latitude: f32,
1240 /// }
1241 ///
1242 /// impl fmt::Display for Position {
1243 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1244 /// write!(f, "({}, {})", self.longitude, self.latitude)
1245 /// }
1246 /// }
1247 ///
1248 /// assert_eq!(
1249 /// "(1.987, 2.983)",
1250 /// format!("{}", Position { longitude: 1.987, latitude: 2.983, }),
1251 /// );
1252 /// ```
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1255}
1256
1257/// `o` formatting.
1258///
1259/// The `Octal` trait should format its output as a number in base-8.
1260///
1261/// For primitive signed integers (`i8` to `i128`, and `isize`),
1262/// negative values are formatted as the two’s complement representation.
1263///
1264/// The alternate flag, `#`, adds a `0o` in front of the output.
1265///
1266/// For more information on formatters, see [the module-level documentation][module].
1267///
1268/// [module]: ../../std/fmt/index.html
1269///
1270/// # Examples
1271///
1272/// Basic usage with `i32`:
1273///
1274/// ```
1275/// let x = 42; // 42 is '52' in octal
1276///
1277/// assert_eq!(format!("{x:o}"), "52");
1278/// assert_eq!(format!("{x:#o}"), "0o52");
1279///
1280/// assert_eq!(format!("{:o}", -16), "37777777760");
1281/// ```
1282///
1283/// Implementing `Octal` on a type:
1284///
1285/// ```
1286/// use std::fmt;
1287///
1288/// struct Length(i32);
1289///
1290/// impl fmt::Octal for Length {
1291/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1292/// let val = self.0;
1293///
1294/// fmt::Octal::fmt(&val, f) // delegate to i32's implementation
1295/// }
1296/// }
1297///
1298/// let l = Length(9);
1299///
1300/// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
1301///
1302/// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
1303/// ```
1304#[stable(feature = "rust1", since = "1.0.0")]
1305pub trait Octal: PointeeSized {
1306 #[doc = include_str!("fmt_trait_method_doc.md")]
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1309}
1310
1311/// `b` formatting.
1312///
1313/// The `Binary` trait should format its output as a number in binary.
1314///
1315/// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
1316/// negative values are formatted as the two’s complement representation.
1317///
1318/// The alternate flag, `#`, adds a `0b` in front of the output.
1319///
1320/// For more information on formatters, see [the module-level documentation][module].
1321///
1322/// [module]: ../../std/fmt/index.html
1323///
1324/// # Examples
1325///
1326/// Basic usage with [`i32`]:
1327///
1328/// ```
1329/// let x = 42; // 42 is '101010' in binary
1330///
1331/// assert_eq!(format!("{x:b}"), "101010");
1332/// assert_eq!(format!("{x:#b}"), "0b101010");
1333///
1334/// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
1335/// ```
1336///
1337/// Implementing `Binary` on a type:
1338///
1339/// ```
1340/// use std::fmt;
1341///
1342/// struct Length(i32);
1343///
1344/// impl fmt::Binary for Length {
1345/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1346/// let val = self.0;
1347///
1348/// fmt::Binary::fmt(&val, f) // delegate to i32's implementation
1349/// }
1350/// }
1351///
1352/// let l = Length(107);
1353///
1354/// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
1355///
1356/// assert_eq!(
1357/// // Note that the `0b` prefix added by `#` is included in the total width, so we
1358/// // need to add two to correctly display all 32 bits.
1359/// format!("l as binary is: {l:#034b}"),
1360/// "l as binary is: 0b00000000000000000000000001101011"
1361/// );
1362/// ```
1363#[stable(feature = "rust1", since = "1.0.0")]
1364pub trait Binary: PointeeSized {
1365 #[doc = include_str!("fmt_trait_method_doc.md")]
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1368}
1369
1370/// `x` formatting.
1371///
1372/// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
1373/// in lower case.
1374///
1375/// For primitive signed integers (`i8` to `i128`, and `isize`),
1376/// negative values are formatted as the two’s complement representation.
1377///
1378/// The alternate flag, `#`, adds a `0x` in front of the output.
1379///
1380/// For more information on formatters, see [the module-level documentation][module].
1381///
1382/// [module]: ../../std/fmt/index.html
1383///
1384/// # Examples
1385///
1386/// Basic usage with `i32`:
1387///
1388/// ```
1389/// let y = 42; // 42 is '2a' in hex
1390///
1391/// assert_eq!(format!("{y:x}"), "2a");
1392/// assert_eq!(format!("{y:#x}"), "0x2a");
1393///
1394/// assert_eq!(format!("{:x}", -16), "fffffff0");
1395/// ```
1396///
1397/// Implementing `LowerHex` on a type:
1398///
1399/// ```
1400/// use std::fmt;
1401///
1402/// struct Length(i32);
1403///
1404/// impl fmt::LowerHex for Length {
1405/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1406/// let val = self.0;
1407///
1408/// fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
1409/// }
1410/// }
1411///
1412/// let l = Length(9);
1413///
1414/// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
1415///
1416/// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
1417/// ```
1418#[stable(feature = "rust1", since = "1.0.0")]
1419pub trait LowerHex: PointeeSized {
1420 #[doc = include_str!("fmt_trait_method_doc.md")]
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1423}
1424
1425/// `X` formatting.
1426///
1427/// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
1428/// in upper case.
1429///
1430/// For primitive signed integers (`i8` to `i128`, and `isize`),
1431/// negative values are formatted as the two’s complement representation.
1432///
1433/// The alternate flag, `#`, adds a `0x` in front of the output.
1434///
1435/// For more information on formatters, see [the module-level documentation][module].
1436///
1437/// [module]: ../../std/fmt/index.html
1438///
1439/// # Examples
1440///
1441/// Basic usage with `i32`:
1442///
1443/// ```
1444/// let y = 42; // 42 is '2A' in hex
1445///
1446/// assert_eq!(format!("{y:X}"), "2A");
1447/// assert_eq!(format!("{y:#X}"), "0x2A");
1448///
1449/// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
1450/// ```
1451///
1452/// Implementing `UpperHex` on a type:
1453///
1454/// ```
1455/// use std::fmt;
1456///
1457/// struct Length(i32);
1458///
1459/// impl fmt::UpperHex for Length {
1460/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1461/// let val = self.0;
1462///
1463/// fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
1464/// }
1465/// }
1466///
1467/// let l = Length(i32::MAX);
1468///
1469/// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
1470///
1471/// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
1472/// ```
1473#[stable(feature = "rust1", since = "1.0.0")]
1474pub trait UpperHex: PointeeSized {
1475 #[doc = include_str!("fmt_trait_method_doc.md")]
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1478}
1479
1480/// `p` formatting.
1481///
1482/// The `Pointer` trait should format its output as a memory location. This is commonly presented
1483/// as hexadecimal. For more information on formatters, see [the module-level documentation][module].
1484///
1485/// Printing of pointers is not a reliable way to discover how Rust programs are implemented.
1486/// The act of reading an address changes the program itself, and may change how the data is represented
1487/// in memory, and may affect which optimizations are applied to the code.
1488///
1489/// The printed pointer values are not guaranteed to be stable nor unique identifiers of objects.
1490/// Rust allows moving values to different memory locations, and may reuse the same memory locations
1491/// for different purposes.
1492///
1493/// There is no guarantee that the printed value can be converted back to a pointer.
1494///
1495/// [module]: ../../std/fmt/index.html
1496///
1497/// # Examples
1498///
1499/// Basic usage with `&i32`:
1500///
1501/// ```
1502/// let x = &42;
1503///
1504/// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
1505/// ```
1506///
1507/// Implementing `Pointer` on a type:
1508///
1509/// ```
1510/// use std::fmt;
1511///
1512/// struct Length(i32);
1513///
1514/// impl fmt::Pointer for Length {
1515/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1516/// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
1517///
1518/// let ptr = self as *const Self;
1519/// fmt::Pointer::fmt(&ptr, f)
1520/// }
1521/// }
1522///
1523/// let l = Length(42);
1524///
1525/// println!("l is in memory here: {l:p}");
1526///
1527/// let l_ptr = format!("{l:018p}");
1528/// assert_eq!(l_ptr.len(), 18);
1529/// assert_eq!(&l_ptr[..2], "0x");
1530/// ```
1531#[stable(feature = "rust1", since = "1.0.0")]
1532#[rustc_diagnostic_item = "Pointer"]
1533pub trait Pointer: PointeeSized {
1534 #[doc = include_str!("fmt_trait_method_doc.md")]
1535 #[stable(feature = "rust1", since = "1.0.0")]
1536 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1537}
1538
1539/// `e` formatting.
1540///
1541/// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
1542///
1543/// For more information on formatters, see [the module-level documentation][module].
1544///
1545/// [module]: ../../std/fmt/index.html
1546///
1547/// # Examples
1548///
1549/// Basic usage with `f64`:
1550///
1551/// ```
1552/// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
1553///
1554/// assert_eq!(format!("{x:e}"), "4.2e1");
1555/// ```
1556///
1557/// Implementing `LowerExp` on a type:
1558///
1559/// ```
1560/// use std::fmt;
1561///
1562/// struct Length(i32);
1563///
1564/// impl fmt::LowerExp for Length {
1565/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1566/// let val = f64::from(self.0);
1567/// fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
1568/// }
1569/// }
1570///
1571/// let l = Length(100);
1572///
1573/// assert_eq!(
1574/// format!("l in scientific notation is: {l:e}"),
1575/// "l in scientific notation is: 1e2"
1576/// );
1577///
1578/// assert_eq!(
1579/// format!("l in scientific notation is: {l:05e}"),
1580/// "l in scientific notation is: 001e2"
1581/// );
1582/// ```
1583#[stable(feature = "rust1", since = "1.0.0")]
1584pub trait LowerExp: PointeeSized {
1585 #[doc = include_str!("fmt_trait_method_doc.md")]
1586 #[stable(feature = "rust1", since = "1.0.0")]
1587 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1588}
1589
1590/// `E` formatting.
1591///
1592/// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
1593///
1594/// For more information on formatters, see [the module-level documentation][module].
1595///
1596/// [module]: ../../std/fmt/index.html
1597///
1598/// # Examples
1599///
1600/// Basic usage with `f64`:
1601///
1602/// ```
1603/// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
1604///
1605/// assert_eq!(format!("{x:E}"), "4.2E1");
1606/// ```
1607///
1608/// Implementing `UpperExp` on a type:
1609///
1610/// ```
1611/// use std::fmt;
1612///
1613/// struct Length(i32);
1614///
1615/// impl fmt::UpperExp for Length {
1616/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1617/// let val = f64::from(self.0);
1618/// fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
1619/// }
1620/// }
1621///
1622/// let l = Length(100);
1623///
1624/// assert_eq!(
1625/// format!("l in scientific notation is: {l:E}"),
1626/// "l in scientific notation is: 1E2"
1627/// );
1628///
1629/// assert_eq!(
1630/// format!("l in scientific notation is: {l:05E}"),
1631/// "l in scientific notation is: 001E2"
1632/// );
1633/// ```
1634#[stable(feature = "rust1", since = "1.0.0")]
1635pub trait UpperExp: PointeeSized {
1636 #[doc = include_str!("fmt_trait_method_doc.md")]
1637 #[stable(feature = "rust1", since = "1.0.0")]
1638 fn fmt(&self, f: &mut Formatter<'_>) -> Result;
1639}
1640
1641/// Takes an output stream and an `Arguments` struct that can be precompiled with
1642/// the `format_args!` macro.
1643///
1644/// The arguments will be formatted according to the specified format string
1645/// into the output stream provided.
1646///
1647/// # Examples
1648///
1649/// Basic usage:
1650///
1651/// ```
1652/// use std::fmt;
1653///
1654/// let mut output = String::new();
1655/// fmt::write(&mut output, format_args!("Hello {}!", "world"))
1656/// .expect("writing to a `String` should not fail");
1657/// assert_eq!(output, "Hello world!");
1658/// ```
1659///
1660/// Please note that using [`write!`] might be preferable. Example:
1661///
1662/// ```
1663/// use std::fmt::Write;
1664///
1665/// let mut output = String::new();
1666/// write!(&mut output, "Hello {}!", "world")
1667/// .expect("writing to a `String` should not fail");
1668/// assert_eq!(output, "Hello world!");
1669/// ```
1670///
1671/// [`write!`]: crate::write!
1672#[stable(feature = "rust1", since = "1.0.0")]
1673#[ferrocene::prevalidated]
1674pub fn write(output: &mut dyn Write, fmt: Arguments<'_>) -> Result {
1675 if let Some(s) = fmt.as_str() {
1676 return output.write_str(s);
1677 }
1678
1679 let mut template = fmt.template;
1680 let args = fmt.args;
1681
1682 let mut arg_index = 0;
1683
1684 // See comment on `fmt::Arguments` for the details of how the template is encoded.
1685
1686 // This must match the encoding from `expand_format_args` in
1687 // compiler/rustc_ast_lowering/src/format.rs.
1688 loop {
1689 // SAFETY: We can assume the template is valid.
1690 let n = unsafe {
1691 let n = template.read();
1692 template = template.add(1);
1693 n
1694 };
1695
1696 if n == 0 {
1697 // End of template.
1698 return Ok(());
1699 } else if n < 0x80 {
1700 // Literal string piece of length `n`.
1701
1702 // SAFETY: We can assume the strings in the template are valid.
1703 let s = unsafe {
1704 let s = crate::str::from_raw_parts(template.as_ptr(), n as usize);
1705 template = template.add(n as usize);
1706 s
1707 };
1708 output.write_str(s)?;
1709 } else if n == 0x80 {
1710 // Literal string piece with a 16-bit length.
1711
1712 // SAFETY: We can assume the strings in the template are valid.
1713 let s = unsafe {
1714 let len = usize::from(u16::from_le_bytes(template.cast_array().read()));
1715 template = template.add(2);
1716 let s = crate::str::from_raw_parts(template.as_ptr(), len);
1717 template = template.add(len);
1718 s
1719 };
1720 output.write_str(s)?;
1721 } else if n == 0xC0 {
1722 // Placeholder for next argument with default options.
1723 //
1724 // Having this as a separate case improves performance for the common case.
1725
1726 // SAFETY: We can assume the template only refers to arguments that exist.
1727 unsafe {
1728 args.add(arg_index)
1729 .as_ref()
1730 .fmt(&mut Formatter::new(output, FormattingOptions::new()))?;
1731 }
1732 arg_index += 1;
1733 } else {
1734 // SAFETY: We can assume the template is valid.
1735 unsafe { assert_unchecked(n > 0xC0) };
1736
1737 // Placeholder with custom options.
1738
1739 let mut opt = FormattingOptions::new();
1740
1741 // SAFETY: We can assume the template is valid.
1742 unsafe {
1743 if n & 1 != 0 {
1744 opt.flags = u32::from_le_bytes(template.cast_array().read());
1745 template = template.add(4);
1746 }
1747 if n & 2 != 0 {
1748 opt.width = u16::from_le_bytes(template.cast_array().read());
1749 template = template.add(2);
1750 }
1751 if n & 4 != 0 {
1752 opt.precision = u16::from_le_bytes(template.cast_array().read());
1753 template = template.add(2);
1754 }
1755 if n & 8 != 0 {
1756 arg_index = usize::from(u16::from_le_bytes(template.cast_array().read()));
1757 template = template.add(2);
1758 }
1759 }
1760 if n & 16 != 0 {
1761 // Dynamic width from a usize argument.
1762 // SAFETY: We can assume the template only refers to arguments that exist.
1763 unsafe {
1764 opt.width = args.add(opt.width as usize).as_ref().as_u16().unwrap_unchecked();
1765 }
1766 }
1767 if n & 32 != 0 {
1768 // Dynamic precision from a usize argument.
1769 // SAFETY: We can assume the template only refers to arguments that exist.
1770 unsafe {
1771 opt.precision =
1772 args.add(opt.precision as usize).as_ref().as_u16().unwrap_unchecked();
1773 }
1774 }
1775
1776 // SAFETY: We can assume the template only refers to arguments that exist.
1777 unsafe {
1778 args.add(arg_index).as_ref().fmt(&mut Formatter::new(output, opt))?;
1779 }
1780 arg_index += 1;
1781 }
1782 }
1783}
1784
1785/// Padding after the end of something. Returned by `Formatter::padding`.
1786#[must_use = "don't forget to write the post padding"]
1787#[ferrocene::prevalidated]
1788pub(crate) struct PostPadding {
1789 fill: char,
1790 padding: u16,
1791}
1792
1793impl PostPadding {
1794 #[ferrocene::prevalidated]
1795 fn new(fill: char, padding: u16) -> PostPadding {
1796 PostPadding { fill, padding }
1797 }
1798
1799 /// Writes this post padding.
1800 #[ferrocene::prevalidated]
1801 pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result {
1802 for _ in 0..self.padding {
1803 f.buf.write_char(self.fill)?;
1804 }
1805 Ok(())
1806 }
1807}
1808
1809impl<'a> Formatter<'a> {
1810 #[ferrocene::prevalidated]
1811 fn wrap_buf<'b, 'c, F>(&'b mut self, wrap: F) -> Formatter<'c>
1812 where
1813 'b: 'c,
1814 F: FnOnce(&'b mut (dyn Write + 'b)) -> &'c mut (dyn Write + 'c),
1815 {
1816 Formatter {
1817 // We want to change this
1818 buf: wrap(self.buf),
1819
1820 // And preserve these
1821 options: self.options,
1822 }
1823 }
1824
1825 // Helper methods used for padding and processing formatting arguments that
1826 // all formatting traits can use.
1827
1828 /// Performs the correct padding for an integer which has already been
1829 /// emitted into a str. The str should *not* contain the sign for the
1830 /// integer, that will be added by this method.
1831 ///
1832 /// # Arguments
1833 ///
1834 /// * is_nonnegative - whether the original integer was either positive or zero.
1835 /// * prefix - if the '#' character (Alternate) is provided, this
1836 /// is the prefix to put in front of the number.
1837 /// * buf - the byte array that the number has been formatted into
1838 ///
1839 /// This function will correctly account for the flags provided as well as
1840 /// the minimum width. It will not take precision into account.
1841 ///
1842 /// # Examples
1843 ///
1844 /// ```
1845 /// use std::fmt;
1846 ///
1847 /// struct Foo { nb: i32 }
1848 ///
1849 /// impl Foo {
1850 /// fn new(nb: i32) -> Foo {
1851 /// Foo {
1852 /// nb,
1853 /// }
1854 /// }
1855 /// }
1856 ///
1857 /// impl fmt::Display for Foo {
1858 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1859 /// // We need to remove "-" from the number output.
1860 /// let tmp = self.nb.abs().to_string();
1861 ///
1862 /// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
1863 /// }
1864 /// }
1865 ///
1866 /// assert_eq!(format!("{}", Foo::new(2)), "2");
1867 /// assert_eq!(format!("{}", Foo::new(-1)), "-1");
1868 /// assert_eq!(format!("{}", Foo::new(0)), "0");
1869 /// assert_eq!(format!("{:#}", Foo::new(-1)), "-Foo 1");
1870 /// assert_eq!(format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
1871 /// ```
1872 #[stable(feature = "rust1", since = "1.0.0")]
1873 #[ferrocene::prevalidated]
1874 pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result {
1875 let mut width = buf.len();
1876
1877 let mut sign = None;
1878 if !is_nonnegative {
1879 sign = Some('-');
1880 width += 1;
1881 } else if self.sign_plus() {
1882 sign = Some('+');
1883 width += 1;
1884 }
1885
1886 let prefix = if self.alternate() {
1887 width += prefix.chars().count();
1888 Some(prefix)
1889 } else {
1890 None
1891 };
1892
1893 // Writes the sign if it exists, and then the prefix if it was requested
1894 #[inline(never)]
1895 #[ferrocene::prevalidated]
1896 fn write_prefix(f: &mut Formatter<'_>, sign: Option<char>, prefix: Option<&str>) -> Result {
1897 if let Some(c) = sign {
1898 f.buf.write_char(c)?;
1899 }
1900 if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) }
1901 }
1902
1903 // The `width` field is more of a `min-width` parameter at this point.
1904 let min = self.options.width;
1905 if width >= usize::from(min) {
1906 // We're over the minimum width, so then we can just write the bytes.
1907 write_prefix(self, sign, prefix)?;
1908 self.buf.write_str(buf)
1909 } else if self.sign_aware_zero_pad() {
1910 // The sign and prefix goes before the padding if the fill character
1911 // is zero
1912 let old_options = self.options;
1913 self.options.fill('0').align(Some(Alignment::Right));
1914 write_prefix(self, sign, prefix)?;
1915 let post_padding = self.padding(min - width as u16, Alignment::Right)?;
1916 self.buf.write_str(buf)?;
1917 #[cfg(feature = "ferrocene_test")]
1918 assert_eq!(post_padding.write(self), Ok(()));
1919 #[cfg(not(feature = "ferrocene_test"))]
1920 #[ferrocene::annotation(
1921 "The error `?` is not reachable, it exists only due to the trait. \
1922 Above, `self.padding(...)` is called after the alignment has been set to `Alignment::Right`. \
1923 For right alignment, `padding_left` equals `padding`, so a successful call to \
1924 `self.padding(...)` returns a `PostPadding` whose `padding` is `padding - padding_left == 0`. \
1925 Therefore `post_padding.write(self)` performs no writes and cannot return an error."
1926 )]
1927 post_padding.write(self)?;
1928 self.options = old_options;
1929 Ok(())
1930 } else {
1931 // Otherwise, the sign and prefix goes after the padding
1932 let post_padding = self.padding(min - width as u16, Alignment::Right)?;
1933 write_prefix(self, sign, prefix)?;
1934 self.buf.write_str(buf)?;
1935 post_padding.write(self)
1936 }
1937 }
1938
1939 /// Takes a string slice and emits it to the internal buffer after applying
1940 /// the relevant formatting flags specified.
1941 ///
1942 /// The flags recognized for generic strings are:
1943 ///
1944 /// * width - the minimum width of what to emit
1945 /// * fill/align - what to emit and where to emit it if the string
1946 /// provided needs to be padded
1947 /// * precision - the maximum length to emit, the string is truncated if it
1948 /// is longer than this length
1949 ///
1950 /// Notably this function ignores the `flag` parameters.
1951 ///
1952 /// # Examples
1953 ///
1954 /// ```
1955 /// use std::fmt;
1956 ///
1957 /// struct Foo;
1958 ///
1959 /// impl fmt::Display for Foo {
1960 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1961 /// formatter.pad("Foo")
1962 /// }
1963 /// }
1964 ///
1965 /// assert_eq!(format!("{Foo:<4}"), "Foo ");
1966 /// assert_eq!(format!("{Foo:0>4}"), "0Foo");
1967 /// ```
1968 #[stable(feature = "rust1", since = "1.0.0")]
1969 #[ferrocene::prevalidated]
1970 pub fn pad(&mut self, s: &str) -> Result {
1971 // Make sure there's a fast path up front.
1972 if self.options.flags & (flags::WIDTH_FLAG | flags::PRECISION_FLAG) == 0 {
1973 return self.buf.write_str(s);
1974 }
1975
1976 // The `precision` field can be interpreted as a maximum width for the
1977 // string being formatted.
1978 let (s, char_count) = if let Some(max_char_count) = self.options.get_precision() {
1979 let mut iter = s.char_indices();
1980 let remaining = match iter.advance_by(usize::from(max_char_count)) {
1981 Ok(()) => 0,
1982 Err(remaining) => remaining.get(),
1983 };
1984 // SAFETY: The offset of `.char_indices()` is guaranteed to be
1985 // in-bounds and between character boundaries.
1986 let truncated = unsafe { s.get_unchecked(..iter.offset()) };
1987 (truncated, usize::from(max_char_count) - remaining)
1988 } else {
1989 // Use the optimized char counting algorithm for the full string.
1990 (s, s.chars().count())
1991 };
1992
1993 // The `width` field is more of a minimum width parameter at this point.
1994 if char_count < usize::from(self.options.width) {
1995 // If we're under the minimum width, then fill up the minimum width
1996 // with the specified string + some alignment.
1997 let post_padding =
1998 self.padding(self.options.width - char_count as u16, Alignment::Left)?;
1999 self.buf.write_str(s)?;
2000 post_padding.write(self)
2001 } else {
2002 // If we're over the minimum width or there is no minimum width, we
2003 // can just emit the string.
2004 self.buf.write_str(s)
2005 }
2006 }
2007
2008 /// Writes the pre-padding and returns the unwritten post-padding.
2009 ///
2010 /// Callers are responsible for ensuring post-padding is written after the
2011 /// thing that is being padded.
2012 #[ferrocene::prevalidated]
2013 pub(crate) fn padding(
2014 &mut self,
2015 padding: u16,
2016 default: Alignment,
2017 ) -> result::Result<PostPadding, Error> {
2018 let align = self.options.get_align().unwrap_or(default);
2019 let fill = self.options.get_fill();
2020
2021 let padding_left = match align {
2022 Alignment::Left => 0,
2023 Alignment::Right => padding,
2024 Alignment::Center => padding / 2,
2025 };
2026
2027 for _ in 0..padding_left {
2028 self.buf.write_char(fill)?;
2029 }
2030
2031 Ok(PostPadding::new(fill, padding - padding_left))
2032 }
2033
2034 /// Takes the formatted parts and applies the padding.
2035 ///
2036 /// Assumes that the caller already has rendered the parts with required precision,
2037 /// so that `self.precision` can be ignored.
2038 ///
2039 /// # Safety
2040 ///
2041 /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
2042 #[ferrocene::prevalidated]
2043 unsafe fn pad_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
2044 if self.options.width == 0 {
2045 // this is the common case and we take a shortcut
2046 // SAFETY: Per the precondition.
2047 unsafe { self.write_formatted_parts(formatted) }
2048 } else {
2049 // for the sign-aware zero padding, we render the sign first and
2050 // behave as if we had no sign from the beginning.
2051 let mut formatted = formatted.clone();
2052 let mut width = self.options.width;
2053 let old_options = self.options;
2054 if self.sign_aware_zero_pad() {
2055 // a sign always goes first
2056 let sign = formatted.sign;
2057 self.buf.write_str(sign)?;
2058
2059 // remove the sign from the formatted parts
2060 formatted.sign = "";
2061 width = width.saturating_sub(sign.len() as u16);
2062 self.options.fill('0').align(Some(Alignment::Right));
2063 }
2064
2065 // remaining parts go through the ordinary padding process.
2066 let len = formatted.len();
2067 let ret = if usize::from(width) <= len {
2068 // no padding
2069 // SAFETY: Per the precondition.
2070 unsafe { self.write_formatted_parts(&formatted) }
2071 } else {
2072 // Padding widths are capped at `u16`, so reaching this branch means
2073 // the formatted output is also shorter than `u16::MAX`.
2074 let len = match u16::try_from(len) {
2075 Ok(len) => len,
2076 #[ferrocene::annotation(
2077 "The `Err(_)` branch is explicitly marked unreachable, causing it to be reached would be a bug"
2078 )]
2079 Err(_) => unreachable!(),
2080 };
2081 let post_padding = self.padding(width - len, Alignment::Right)?;
2082 // SAFETY: Per the precondition.
2083 unsafe {
2084 self.write_formatted_parts(&formatted)?;
2085 }
2086 post_padding.write(self)
2087 };
2088 self.options = old_options;
2089 ret
2090 }
2091 }
2092
2093 /// # Safety
2094 ///
2095 /// Any `numfmt::Part::Copy` parts in `formatted` must contain valid UTF-8.
2096 #[ferrocene::prevalidated]
2097 unsafe fn write_formatted_parts(&mut self, formatted: &numfmt::Formatted<'_>) -> Result {
2098 #[ferrocene::prevalidated]
2099 unsafe fn write_bytes(buf: &mut dyn Write, s: &[u8]) -> Result {
2100 // SAFETY: This is used for `numfmt::Part::Num` and `numfmt::Part::Copy`.
2101 // It's safe to use for `numfmt::Part::Num` since every char `c` is between
2102 // `b'0'` and `b'9'`, which means `s` is valid UTF-8. It's safe to use for
2103 // `numfmt::Part::Copy` due to this function's precondition.
2104 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
2105 }
2106
2107 if !formatted.sign.is_empty() {
2108 self.buf.write_str(formatted.sign)?;
2109 }
2110 for part in formatted.parts {
2111 match *part {
2112 numfmt::Part::Zero(mut nzeroes) => {
2113 const ZEROES: &str = // 64 zeroes
2114 "0000000000000000000000000000000000000000000000000000000000000000";
2115 while nzeroes > ZEROES.len() {
2116 self.buf.write_str(ZEROES)?;
2117 nzeroes -= ZEROES.len();
2118 }
2119 if nzeroes > 0 {
2120 self.buf.write_str(&ZEROES[..nzeroes])?;
2121 }
2122 }
2123 numfmt::Part::Num(mut v) => {
2124 let mut s = [0; 5];
2125 let len = part.len();
2126 for c in s[..len].iter_mut().rev() {
2127 *c = b'0' + (v % 10) as u8;
2128 v /= 10;
2129 }
2130 // SAFETY: Per the precondition.
2131 unsafe {
2132 write_bytes(self.buf, &s[..len])?;
2133 }
2134 }
2135 // SAFETY: Per the precondition.
2136 numfmt::Part::Copy(buf) => unsafe {
2137 write_bytes(self.buf, buf)?;
2138 },
2139 }
2140 }
2141 Ok(())
2142 }
2143
2144 /// Writes some data to the underlying buffer contained within this
2145 /// formatter.
2146 ///
2147 /// # Examples
2148 ///
2149 /// ```
2150 /// use std::fmt;
2151 ///
2152 /// struct Foo;
2153 ///
2154 /// impl fmt::Display for Foo {
2155 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2156 /// formatter.write_str("Foo")
2157 /// // This is equivalent to:
2158 /// // write!(formatter, "Foo")
2159 /// }
2160 /// }
2161 ///
2162 /// assert_eq!(format!("{Foo}"), "Foo");
2163 /// assert_eq!(format!("{Foo:0>8}"), "Foo");
2164 /// ```
2165 #[stable(feature = "rust1", since = "1.0.0")]
2166 #[ferrocene::prevalidated]
2167 pub fn write_str(&mut self, data: &str) -> Result {
2168 self.buf.write_str(data)
2169 }
2170
2171 /// Glue for usage of the [`write!`] macro with implementors of this trait.
2172 ///
2173 /// This method should generally not be invoked manually, but rather through
2174 /// the [`write!`] macro itself.
2175 ///
2176 /// Writes some formatted information into this instance.
2177 ///
2178 /// This method delegates to the underlying [`Write`] implementation, so
2179 /// whether the formatted output is appended to, or replaces, previously
2180 /// written data is up to that writer.
2181 ///
2182 /// # Examples
2183 ///
2184 /// ```
2185 /// use std::fmt;
2186 ///
2187 /// struct Foo(i32);
2188 ///
2189 /// impl fmt::Display for Foo {
2190 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2191 /// formatter.write_fmt(format_args!("Foo {}", self.0))
2192 /// }
2193 /// }
2194 ///
2195 /// assert_eq!(format!("{}", Foo(-1)), "Foo -1");
2196 /// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
2197 /// ```
2198 ///
2199 /// The same formatting code can produce different output depending on the
2200 /// underlying writer:
2201 ///
2202 /// ```
2203 /// use std::fmt;
2204 ///
2205 /// struct Hello;
2206 ///
2207 /// impl fmt::Display for Hello {
2208 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2209 /// formatter.write_fmt(format_args!("Hello"))?;
2210 /// formatter.write_fmt(format_args!(" world"))
2211 /// }
2212 /// }
2213 ///
2214 /// // A writer that replaces its contents on every write.
2215 /// struct Replace(String);
2216 ///
2217 /// impl fmt::Write for Replace {
2218 /// fn write_str(&mut self, s: &str) -> fmt::Result {
2219 /// self.0.clear();
2220 /// self.0.push_str(s);
2221 /// Ok(())
2222 /// }
2223 /// }
2224 ///
2225 /// // With `String`, which appends, both writes are kept.
2226 /// let mut s = String::new();
2227 /// fmt::write(&mut s, format_args!("{Hello}"))?;
2228 /// assert_eq!(s, "Hello world");
2229 ///
2230 /// // With a writer that replaces, the second write replaces the first.
2231 /// let mut w = Replace(String::new());
2232 /// fmt::write(&mut w, format_args!("{Hello}"))?;
2233 /// assert_eq!(w.0, " world");
2234 /// # Ok::<(), fmt::Error>(())
2235 /// ```
2236 #[stable(feature = "rust1", since = "1.0.0")]
2237 #[inline]
2238 #[ferrocene::prevalidated]
2239 pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
2240 if let Some(s) = fmt.as_statically_known_str() {
2241 self.buf.write_str(s)
2242 } else {
2243 write(self.buf, fmt)
2244 }
2245 }
2246
2247 /// Returns flags for formatting.
2248 #[must_use]
2249 #[stable(feature = "rust1", since = "1.0.0")]
2250 #[deprecated(
2251 since = "1.24.0",
2252 note = "use the `sign_plus`, `sign_minus`, `alternate`, \
2253 or `sign_aware_zero_pad` methods instead"
2254 )]
2255 #[ferrocene::prevalidated]
2256 pub fn flags(&self) -> u32 {
2257 // Extract the debug upper/lower hex, zero pad, alternate, and plus/minus flags
2258 // to stay compatible with older versions of Rust.
2259 self.options.flags >> 21 & 0x3F
2260 }
2261
2262 /// Returns the character used as 'fill' whenever there is alignment.
2263 ///
2264 /// # Examples
2265 ///
2266 /// ```
2267 /// use std::fmt;
2268 ///
2269 /// struct Foo;
2270 ///
2271 /// impl fmt::Display for Foo {
2272 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2273 /// let c = formatter.fill();
2274 /// if let Some(width) = formatter.width() {
2275 /// for _ in 0..width {
2276 /// write!(formatter, "{c}")?;
2277 /// }
2278 /// Ok(())
2279 /// } else {
2280 /// write!(formatter, "{c}")
2281 /// }
2282 /// }
2283 /// }
2284 ///
2285 /// // We set alignment to the right with ">".
2286 /// assert_eq!(format!("{Foo:G>3}"), "GGG");
2287 /// assert_eq!(format!("{Foo:t>6}"), "tttttt");
2288 /// ```
2289 #[must_use]
2290 #[stable(feature = "fmt_flags", since = "1.5.0")]
2291 #[ferrocene::prevalidated]
2292 pub fn fill(&self) -> char {
2293 self.options.get_fill()
2294 }
2295
2296 /// Returns a flag indicating what form of alignment was requested.
2297 ///
2298 /// # Examples
2299 ///
2300 /// ```
2301 /// use std::fmt::{self, Alignment};
2302 ///
2303 /// struct Foo;
2304 ///
2305 /// impl fmt::Display for Foo {
2306 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2307 /// let s = if let Some(s) = formatter.align() {
2308 /// match s {
2309 /// Alignment::Left => "left",
2310 /// Alignment::Right => "right",
2311 /// Alignment::Center => "center",
2312 /// }
2313 /// } else {
2314 /// "into the void"
2315 /// };
2316 /// write!(formatter, "{s}")
2317 /// }
2318 /// }
2319 ///
2320 /// assert_eq!(format!("{Foo:<}"), "left");
2321 /// assert_eq!(format!("{Foo:>}"), "right");
2322 /// assert_eq!(format!("{Foo:^}"), "center");
2323 /// assert_eq!(format!("{Foo}"), "into the void");
2324 /// ```
2325 #[must_use]
2326 #[stable(feature = "fmt_flags_align", since = "1.28.0")]
2327 #[ferrocene::prevalidated]
2328 pub fn align(&self) -> Option<Alignment> {
2329 self.options.get_align()
2330 }
2331
2332 /// Returns the optionally specified integer width that the output should be.
2333 ///
2334 /// # Examples
2335 ///
2336 /// ```
2337 /// use std::fmt;
2338 ///
2339 /// struct Foo(i32);
2340 ///
2341 /// impl fmt::Display for Foo {
2342 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2343 /// if let Some(width) = formatter.width() {
2344 /// // If we received a width, we use it
2345 /// write!(formatter, "{:width$}", format!("Foo({})", self.0), width = width)
2346 /// } else {
2347 /// // Otherwise we do nothing special
2348 /// write!(formatter, "Foo({})", self.0)
2349 /// }
2350 /// }
2351 /// }
2352 ///
2353 /// assert_eq!(format!("{:10}", Foo(23)), "Foo(23) ");
2354 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2355 /// ```
2356 #[must_use]
2357 #[stable(feature = "fmt_flags", since = "1.5.0")]
2358 #[ferrocene::prevalidated]
2359 pub fn width(&self) -> Option<usize> {
2360 if self.options.flags & flags::WIDTH_FLAG == 0 {
2361 None
2362 } else {
2363 Some(self.options.width as usize)
2364 }
2365 }
2366
2367 /// Returns the optionally specified precision for numeric types.
2368 /// Alternatively, the maximum width for string types.
2369 ///
2370 /// # Examples
2371 ///
2372 /// ```
2373 /// use std::fmt;
2374 ///
2375 /// struct Foo(f32);
2376 ///
2377 /// impl fmt::Display for Foo {
2378 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2379 /// if let Some(precision) = formatter.precision() {
2380 /// // If we received a precision, we use it.
2381 /// write!(formatter, "Foo({1:.*})", precision, self.0)
2382 /// } else {
2383 /// // Otherwise we default to 2.
2384 /// write!(formatter, "Foo({:.2})", self.0)
2385 /// }
2386 /// }
2387 /// }
2388 ///
2389 /// assert_eq!(format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
2390 /// assert_eq!(format!("{}", Foo(23.2)), "Foo(23.20)");
2391 /// ```
2392 #[must_use]
2393 #[stable(feature = "fmt_flags", since = "1.5.0")]
2394 #[ferrocene::prevalidated]
2395 pub fn precision(&self) -> Option<usize> {
2396 if self.options.flags & flags::PRECISION_FLAG == 0 {
2397 None
2398 } else {
2399 Some(self.options.precision as usize)
2400 }
2401 }
2402
2403 /// Determines if the `+` flag was specified.
2404 ///
2405 /// # Examples
2406 ///
2407 /// ```
2408 /// use std::fmt;
2409 ///
2410 /// struct Foo(i32);
2411 ///
2412 /// impl fmt::Display for Foo {
2413 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2414 /// if formatter.sign_plus() {
2415 /// write!(formatter,
2416 /// "Foo({}{})",
2417 /// if self.0 < 0 { '-' } else { '+' },
2418 /// self.0.abs())
2419 /// } else {
2420 /// write!(formatter, "Foo({})", self.0)
2421 /// }
2422 /// }
2423 /// }
2424 ///
2425 /// assert_eq!(format!("{:+}", Foo(23)), "Foo(+23)");
2426 /// assert_eq!(format!("{:+}", Foo(-23)), "Foo(-23)");
2427 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2428 /// ```
2429 #[must_use]
2430 #[stable(feature = "fmt_flags", since = "1.5.0")]
2431 #[ferrocene::prevalidated]
2432 pub fn sign_plus(&self) -> bool {
2433 self.options.flags & flags::SIGN_PLUS_FLAG != 0
2434 }
2435
2436 /// Determines if the `-` flag was specified.
2437 ///
2438 /// # Examples
2439 ///
2440 /// ```
2441 /// use std::fmt;
2442 ///
2443 /// struct Foo(i32);
2444 ///
2445 /// impl fmt::Display for Foo {
2446 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2447 /// if formatter.sign_minus() {
2448 /// // You want a minus sign? Have one!
2449 /// write!(formatter, "-Foo({})", self.0)
2450 /// } else {
2451 /// write!(formatter, "Foo({})", self.0)
2452 /// }
2453 /// }
2454 /// }
2455 ///
2456 /// assert_eq!(format!("{:-}", Foo(23)), "-Foo(23)");
2457 /// assert_eq!(format!("{}", Foo(23)), "Foo(23)");
2458 /// ```
2459 #[must_use]
2460 #[stable(feature = "fmt_flags", since = "1.5.0")]
2461 #[ferrocene::prevalidated]
2462 pub fn sign_minus(&self) -> bool {
2463 self.options.flags & flags::SIGN_MINUS_FLAG != 0
2464 }
2465
2466 /// Determines if the `#` flag was specified.
2467 ///
2468 /// # Examples
2469 ///
2470 /// ```
2471 /// use std::fmt;
2472 ///
2473 /// struct Foo(i32);
2474 ///
2475 /// impl fmt::Display for Foo {
2476 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2477 /// if formatter.alternate() {
2478 /// write!(formatter, "Foo({})", self.0)
2479 /// } else {
2480 /// write!(formatter, "{}", self.0)
2481 /// }
2482 /// }
2483 /// }
2484 ///
2485 /// assert_eq!(format!("{:#}", Foo(23)), "Foo(23)");
2486 /// assert_eq!(format!("{}", Foo(23)), "23");
2487 /// ```
2488 #[must_use]
2489 #[stable(feature = "fmt_flags", since = "1.5.0")]
2490 #[ferrocene::prevalidated]
2491 pub fn alternate(&self) -> bool {
2492 self.options.flags & flags::ALTERNATE_FLAG != 0
2493 }
2494
2495 /// Determines if the `0` flag was specified.
2496 ///
2497 /// # Examples
2498 ///
2499 /// ```
2500 /// use std::fmt;
2501 ///
2502 /// struct Foo(i32);
2503 ///
2504 /// impl fmt::Display for Foo {
2505 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2506 /// assert!(formatter.sign_aware_zero_pad());
2507 /// assert_eq!(formatter.width(), Some(4));
2508 /// // We ignore the formatter's options.
2509 /// write!(formatter, "{}", self.0)
2510 /// }
2511 /// }
2512 ///
2513 /// assert_eq!(format!("{:04}", Foo(23)), "23");
2514 /// ```
2515 #[must_use]
2516 #[stable(feature = "fmt_flags", since = "1.5.0")]
2517 #[ferrocene::prevalidated]
2518 pub fn sign_aware_zero_pad(&self) -> bool {
2519 self.options.flags & flags::SIGN_AWARE_ZERO_PAD_FLAG != 0
2520 }
2521
2522 // FIXME: Decide what public API we want for these two flags.
2523 // https://github.com/rust-lang/rust/issues/48584
2524 #[ferrocene::prevalidated]
2525 fn debug_lower_hex(&self) -> bool {
2526 self.options.flags & flags::DEBUG_LOWER_HEX_FLAG != 0
2527 }
2528 #[ferrocene::prevalidated]
2529 fn debug_upper_hex(&self) -> bool {
2530 self.options.flags & flags::DEBUG_UPPER_HEX_FLAG != 0
2531 }
2532
2533 /// Creates a [`DebugStruct`] builder designed to assist with creation of
2534 /// [`fmt::Debug`] implementations for structs.
2535 ///
2536 /// [`fmt::Debug`]: self::Debug
2537 ///
2538 /// # Examples
2539 ///
2540 /// ```rust
2541 /// use std::fmt;
2542 /// use std::net::Ipv4Addr;
2543 ///
2544 /// struct Foo {
2545 /// bar: i32,
2546 /// baz: String,
2547 /// addr: Ipv4Addr,
2548 /// }
2549 ///
2550 /// impl fmt::Debug for Foo {
2551 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2552 /// fmt.debug_struct("Foo")
2553 /// .field("bar", &self.bar)
2554 /// .field("baz", &self.baz)
2555 /// .field("addr", &format_args!("{}", self.addr))
2556 /// .finish()
2557 /// }
2558 /// }
2559 ///
2560 /// assert_eq!(
2561 /// "Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
2562 /// format!("{:?}", Foo {
2563 /// bar: 10,
2564 /// baz: "Hello World".to_string(),
2565 /// addr: Ipv4Addr::new(127, 0, 0, 1),
2566 /// })
2567 /// );
2568 /// ```
2569 #[stable(feature = "debug_builders", since = "1.2.0")]
2570 #[ferrocene::prevalidated]
2571 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
2572 builders::debug_struct_new(self, name)
2573 }
2574
2575 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2576 /// binaries. `debug_struct_fields_finish` is more general, but this is
2577 /// faster for 1 field.
2578 #[doc(hidden)]
2579 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2580 #[ferrocene::prevalidated]
2581 pub fn debug_struct_field1_finish<'b>(&'b mut self, names: &str, value1: &dyn Debug) -> Result {
2582 self.debug_struct_fields_finish(names, &[value1])
2583 }
2584
2585 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2586 /// binaries. `debug_struct_fields_finish` is more general, but this is
2587 /// faster for 2 fields.
2588 #[doc(hidden)]
2589 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2590 #[ferrocene::prevalidated]
2591 pub fn debug_struct_field2_finish<'b>(
2592 &'b mut self,
2593 names: &str,
2594 value1: &dyn Debug,
2595 value2: &dyn Debug,
2596 ) -> Result {
2597 self.debug_struct_fields_finish(names, &[value1, value2])
2598 }
2599
2600 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2601 /// binaries. `debug_struct_fields_finish` is more general, but this is
2602 /// faster for 3 fields.
2603 #[doc(hidden)]
2604 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2605 #[ferrocene::prevalidated]
2606 pub fn debug_struct_field3_finish<'b>(
2607 &'b mut self,
2608 names: &str,
2609 value1: &dyn Debug,
2610 value2: &dyn Debug,
2611 value3: &dyn Debug,
2612 ) -> Result {
2613 self.debug_struct_fields_finish(names, &[value1, value2, value3])
2614 }
2615
2616 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2617 /// binaries. `debug_struct_fields_finish` is more general, but this is
2618 /// faster for 4 fields.
2619 #[doc(hidden)]
2620 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2621 #[ferrocene::prevalidated]
2622 pub fn debug_struct_field4_finish<'b>(
2623 &'b mut self,
2624 names: &str,
2625 value1: &dyn Debug,
2626 value2: &dyn Debug,
2627 value3: &dyn Debug,
2628 value4: &dyn Debug,
2629 ) -> Result {
2630 self.debug_struct_fields_finish(names, &[value1, value2, value3, value4])
2631 }
2632
2633 /// Shrinks `derive(Debug)` code, for faster compilation and smaller
2634 /// binaries. `debug_struct_fields_finish` is more general, but this is
2635 /// faster for 5 fields.
2636 #[doc(hidden)]
2637 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2638 #[ferrocene::prevalidated]
2639 pub fn debug_struct_field5_finish<'b>(
2640 &'b mut self,
2641 names: &str,
2642 value1: &dyn Debug,
2643 value2: &dyn Debug,
2644 value3: &dyn Debug,
2645 value4: &dyn Debug,
2646 value5: &dyn Debug,
2647 ) -> Result {
2648 self.debug_struct_fields_finish(names, &[value1, value2, value3, value4, value5])
2649 }
2650
2651 /// Shrinks `derive(Debug)` code, for faster compilation and smaller binaries.
2652 /// For the cases not covered by `debug_struct_field[12345]_finish`.
2653 /// Field names should be separated by space.
2654 #[doc(hidden)]
2655 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2656 #[ferrocene::prevalidated]
2657 pub fn debug_struct_fields_finish<'b>(
2658 &'b mut self,
2659 names: &str,
2660 values: &[&dyn Debug],
2661 ) -> Result {
2662 // the macro generates either "Point x y" for a struct like `Point { x: u32, y: u32, }`
2663 // or just "Point" for a tuple struct like `Point(u32, u32)`. If there are no field names
2664 // (and therefore no space separator), we assume we format a tuple struct.
2665 // `.as_bytes()` is to avoid bringing in UTF-8 code bloat
2666 let is_tuple = !names.as_bytes().contains(&b' ');
2667 if is_tuple {
2668 let mut builder = builders::debug_tuple_new(self, names);
2669 for value in values {
2670 builder.field(value);
2671 }
2672 builder.finish()
2673 } else {
2674 let mut names = split_str_by_space(names);
2675 let mut builder = builders::debug_struct_new(self, names.next().unwrap());
2676 for value in values.into_iter() {
2677 let name = names.next().unwrap();
2678 builder.field(name, value);
2679 }
2680 builder.finish()
2681 }
2682 }
2683
2684 /// Shrinks `derive(Debug)` code, for faster compilation and smaller binaries.
2685 /// For C-like enums with concatenated variant name strings.
2686 /// Names should be separated by space.
2687 #[ferrocene::prevalidated]
2688 #[doc(hidden)]
2689 #[unstable(feature = "fmt_helpers_for_derive", issue = "none")]
2690 pub fn debug_c_like_enum_write_str<'b>(
2691 &'b mut self,
2692 names: &str,
2693 start_index: usize,
2694 ) -> Result {
2695 // we use `get().unwrap()` instead of indexing to avoid binary size
2696 // bloat from the error path (`slice_error_fail_rt`)
2697 self.write_str(split_str_by_space(names.get(start_index..).unwrap()).next().unwrap())
2698 }
2699
2700 /// Creates a `DebugTuple` builder designed to assist with creation of
2701 /// `fmt::Debug` implementations for tuple structs.
2702 ///
2703 /// # Examples
2704 ///
2705 /// ```rust
2706 /// use std::fmt;
2707 /// use std::marker::PhantomData;
2708 ///
2709 /// struct Foo<T>(i32, String, PhantomData<T>);
2710 ///
2711 /// impl<T> fmt::Debug for Foo<T> {
2712 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2713 /// fmt.debug_tuple("Foo")
2714 /// .field(&self.0)
2715 /// .field(&self.1)
2716 /// .field(&format_args!("_"))
2717 /// .finish()
2718 /// }
2719 /// }
2720 ///
2721 /// assert_eq!(
2722 /// "Foo(10, \"Hello\", _)",
2723 /// format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
2724 /// );
2725 /// ```
2726 #[stable(feature = "debug_builders", since = "1.2.0")]
2727 #[ferrocene::prevalidated]
2728 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
2729 builders::debug_tuple_new(self, name)
2730 }
2731
2732 /// Creates a `DebugList` builder designed to assist with creation of
2733 /// `fmt::Debug` implementations for list-like structures.
2734 ///
2735 /// # Examples
2736 ///
2737 /// ```rust
2738 /// use std::fmt;
2739 ///
2740 /// struct Foo(Vec<i32>);
2741 ///
2742 /// impl fmt::Debug for Foo {
2743 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2744 /// fmt.debug_list().entries(self.0.iter()).finish()
2745 /// }
2746 /// }
2747 ///
2748 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
2749 /// ```
2750 #[stable(feature = "debug_builders", since = "1.2.0")]
2751 #[ferrocene::prevalidated]
2752 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
2753 builders::debug_list_new(self)
2754 }
2755
2756 /// Creates a `DebugSet` builder designed to assist with creation of
2757 /// `fmt::Debug` implementations for set-like structures.
2758 ///
2759 /// # Examples
2760 ///
2761 /// ```rust
2762 /// use std::fmt;
2763 ///
2764 /// struct Foo(Vec<i32>);
2765 ///
2766 /// impl fmt::Debug for Foo {
2767 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2768 /// fmt.debug_set().entries(self.0.iter()).finish()
2769 /// }
2770 /// }
2771 ///
2772 /// assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
2773 /// ```
2774 ///
2775 /// [`format_args!`]: crate::format_args
2776 ///
2777 /// In this more complex example, we use [`format_args!`] and `.debug_set()`
2778 /// to build a list of match arms:
2779 ///
2780 /// ```rust
2781 /// use std::fmt;
2782 ///
2783 /// struct Arm<'a, L, R>(&'a (L, R));
2784 /// struct Table<'a, K, V>(&'a [(K, V)], V);
2785 ///
2786 /// impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
2787 /// where
2788 /// L: 'a + fmt::Debug, R: 'a + fmt::Debug
2789 /// {
2790 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2791 /// L::fmt(&(self.0).0, fmt)?;
2792 /// fmt.write_str(" => ")?;
2793 /// R::fmt(&(self.0).1, fmt)
2794 /// }
2795 /// }
2796 ///
2797 /// impl<'a, K, V> fmt::Debug for Table<'a, K, V>
2798 /// where
2799 /// K: 'a + fmt::Debug, V: 'a + fmt::Debug
2800 /// {
2801 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2802 /// fmt.debug_set()
2803 /// .entries(self.0.iter().map(Arm))
2804 /// .entry(&Arm(&(format_args!("_"), &self.1)))
2805 /// .finish()
2806 /// }
2807 /// }
2808 /// ```
2809 #[stable(feature = "debug_builders", since = "1.2.0")]
2810 #[ferrocene::prevalidated]
2811 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
2812 builders::debug_set_new(self)
2813 }
2814
2815 /// Creates a `DebugMap` builder designed to assist with creation of
2816 /// `fmt::Debug` implementations for map-like structures.
2817 ///
2818 /// # Examples
2819 ///
2820 /// ```rust
2821 /// use std::fmt;
2822 ///
2823 /// struct Foo(Vec<(String, i32)>);
2824 ///
2825 /// impl fmt::Debug for Foo {
2826 /// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2827 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
2828 /// }
2829 /// }
2830 ///
2831 /// assert_eq!(
2832 /// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
2833 /// r#"{"A": 10, "B": 11}"#
2834 /// );
2835 /// ```
2836 #[stable(feature = "debug_builders", since = "1.2.0")]
2837 #[ferrocene::prevalidated]
2838 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
2839 builders::debug_map_new(self)
2840 }
2841
2842 /// Returns the sign of this formatter (`+` or `-`).
2843 #[unstable(feature = "formatting_options", issue = "118117")]
2844 #[ferrocene::prevalidated]
2845 pub const fn sign(&self) -> Option<Sign> {
2846 self.options.get_sign()
2847 }
2848
2849 /// Returns the formatting options this formatter corresponds to.
2850 #[unstable(feature = "formatting_options", issue = "118117")]
2851 #[ferrocene::prevalidated]
2852 pub const fn options(&self) -> FormattingOptions {
2853 self.options
2854 }
2855}
2856
2857/// Like `.split(' ')`, but doesn't bloat binary size
2858#[ferrocene::prevalidated]
2859fn split_str_by_space(s: &str) -> impl Iterator<Item = &str> {
2860 s.as_bytes()
2861 .split(|&b| b == b' ')
2862 // SAFETY:
2863 // splitting a valid UTF-8 string on an ASCII byte results in valid UTF-8 substrings
2864 .map(|bytes| unsafe { str::from_utf8_unchecked(bytes) })
2865}
2866
2867#[stable(since = "1.2.0", feature = "formatter_write")]
2868impl Write for Formatter<'_> {
2869 #[ferrocene::prevalidated]
2870 fn write_str(&mut self, s: &str) -> Result {
2871 self.buf.write_str(s)
2872 }
2873
2874 #[ferrocene::prevalidated]
2875 fn write_char(&mut self, c: char) -> Result {
2876 self.buf.write_char(c)
2877 }
2878
2879 #[inline]
2880 #[ferrocene::prevalidated]
2881 fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2882 if let Some(s) = args.as_statically_known_str() {
2883 self.buf.write_str(s)
2884 } else {
2885 write(self.buf, args)
2886 }
2887 }
2888}
2889
2890#[stable(feature = "rust1", since = "1.0.0")]
2891impl Display for Error {
2892 #[ferrocene::prevalidated]
2893 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2894 Display::fmt("an error occurred when formatting an argument", f)
2895 }
2896}
2897
2898// Implementations of the core formatting traits
2899
2900macro_rules! fmt_refs {
2901 ($($tr:ident),*) => {
2902 $(
2903 #[stable(feature = "rust1", since = "1.0.0")]
2904 impl<T: PointeeSized + $tr> $tr for &T {
2905 #[ferrocene::prevalidated]
2906 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2907 }
2908 #[stable(feature = "rust1", since = "1.0.0")]
2909 impl<T: PointeeSized + $tr> $tr for &mut T {
2910 #[ferrocene::prevalidated]
2911 fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) }
2912 }
2913 )*
2914 }
2915}
2916
2917fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
2918
2919#[stable(feature = "never_type", since = "1.100.0")]
2920impl Debug for ! {
2921 #[inline]
2922 #[ferrocene::prevalidated]
2923 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2924 *self
2925 }
2926}
2927
2928#[stable(feature = "never_type", since = "1.100.0")]
2929impl Display for ! {
2930 #[inline]
2931 #[ferrocene::prevalidated]
2932 fn fmt(&self, _: &mut Formatter<'_>) -> Result {
2933 *self
2934 }
2935}
2936
2937#[stable(feature = "rust1", since = "1.0.0")]
2938impl Debug for bool {
2939 #[inline]
2940 #[ferrocene::prevalidated]
2941 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2942 Display::fmt(self, f)
2943 }
2944}
2945
2946#[stable(feature = "rust1", since = "1.0.0")]
2947impl Display for bool {
2948 #[ferrocene::prevalidated]
2949 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2950 Display::fmt(if *self { "true" } else { "false" }, f)
2951 }
2952}
2953
2954#[stable(feature = "rust1", since = "1.0.0")]
2955impl Debug for str {
2956 #[ferrocene::prevalidated]
2957 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2958 f.write_char('"')?;
2959
2960 // substring we know is printable
2961 let mut printable_range = 0..0;
2962
2963 #[ferrocene::prevalidated]
2964 fn needs_escape(b: u8) -> bool {
2965 b > 0x7E || b < 0x20 || b == b'\\' || b == b'"'
2966 }
2967
2968 // the loop here first skips over runs of printable ASCII as a fast path.
2969 // other chars (unicode, or ASCII that needs escaping) are then handled per-`char`.
2970 let mut rest = self;
2971 while !rest.is_empty() {
2972 let Some(non_printable_start) = rest.as_bytes().iter().position(|&b| needs_escape(b))
2973 else {
2974 printable_range.end += rest.len();
2975 break;
2976 };
2977
2978 printable_range.end += non_printable_start;
2979 // SAFETY: the position was derived from an iterator, so is known to be within bounds, and at a char boundary
2980 rest = unsafe { rest.get_unchecked(non_printable_start..) };
2981
2982 let mut chars = rest.chars();
2983 if let Some(c) = chars.next() {
2984 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
2985 escape_single_quote: false,
2986 escape_double_quote: true,
2987 });
2988 if esc.len() != 1 {
2989 f.write_str(&self[printable_range.clone()])?;
2990 Display::fmt(&esc, f)?;
2991 printable_range.start = printable_range.end + c.len_utf8();
2992 }
2993 printable_range.end += c.len_utf8();
2994 } else {
2995 #[ferrocene::annotation(
2996 "
2997 This branch is effectively unreachable as the `chars` iterator is guaranteed to
2998 have at least one element. This is because `rest` is non-empty and
2999 `non_printable_start` is guaranteed to point to a char boundary due to the
3000 definition of `needs_escape` and the fact that strings in Rust are UTF-8.
3001 "
3002 )]
3003 {}
3004 }
3005 rest = chars.as_str();
3006 }
3007
3008 f.write_str(&self[printable_range])?;
3009
3010 f.write_char('"')
3011 }
3012}
3013
3014#[stable(feature = "rust1", since = "1.0.0")]
3015impl Display for str {
3016 #[ferrocene::prevalidated]
3017 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3018 f.pad(self)
3019 }
3020}
3021
3022#[stable(feature = "rust1", since = "1.0.0")]
3023impl Debug for char {
3024 #[ferrocene::prevalidated]
3025 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3026 f.write_char('\'')?;
3027 let esc = self.escape_debug_ext(EscapeDebugExtArgs {
3028 escape_single_quote: true,
3029 escape_double_quote: false,
3030 });
3031 Display::fmt(&esc, f)?;
3032 f.write_char('\'')
3033 }
3034}
3035
3036#[stable(feature = "rust1", since = "1.0.0")]
3037impl Display for char {
3038 #[ferrocene::prevalidated]
3039 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3040 if f.options.flags & (flags::WIDTH_FLAG | flags::PRECISION_FLAG) == 0 {
3041 f.write_char(*self)
3042 } else {
3043 f.pad(self.encode_utf8(&mut [0; char::MAX_LEN_UTF8]))
3044 }
3045 }
3046}
3047
3048#[stable(feature = "rust1", since = "1.0.0")]
3049impl<T: PointeeSized> Pointer for *const T {
3050 #[ferrocene::prevalidated]
3051 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3052 // Since the formatting will be identical for all pointer types, erase the pointee type and
3053 // metadata type to reduce the amount of codegen work needed for each distinct type.
3054 let ptr: *const T = *self;
3055 let ptr_addr = ptr.expose_provenance();
3056 if <<T as core::ptr::Pointee>::Metadata as core::unit::IsUnit>::IS_UNIT {
3057 pointer_fmt_inner(ptr_addr, f)
3058 } else {
3059 wide_pointer_fmt_inner(ptr_addr, &core::ptr::metadata(ptr), f)
3060 }
3061 }
3062}
3063
3064/// Formats an address in `fmt::Pointer` style.
3065///
3066/// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for
3067/// `fn(...) -> ...` without using [problematic] "Oxford Casts".
3068///
3069/// [problematic]: https://github.com/rust-lang/rust/issues/95489
3070#[ferrocene::prevalidated]
3071pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Result {
3072 let old_options = f.options;
3073
3074 // The alternate flag is already treated by LowerHex as being special-
3075 // it denotes whether to prefix with 0x. We use it to work out whether
3076 // or not to zero extend, and then unconditionally set it to get the
3077 // prefix.
3078 if f.options.get_alternate() {
3079 f.options.sign_aware_zero_pad(true);
3080
3081 if f.options.get_width().is_none() {
3082 f.options.width(Some((usize::BITS / 4) as u16 + 2));
3083 }
3084 }
3085 f.options.alternate(true);
3086
3087 let ret = LowerHex::fmt(&ptr_addr, f);
3088
3089 f.options = old_options;
3090
3091 ret
3092}
3093
3094/// Formats a wide pointer (address and type-erased metadata) in `fmt::Pointer` style.
3095#[ferrocene::prevalidated]
3096fn wide_pointer_fmt_inner(ptr_addr: usize, metadata: &dyn Debug, f: &mut Formatter<'_>) -> Result {
3097 f.debug_struct("Pointer")
3098 .field_with("addr", move |f| pointer_fmt_inner(ptr_addr, f))
3099 .field("metadata", metadata)
3100 .finish()
3101}
3102
3103#[stable(feature = "rust1", since = "1.0.0")]
3104impl<T: PointeeSized> Pointer for *mut T {
3105 #[ferrocene::prevalidated]
3106 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3107 Pointer::fmt(&(*self as *const T), f)
3108 }
3109}
3110
3111#[stable(feature = "rust1", since = "1.0.0")]
3112impl<T: PointeeSized> Pointer for &T {
3113 #[ferrocene::prevalidated]
3114 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3115 Pointer::fmt(&(*self as *const T), f)
3116 }
3117}
3118
3119#[stable(feature = "rust1", since = "1.0.0")]
3120impl<T: PointeeSized> Pointer for &mut T {
3121 #[ferrocene::prevalidated]
3122 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3123 Pointer::fmt(&(&**self as *const T), f)
3124 }
3125}
3126
3127// Implementation of Display/Debug for various core types
3128
3129#[stable(feature = "rust1", since = "1.0.0")]
3130impl<T: PointeeSized> Debug for *const T {
3131 #[ferrocene::prevalidated]
3132 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3133 Pointer::fmt(self, f)
3134 }
3135}
3136#[stable(feature = "rust1", since = "1.0.0")]
3137impl<T: PointeeSized> Debug for *mut T {
3138 #[ferrocene::prevalidated]
3139 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3140 Pointer::fmt(self, f)
3141 }
3142}
3143
3144macro_rules! peel {
3145 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
3146}
3147
3148macro_rules! tuple {
3149 () => ();
3150 ( $($name:ident,)+ ) => (
3151 maybe_tuple_doc! {
3152 $($name)+ @
3153 #[stable(feature = "rust1", since = "1.0.0")]
3154 impl<$($name:Debug),+> Debug for ($($name,)+) {
3155 #[allow(non_snake_case, unused_assignments)]
3156 #[ferrocene::prevalidated]
3157 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3158 let mut builder = f.debug_tuple("");
3159 let ($(ref $name,)+) = *self;
3160 $(
3161 builder.field(&$name);
3162 )+
3163
3164 builder.finish()
3165 }
3166 }
3167 }
3168 peel! { $($name,)+ }
3169 )
3170}
3171
3172macro_rules! maybe_tuple_doc {
3173 ($a:ident @ #[$meta:meta] $item:item) => {
3174 #[doc(fake_variadic)]
3175 #[doc = "This trait is implemented for tuples up to twelve items long."]
3176 #[$meta]
3177 $item
3178 };
3179 ($a:ident $($rest_a:ident)+ @ #[$meta:meta] $item:item) => {
3180 #[doc(hidden)]
3181 #[$meta]
3182 $item
3183 };
3184}
3185
3186tuple! { E, D, C, B, A, Z, Y, X, W, V, U, T, }
3187
3188#[stable(feature = "rust1", since = "1.0.0")]
3189impl<T: Debug> Debug for [T] {
3190 #[ferrocene::prevalidated]
3191 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3192 f.debug_list().entries(self.iter()).finish()
3193 }
3194}
3195
3196#[stable(feature = "rust1", since = "1.0.0")]
3197impl Debug for () {
3198 #[inline]
3199 #[ferrocene::prevalidated]
3200 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3201 f.pad("()")
3202 }
3203}
3204#[stable(feature = "rust1", since = "1.0.0")]
3205impl<T: ?Sized> Debug for PhantomData<T> {
3206 #[ferrocene::prevalidated]
3207 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3208 write!(f, "PhantomData<{}>", crate::any::type_name::<T>())
3209 }
3210}
3211
3212#[stable(feature = "rust1", since = "1.0.0")]
3213impl<T: Copy + Debug> Debug for Cell<T> {
3214 #[ferrocene::prevalidated]
3215 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3216 f.debug_struct("Cell").field("value", &self.get()).finish()
3217 }
3218}
3219
3220#[stable(feature = "rust1", since = "1.0.0")]
3221impl<T: ?Sized + Debug> Debug for RefCell<T> {
3222 #[ferrocene::prevalidated]
3223 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3224 let mut d = f.debug_struct("RefCell");
3225 match self.try_borrow() {
3226 Ok(borrow) => d.field("value", &borrow),
3227 Err(_) => d.field("value", &format_args!("<borrowed>")),
3228 };
3229 d.finish()
3230 }
3231}
3232
3233#[stable(feature = "rust1", since = "1.0.0")]
3234impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
3235 #[ferrocene::prevalidated]
3236 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3237 Debug::fmt(&**self, f)
3238 }
3239}
3240
3241#[stable(feature = "rust1", since = "1.0.0")]
3242impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
3243 #[ferrocene::prevalidated]
3244 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3245 Debug::fmt(self.deref(), f)
3246 }
3247}
3248
3249#[stable(feature = "core_impl_debug", since = "1.9.0")]
3250impl<T: ?Sized> Debug for UnsafeCell<T> {
3251 #[ferrocene::prevalidated]
3252 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3253 f.debug_struct("UnsafeCell").finish_non_exhaustive()
3254 }
3255}
3256
3257#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
3258impl<T: ?Sized> Debug for SyncUnsafeCell<T> {
3259 #[ferrocene::prevalidated]
3260 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
3261 f.debug_struct("SyncUnsafeCell").finish_non_exhaustive()
3262 }
3263}
3264
3265// If you expected tests to be here, look instead at coretests/tests/fmt/;
3266// it's a lot easier than creating all of the rt::Piece structures here.
3267// There are also tests in alloctests/tests/fmt.rs, for those that need allocations.
3268
3269/// Ferrocene addition: Hidden module to test crate-internal functionality
3270#[doc(hidden)]
3271#[unstable(feature = "ferrocene_test", issue = "none")]
3272pub mod ferrocene_test;