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