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