]> git.proxmox.com Git - rustc.git/blame - src/libcore/fmt/mod.rs
New upstream version 1.16.0+dfsg1
[rustc.git] / src / libcore / fmt / mod.rs
CommitLineData
9346a6ac 1// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
1a4d82fc
JJ
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
54a0048b 11//! Utilities for formatting and printing strings.
1a4d82fc 12
85aaf69f 13#![stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 14
476ff2be 15use cell::{UnsafeCell, Cell, RefCell, Ref, RefMut};
9346a6ac 16use marker::PhantomData;
1a4d82fc 17use mem;
d9579d0f 18use num::flt2dec;
9346a6ac 19use ops::Deref;
1a4d82fc 20use result;
1a4d82fc 21use slice;
9346a6ac 22use str;
54a0048b
SL
23
24#[unstable(feature = "fmt_flags_align", issue = "27726")]
25/// Possible alignments returned by `Formatter::align`
26#[derive(Debug)]
27pub enum Alignment {
28 /// Indication that contents should be left-aligned.
29 Left,
30 /// Indication that contents should be right-aligned.
31 Right,
32 /// Indication that contents should be center-aligned.
33 Center,
34 /// No alignment was requested.
35 Unknown,
36}
37
92a42be0 38#[stable(feature = "debug_builders", since = "1.2.0")]
c34b1796
AL
39pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
40
1a4d82fc 41mod num;
c34b1796 42mod builders;
1a4d82fc 43
e9174d1e
SL
44#[unstable(feature = "fmt_internals", reason = "internal to format_args!",
45 issue = "0")]
85aaf69f
SL
46#[doc(hidden)]
47pub mod rt {
48 pub mod v1;
49}
50
51#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
52/// The type returned by formatter methods.
53pub type Result = result::Result<(), Error>;
54
55/// The error type which is returned from formatting a message into a stream.
56///
57/// This type does not support transmission of an error other than that an error
58/// occurred. Any extra information must be arranged to be transmitted through
59/// some other means.
85aaf69f 60#[stable(feature = "rust1", since = "1.0.0")]
a7813a04 61#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
1a4d82fc
JJ
62pub struct Error;
63
64/// A collection of methods that are required to format a message into a stream.
65///
66/// This trait is the type which this modules requires when formatting
85aaf69f 67/// information. This is similar to the standard library's `io::Write` trait,
1a4d82fc
JJ
68/// but it is only intended for use in libcore.
69///
70/// This trait should generally not be implemented by consumers of the standard
85aaf69f
SL
71/// library. The `write!` macro accepts an instance of `io::Write`, and the
72/// `io::Write` trait is favored over implementing this trait.
73#[stable(feature = "rust1", since = "1.0.0")]
74pub trait Write {
1a4d82fc
JJ
75 /// Writes a slice of bytes into this writer, returning whether the write
76 /// succeeded.
77 ///
78 /// This method can only succeed if the entire byte slice was successfully
79 /// written, and this method will not return until all data has been
80 /// written or an error occurs.
81 ///
82 /// # Errors
83 ///
62682a34 84 /// This function will return an instance of `Error` on error.
85aaf69f 85 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
86 fn write_str(&mut self, s: &str) -> Result;
87
d9579d0f
AL
88 /// Writes a `char` into this writer, returning whether the write succeeded.
89 ///
90 /// A single `char` may be encoded as more than one byte.
91 /// This method can only succeed if the entire byte sequence was successfully
92 /// written, and this method will not return until all data has been
93 /// written or an error occurs.
94 ///
95 /// # Errors
96 ///
62682a34 97 /// This function will return an instance of `Error` on error.
d9579d0f
AL
98 #[stable(feature = "fmt_write_char", since = "1.1.0")]
99 fn write_char(&mut self, c: char) -> Result {
c30ab7b3 100 self.write_str(c.encode_utf8(&mut [0; 4]))
d9579d0f
AL
101 }
102
b039eaaf 103 /// Glue for usage of the `write!` macro with implementors of this trait.
1a4d82fc
JJ
104 ///
105 /// This method should generally not be invoked manually, but rather through
106 /// the `write!` macro itself.
85aaf69f 107 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
108 fn write_fmt(&mut self, args: Arguments) -> Result {
109 // This Adapter is needed to allow `self` (of type `&mut
85aaf69f 110 // Self`) to be cast to a Write (below) without
1a4d82fc
JJ
111 // requiring a `Sized` bound.
112 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
113
85aaf69f
SL
114 impl<'a, T: ?Sized> Write for Adapter<'a, T>
115 where T: Write
1a4d82fc
JJ
116 {
117 fn write_str(&mut self, s: &str) -> Result {
118 self.0.write_str(s)
119 }
120
7453a54e
SL
121 fn write_char(&mut self, c: char) -> Result {
122 self.0.write_char(c)
123 }
124
1a4d82fc
JJ
125 fn write_fmt(&mut self, args: Arguments) -> Result {
126 self.0.write_fmt(args)
127 }
128 }
129
130 write(&mut Adapter(self), args)
131 }
132}
133
e9174d1e
SL
134#[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
135impl<'a, W: Write + ?Sized> Write for &'a mut W {
136 fn write_str(&mut self, s: &str) -> Result {
137 (**self).write_str(s)
138 }
139
140 fn write_char(&mut self, c: char) -> Result {
141 (**self).write_char(c)
142 }
143
144 fn write_fmt(&mut self, args: Arguments) -> Result {
145 (**self).write_fmt(args)
146 }
147}
148
1a4d82fc
JJ
149/// A struct to represent both where to emit formatting strings to and how they
150/// should be formatted. A mutable version of this is passed to all formatting
151/// traits.
54a0048b 152#[allow(missing_debug_implementations)]
85aaf69f 153#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 154pub struct Formatter<'a> {
c34b1796 155 flags: u32,
1a4d82fc 156 fill: char,
85aaf69f 157 align: rt::v1::Alignment,
c34b1796
AL
158 width: Option<usize>,
159 precision: Option<usize>,
1a4d82fc 160
85aaf69f
SL
161 buf: &'a mut (Write+'a),
162 curarg: slice::Iter<'a, ArgumentV1<'a>>,
163 args: &'a [ArgumentV1<'a>],
1a4d82fc
JJ
164}
165
166// NB. Argument is essentially an optimized partially applied formatting function,
167// equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
168
476ff2be
SL
169struct Void {
170 _priv: (),
171}
1a4d82fc
JJ
172
173/// This struct represents the generic "argument" which is taken by the Xprintf
174/// family of functions. It contains a function to format the given value. At
175/// compile time it is ensured that the function and the value have the correct
176/// types, and then this struct is used to canonicalize arguments to one type.
1a4d82fc 177#[derive(Copy)]
54a0048b 178#[allow(missing_debug_implementations)]
e9174d1e
SL
179#[unstable(feature = "fmt_internals", reason = "internal to format_args!",
180 issue = "0")]
85aaf69f
SL
181#[doc(hidden)]
182pub struct ArgumentV1<'a> {
1a4d82fc
JJ
183 value: &'a Void,
184 formatter: fn(&Void, &mut Formatter) -> Result,
185}
186
92a42be0
SL
187#[unstable(feature = "fmt_internals", reason = "internal to format_args!",
188 issue = "0")]
c34b1796
AL
189impl<'a> Clone for ArgumentV1<'a> {
190 fn clone(&self) -> ArgumentV1<'a> {
191 *self
192 }
193}
194
85aaf69f 195impl<'a> ArgumentV1<'a> {
1a4d82fc 196 #[inline(never)]
c34b1796 197 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
85aaf69f 198 Display::fmt(x, f)
1a4d82fc
JJ
199 }
200
85aaf69f 201 #[doc(hidden)]
e9174d1e
SL
202 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
203 issue = "0")]
85aaf69f
SL
204 pub fn new<'b, T>(x: &'b T,
205 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
1a4d82fc 206 unsafe {
85aaf69f 207 ArgumentV1 {
1a4d82fc
JJ
208 formatter: mem::transmute(f),
209 value: mem::transmute(x)
210 }
211 }
212 }
213
85aaf69f 214 #[doc(hidden)]
e9174d1e
SL
215 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
216 issue = "0")]
c34b1796
AL
217 pub fn from_usize(x: &usize) -> ArgumentV1 {
218 ArgumentV1::new(x, ArgumentV1::show_usize)
1a4d82fc
JJ
219 }
220
c34b1796
AL
221 fn as_usize(&self) -> Option<usize> {
222 if self.formatter as usize == ArgumentV1::show_usize as usize {
223 Some(unsafe { *(self.value as *const _ as *const usize) })
1a4d82fc
JJ
224 } else {
225 None
226 }
227 }
228}
229
85aaf69f 230// flags available in the v1 format of format_args
c34b1796 231#[derive(Copy, Clone)]
85aaf69f
SL
232#[allow(dead_code)] // SignMinus isn't currently used
233enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
234
1a4d82fc
JJ
235impl<'a> Arguments<'a> {
236 /// When using the format_args!() macro, this function is used to generate the
237 /// Arguments structure.
238 #[doc(hidden)] #[inline]
e9174d1e
SL
239 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
240 issue = "0")]
85aaf69f
SL
241 pub fn new_v1(pieces: &'a [&'a str],
242 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
1a4d82fc
JJ
243 Arguments {
244 pieces: pieces,
245 fmt: None,
246 args: args
247 }
248 }
249
250 /// This function is used to specify nonstandard formatting parameters.
251 /// The `pieces` array must be at least as long as `fmt` to construct
252 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
253 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
c34b1796 254 /// created with `argumentusize`. However, failing to do so doesn't cause
1a4d82fc
JJ
255 /// unsafety, but will ignore invalid .
256 #[doc(hidden)] #[inline]
e9174d1e
SL
257 #[unstable(feature = "fmt_internals", reason = "internal to format_args!",
258 issue = "0")]
85aaf69f
SL
259 pub fn new_v1_formatted(pieces: &'a [&'a str],
260 args: &'a [ArgumentV1<'a>],
261 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
1a4d82fc
JJ
262 Arguments {
263 pieces: pieces,
264 fmt: Some(fmt),
265 args: args
266 }
267 }
268}
269
270/// This structure represents a safely precompiled version of a format string
271/// and its arguments. This cannot be generated at runtime because it cannot
272/// safely be done so, so no constructors are given and the fields are private
273/// to prevent modification.
274///
9e0c209e 275/// The [`format_args!`] macro will safely create an instance of this structure
1a4d82fc 276/// and pass it to a function or closure, passed as the first argument. The
9e0c209e
SL
277/// macro validates the format string at compile-time so usage of the [`write`]
278/// and [`format`] functions can be safely performed.
279///
280/// [`format_args!`]: ../../std/macro.format_args.html
281/// [`format`]: ../../std/fmt/fn.format.html
282/// [`write`]: ../../std/fmt/fn.write.html
85aaf69f 283#[stable(feature = "rust1", since = "1.0.0")]
c34b1796 284#[derive(Copy, Clone)]
1a4d82fc
JJ
285pub struct Arguments<'a> {
286 // Format string pieces to print.
287 pieces: &'a [&'a str],
288
289 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
85aaf69f 290 fmt: Option<&'a [rt::v1::Argument]>,
1a4d82fc
JJ
291
292 // Dynamic arguments for interpolation, to be interleaved with string
293 // pieces. (Every argument is preceded by a string piece.)
85aaf69f 294 args: &'a [ArgumentV1<'a>],
1a4d82fc
JJ
295}
296
85aaf69f
SL
297#[stable(feature = "rust1", since = "1.0.0")]
298impl<'a> Debug for Arguments<'a> {
1a4d82fc 299 fn fmt(&self, fmt: &mut Formatter) -> Result {
85aaf69f 300 Display::fmt(self, fmt)
1a4d82fc
JJ
301 }
302}
303
85aaf69f
SL
304#[stable(feature = "rust1", since = "1.0.0")]
305impl<'a> Display for Arguments<'a> {
1a4d82fc
JJ
306 fn fmt(&self, fmt: &mut Formatter) -> Result {
307 write(fmt.buf, *self)
308 }
309}
310
c1a9b12d
SL
311/// Format trait for the `?` character.
312///
313/// `Debug` should format the output in a programmer-facing, debugging context.
62682a34
SL
314///
315/// Generally speaking, you should just `derive` a `Debug` implementation.
316///
c1a9b12d
SL
317/// When used with the alternate format specifier `#?`, the output is pretty-printed.
318///
319/// For more information on formatters, see [the module-level documentation][module].
320///
b039eaaf 321/// [module]: ../../std/fmt/index.html
c1a9b12d 322///
3157f602
XL
323/// This trait can be used with `#[derive]` if all fields implement `Debug`. When
324/// `derive`d for structs, it will use the name of the `struct`, then `{`, then a
325/// comma-separated list of each field's name and `Debug` value, then `}`. For
326/// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
327/// `Debug` values of the fields, then `)`.
92a42be0 328///
62682a34
SL
329/// # Examples
330///
331/// Deriving an implementation:
332///
333/// ```
334/// #[derive(Debug)]
335/// struct Point {
336/// x: i32,
337/// y: i32,
338/// }
339///
340/// let origin = Point { x: 0, y: 0 };
341///
342/// println!("The origin is: {:?}", origin);
343/// ```
344///
345/// Manually implementing:
346///
347/// ```
348/// use std::fmt;
349///
350/// struct Point {
351/// x: i32,
352/// y: i32,
353/// }
354///
355/// impl fmt::Debug for Point {
356/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92a42be0 357/// write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
62682a34
SL
358/// }
359/// }
360///
361/// let origin = Point { x: 0, y: 0 };
362///
363/// println!("The origin is: {:?}", origin);
364/// ```
365///
c1a9b12d
SL
366/// This outputs:
367///
368/// ```text
369/// The origin is: Point { x: 0, y: 0 }
370/// ```
371///
62682a34
SL
372/// There are a number of `debug_*` methods on `Formatter` to help you with manual
373/// implementations, such as [`debug_struct`][debug_struct].
374///
c1a9b12d
SL
375/// `Debug` implementations using either `derive` or the debug builder API
376/// on `Formatter` support pretty printing using the alternate flag: `{:#?}`.
377///
9cc50fc6 378/// [debug_struct]: ../../std/fmt/struct.Formatter.html#method.debug_struct
c1a9b12d
SL
379///
380/// Pretty printing with `#?`:
381///
382/// ```
383/// #[derive(Debug)]
384/// struct Point {
385/// x: i32,
386/// y: i32,
387/// }
388///
389/// let origin = Point { x: 0, y: 0 };
390///
391/// println!("The origin is: {:#?}", origin);
392/// ```
393///
394/// This outputs:
395///
396/// ```text
397/// The origin is: Point {
398/// x: 0,
399/// y: 0
400/// }
401/// ```
85aaf69f
SL
402#[stable(feature = "rust1", since = "1.0.0")]
403#[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
404 defined in your crate, add `#[derive(Debug)]` or \
405 manually implement it"]
406#[lang = "debug_trait"]
407pub trait Debug {
408 /// Formats the value using the given formatter.
409 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
410 fn fmt(&self, &mut Formatter) -> Result;
411}
412
c1a9b12d
SL
413/// Format trait for an empty format, `{}`.
414///
415/// `Display` is similar to [`Debug`][debug], but `Display` is for user-facing
416/// output, and so cannot be derived.
417///
418/// [debug]: trait.Debug.html
419///
420/// For more information on formatters, see [the module-level documentation][module].
421///
b039eaaf 422/// [module]: ../../std/fmt/index.html
c1a9b12d
SL
423///
424/// # Examples
425///
426/// Implementing `Display` on a type:
427///
428/// ```
429/// use std::fmt;
430///
431/// struct Point {
432/// x: i32,
433/// y: i32,
434/// }
435///
436/// impl fmt::Display for Point {
437/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
438/// write!(f, "({}, {})", self.x, self.y)
439/// }
440/// }
441///
442/// let origin = Point { x: 0, y: 0 };
443///
444/// println!("The origin is: {}", origin);
445/// ```
85aaf69f
SL
446#[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
447 formatter; try using `:?` instead if you are using \
448 a format string"]
449#[stable(feature = "rust1", since = "1.0.0")]
450pub trait Display {
451 /// Formats the value using the given formatter.
452 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
453 fn fmt(&self, &mut Formatter) -> Result;
454}
455
c1a9b12d
SL
456/// Format trait for the `o` character.
457///
458/// The `Octal` trait should format its output as a number in base-8.
459///
460/// The alternate flag, `#`, adds a `0o` in front of the output.
461///
462/// For more information on formatters, see [the module-level documentation][module].
463///
b039eaaf 464/// [module]: ../../std/fmt/index.html
c1a9b12d
SL
465///
466/// # Examples
467///
468/// Basic usage with `i32`:
469///
470/// ```
471/// let x = 42; // 42 is '52' in octal
472///
473/// assert_eq!(format!("{:o}", x), "52");
474/// assert_eq!(format!("{:#o}", x), "0o52");
475/// ```
476///
477/// Implementing `Octal` on a type:
478///
479/// ```
480/// use std::fmt;
481///
482/// struct Length(i32);
483///
484/// impl fmt::Octal for Length {
485/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
486/// let val = self.0;
487///
488/// write!(f, "{:o}", val) // delegate to i32's implementation
489/// }
490/// }
491///
492/// let l = Length(9);
493///
494/// println!("l as octal is: {:o}", l);
495/// ```
85aaf69f 496#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
497pub trait Octal {
498 /// Formats the value using the given formatter.
85aaf69f 499 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
500 fn fmt(&self, &mut Formatter) -> Result;
501}
502
c1a9b12d
SL
503/// Format trait for the `b` character.
504///
505/// The `Binary` trait should format its output as a number in binary.
506///
507/// The alternate flag, `#`, adds a `0b` in front of the output.
508///
509/// For more information on formatters, see [the module-level documentation][module].
510///
b039eaaf 511/// [module]: ../../std/fmt/index.html
c1a9b12d
SL
512///
513/// # Examples
514///
515/// Basic usage with `i32`:
516///
517/// ```
518/// let x = 42; // 42 is '101010' in binary
519///
520/// assert_eq!(format!("{:b}", x), "101010");
521/// assert_eq!(format!("{:#b}", x), "0b101010");
522/// ```
523///
524/// Implementing `Binary` on a type:
525///
526/// ```
527/// use std::fmt;
528///
529/// struct Length(i32);
530///
531/// impl fmt::Binary for Length {
532/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
533/// let val = self.0;
534///
535/// write!(f, "{:b}", val) // delegate to i32's implementation
536/// }
537/// }
538///
539/// let l = Length(107);
540///
541/// println!("l as binary is: {:b}", l);
542/// ```
85aaf69f 543#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
544pub trait Binary {
545 /// Formats the value using the given formatter.
85aaf69f 546 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
547 fn fmt(&self, &mut Formatter) -> Result;
548}
549
c1a9b12d
SL
550/// Format trait for the `x` character.
551///
b039eaaf 552/// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
c1a9b12d
SL
553/// in lower case.
554///
555/// The alternate flag, `#`, adds a `0x` in front of the output.
556///
557/// For more information on formatters, see [the module-level documentation][module].
558///
b039eaaf 559/// [module]: ../../std/fmt/index.html
c1a9b12d
SL
560///
561/// # Examples
562///
563/// Basic usage with `i32`:
564///
565/// ```
566/// let x = 42; // 42 is '2a' in hex
567///
568/// assert_eq!(format!("{:x}", x), "2a");
569/// assert_eq!(format!("{:#x}", x), "0x2a");
570/// ```
571///
572/// Implementing `LowerHex` on a type:
573///
574/// ```
575/// use std::fmt;
576///
577/// struct Length(i32);
578///
579/// impl fmt::LowerHex for Length {
580/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
581/// let val = self.0;
582///
583/// write!(f, "{:x}", val) // delegate to i32's implementation
584/// }
585/// }
586///
587/// let l = Length(9);
588///
589/// println!("l as hex is: {:x}", l);
590/// ```
85aaf69f 591#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
592pub trait LowerHex {
593 /// Formats the value using the given formatter.
85aaf69f 594 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
595 fn fmt(&self, &mut Formatter) -> Result;
596}
597
c1a9b12d
SL
598/// Format trait for the `X` character.
599///
b039eaaf 600/// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
c1a9b12d
SL
601/// in upper case.
602///
603/// The alternate flag, `#`, adds a `0x` in front of the output.
604///
605/// For more information on formatters, see [the module-level documentation][module].
606///
b039eaaf 607/// [module]: ../../std/fmt/index.html
c1a9b12d
SL
608///
609/// # Examples
610///
611/// Basic usage with `i32`:
612///
613/// ```
614/// let x = 42; // 42 is '2A' in hex
615///
616/// assert_eq!(format!("{:X}", x), "2A");
617/// assert_eq!(format!("{:#X}", x), "0x2A");
618/// ```
619///
620/// Implementing `UpperHex` on a type:
621///
622/// ```
623/// use std::fmt;
624///
625/// struct Length(i32);
626///
627/// impl fmt::UpperHex for Length {
628/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
629/// let val = self.0;
630///
631/// write!(f, "{:X}", val) // delegate to i32's implementation
632/// }
633/// }
634///
635/// let l = Length(9);
636///
637/// println!("l as hex is: {:X}", l);
638/// ```
85aaf69f 639#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
640pub trait UpperHex {
641 /// Formats the value using the given formatter.
85aaf69f 642 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
643 fn fmt(&self, &mut Formatter) -> Result;
644}
645
c1a9b12d
SL
646/// Format trait for the `p` character.
647///
648/// The `Pointer` trait should format its output as a memory location. This is commonly presented
b039eaaf 649/// as hexadecimal.
c1a9b12d
SL
650///
651/// For more information on formatters, see [the module-level documentation][module].
652///
b039eaaf 653/// [module]: ../../std/fmt/index.html
c1a9b12d
SL
654///
655/// # Examples
656///
657/// Basic usage with `&i32`:
658///
659/// ```
660/// let x = &42;
661///
662/// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
663/// ```
664///
665/// Implementing `Pointer` on a type:
666///
667/// ```
668/// use std::fmt;
669///
670/// struct Length(i32);
671///
672/// impl fmt::Pointer for Length {
673/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
674/// // use `as` to convert to a `*const T`, which implements Pointer, which we can use
675///
676/// write!(f, "{:p}", self as *const Length)
677/// }
678/// }
679///
680/// let l = Length(42);
681///
682/// println!("l is in memory here: {:p}", l);
683/// ```
85aaf69f 684#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
685pub trait Pointer {
686 /// Formats the value using the given formatter.
85aaf69f 687 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
688 fn fmt(&self, &mut Formatter) -> Result;
689}
690
c1a9b12d
SL
691/// Format trait for the `e` character.
692///
693/// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
694///
695/// For more information on formatters, see [the module-level documentation][module].
696///
b039eaaf 697/// [module]: ../../std/fmt/index.html
c1a9b12d
SL
698///
699/// # Examples
700///
701/// Basic usage with `i32`:
702///
703/// ```
704/// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
705///
706/// assert_eq!(format!("{:e}", x), "4.2e1");
707/// ```
708///
709/// Implementing `LowerExp` on a type:
710///
711/// ```
712/// use std::fmt;
713///
714/// struct Length(i32);
715///
716/// impl fmt::LowerExp for Length {
717/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
718/// let val = self.0;
719/// write!(f, "{}e1", val / 10)
720/// }
721/// }
722///
723/// let l = Length(100);
724///
725/// println!("l in scientific notation is: {:e}", l);
726/// ```
85aaf69f 727#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
728pub trait LowerExp {
729 /// Formats the value using the given formatter.
85aaf69f 730 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
731 fn fmt(&self, &mut Formatter) -> Result;
732}
733
c1a9b12d
SL
734/// Format trait for the `E` character.
735///
736/// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
737///
738/// For more information on formatters, see [the module-level documentation][module].
739///
b039eaaf 740/// [module]: ../../std/fmt/index.html
c1a9b12d
SL
741///
742/// # Examples
743///
744/// Basic usage with `f32`:
745///
746/// ```
747/// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
748///
749/// assert_eq!(format!("{:E}", x), "4.2E1");
750/// ```
751///
752/// Implementing `UpperExp` on a type:
753///
754/// ```
755/// use std::fmt;
756///
757/// struct Length(i32);
758///
759/// impl fmt::UpperExp for Length {
760/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
761/// let val = self.0;
762/// write!(f, "{}E1", val / 10)
763/// }
764/// }
765///
766/// let l = Length(100);
767///
768/// println!("l in scientific notation is: {:E}", l);
769/// ```
85aaf69f 770#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
771pub trait UpperExp {
772 /// Formats the value using the given formatter.
85aaf69f 773 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
774 fn fmt(&self, &mut Formatter) -> Result;
775}
776
777/// The `write` function takes an output stream, a precompiled format string,
778/// and a list of arguments. The arguments will be formatted according to the
779/// specified format string into the output stream provided.
780///
781/// # Arguments
782///
783/// * output - the buffer to write output to
784/// * args - the precompiled arguments generated by `format_args!`
a7813a04
XL
785///
786/// # Examples
787///
788/// Basic usage:
789///
790/// ```
791/// use std::fmt;
792///
793/// let mut output = String::new();
794/// fmt::write(&mut output, format_args!("Hello {}!", "world"))
795/// .expect("Error occurred while trying to write in String");
796/// assert_eq!(output, "Hello world!");
797/// ```
798///
c30ab7b3 799/// Please note that using [`write!`] might be preferrable. Example:
a7813a04
XL
800///
801/// ```
802/// use std::fmt::Write;
803///
804/// let mut output = String::new();
805/// write!(&mut output, "Hello {}!", "world")
806/// .expect("Error occurred while trying to write in String");
807/// assert_eq!(output, "Hello world!");
808/// ```
809///
c30ab7b3 810/// [`write!`]: ../../std/macro.write.html
85aaf69f
SL
811#[stable(feature = "rust1", since = "1.0.0")]
812pub fn write(output: &mut Write, args: Arguments) -> Result {
1a4d82fc
JJ
813 let mut formatter = Formatter {
814 flags: 0,
815 width: None,
816 precision: None,
817 buf: output,
54a0048b 818 align: rt::v1::Alignment::Unknown,
1a4d82fc
JJ
819 fill: ' ',
820 args: args.args,
821 curarg: args.args.iter(),
822 };
823
824 let mut pieces = args.pieces.iter();
825
826 match args.fmt {
827 None => {
828 // We can use default formatting parameters for all arguments.
829 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
54a0048b
SL
830 formatter.buf.write_str(*piece)?;
831 (arg.formatter)(arg.value, &mut formatter)?;
1a4d82fc
JJ
832 }
833 }
834 Some(fmt) => {
835 // Every spec has a corresponding argument that is preceded by
836 // a string piece.
837 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
54a0048b
SL
838 formatter.buf.write_str(*piece)?;
839 formatter.run(arg)?;
1a4d82fc
JJ
840 }
841 }
842 }
843
844 // There can be only one trailing string piece left.
3157f602
XL
845 if let Some(piece) = pieces.next() {
846 formatter.buf.write_str(*piece)?;
1a4d82fc
JJ
847 }
848
849 Ok(())
850}
851
852impl<'a> Formatter<'a> {
853
854 // First up is the collection of functions used to execute a format string
855 // at runtime. This consumes all of the compile-time statics generated by
856 // the format! syntax extension.
85aaf69f 857 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
1a4d82fc
JJ
858 // Fill in the format parameters into the formatter
859 self.fill = arg.format.fill;
860 self.align = arg.format.align;
861 self.flags = arg.format.flags;
862 self.width = self.getcount(&arg.format.width);
863 self.precision = self.getcount(&arg.format.precision);
864
865 // Extract the correct argument
866 let value = match arg.position {
85aaf69f
SL
867 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
868 rt::v1::Position::At(i) => self.args[i],
1a4d82fc
JJ
869 };
870
871 // Then actually do some printing
872 (value.formatter)(value.value, self)
873 }
874
c34b1796 875 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
1a4d82fc 876 match *cnt {
85aaf69f
SL
877 rt::v1::Count::Is(n) => Some(n),
878 rt::v1::Count::Implied => None,
879 rt::v1::Count::Param(i) => {
c34b1796 880 self.args[i].as_usize()
1a4d82fc 881 }
85aaf69f 882 rt::v1::Count::NextParam => {
c34b1796 883 self.curarg.next().and_then(|arg| arg.as_usize())
1a4d82fc
JJ
884 }
885 }
886 }
887
888 // Helper methods used for padding and processing formatting arguments that
889 // all formatting traits can use.
890
891 /// Performs the correct padding for an integer which has already been
85aaf69f
SL
892 /// emitted into a str. The str should *not* contain the sign for the
893 /// integer, that will be added by this method.
1a4d82fc
JJ
894 ///
895 /// # Arguments
896 ///
9cc50fc6 897 /// * is_nonnegative - whether the original integer was either positive or zero.
c34b1796 898 /// * prefix - if the '#' character (Alternate) is provided, this
1a4d82fc
JJ
899 /// is the prefix to put in front of the number.
900 /// * buf - the byte array that the number has been formatted into
901 ///
902 /// This function will correctly account for the flags provided as well as
903 /// the minimum width. It will not take precision into account.
85aaf69f 904 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 905 pub fn pad_integral(&mut self,
9cc50fc6 906 is_nonnegative: bool,
1a4d82fc
JJ
907 prefix: &str,
908 buf: &str)
909 -> Result {
1a4d82fc
JJ
910 let mut width = buf.len();
911
912 let mut sign = None;
9cc50fc6 913 if !is_nonnegative {
1a4d82fc 914 sign = Some('-'); width += 1;
b039eaaf 915 } else if self.sign_plus() {
1a4d82fc
JJ
916 sign = Some('+'); width += 1;
917 }
918
919 let mut prefixed = false;
b039eaaf 920 if self.alternate() {
92a42be0 921 prefixed = true; width += prefix.chars().count();
1a4d82fc
JJ
922 }
923
924 // Writes the sign if it exists, and then the prefix if it was requested
85aaf69f
SL
925 let write_prefix = |f: &mut Formatter| {
926 if let Some(c) = sign {
c30ab7b3 927 f.buf.write_str(c.encode_utf8(&mut [0; 4]))?;
1a4d82fc
JJ
928 }
929 if prefixed { f.buf.write_str(prefix) }
930 else { Ok(()) }
931 };
932
933 // The `width` field is more of a `min-width` parameter at this point.
934 match self.width {
935 // If there's no minimum length requirements then we can just
936 // write the bytes.
937 None => {
54a0048b 938 write_prefix(self)?; self.buf.write_str(buf)
1a4d82fc
JJ
939 }
940 // Check if we're over the minimum width, if so then we can also
941 // just write the bytes.
942 Some(min) if width >= min => {
54a0048b 943 write_prefix(self)?; self.buf.write_str(buf)
1a4d82fc
JJ
944 }
945 // The sign and prefix goes before the padding if the fill character
946 // is zero
b039eaaf 947 Some(min) if self.sign_aware_zero_pad() => {
1a4d82fc 948 self.fill = '0';
54a0048b
SL
949 write_prefix(self)?;
950 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1a4d82fc
JJ
951 f.buf.write_str(buf)
952 })
953 }
954 // Otherwise, the sign and prefix goes after the padding
955 Some(min) => {
54a0048b
SL
956 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
957 write_prefix(f)?; f.buf.write_str(buf)
1a4d82fc
JJ
958 })
959 }
960 }
961 }
962
963 /// This function takes a string slice and emits it to the internal buffer
964 /// after applying the relevant formatting flags specified. The flags
965 /// recognized for generic strings are:
966 ///
967 /// * width - the minimum width of what to emit
968 /// * fill/align - what to emit and where to emit it if the string
969 /// provided needs to be padded
970 /// * precision - the maximum length to emit, the string is truncated if it
971 /// is longer than this length
972 ///
973 /// Notably this function ignored the `flag` parameters
85aaf69f 974 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
975 pub fn pad(&mut self, s: &str) -> Result {
976 // Make sure there's a fast path up front
977 if self.width.is_none() && self.precision.is_none() {
978 return self.buf.write_str(s);
979 }
980 // The `precision` field can be interpreted as a `max-width` for the
5bcae85e
SL
981 // string being formatted.
982 let s = if let Some(max) = self.precision {
983 // If our string is longer that the precision, then we must have
984 // truncation. However other flags like `fill`, `width` and `align`
985 // must act as always.
92a42be0 986 if let Some((i, _)) = s.char_indices().skip(max).next() {
5bcae85e
SL
987 &s[..i]
988 } else {
989 &s
1a4d82fc 990 }
5bcae85e
SL
991 } else {
992 &s
993 };
1a4d82fc
JJ
994 // The `width` field is more of a `min-width` parameter at this point.
995 match self.width {
996 // If we're under the maximum length, and there's no minimum length
997 // requirements, then we can just emit the string
998 None => self.buf.write_str(s),
999 // If we're under the maximum width, check if we're over the minimum
1000 // width, if so it's as easy as just emitting the string.
92a42be0 1001 Some(width) if s.chars().count() >= width => {
1a4d82fc
JJ
1002 self.buf.write_str(s)
1003 }
1004 // If we're under both the maximum and the minimum width, then fill
1005 // up the minimum width with the specified string + some alignment.
1006 Some(width) => {
54a0048b
SL
1007 let align = rt::v1::Alignment::Left;
1008 self.with_padding(width - s.chars().count(), align, |me| {
1a4d82fc
JJ
1009 me.buf.write_str(s)
1010 })
1011 }
1012 }
1013 }
1014
1015 /// Runs a callback, emitting the correct padding either before or
1016 /// afterwards depending on whether right or left alignment is requested.
54a0048b 1017 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
85aaf69f
SL
1018 f: F) -> Result
1019 where F: FnOnce(&mut Formatter) -> Result,
1a4d82fc 1020 {
1a4d82fc 1021 let align = match self.align {
54a0048b 1022 rt::v1::Alignment::Unknown => default,
1a4d82fc
JJ
1023 _ => self.align
1024 };
1025
1026 let (pre_pad, post_pad) = match align {
54a0048b
SL
1027 rt::v1::Alignment::Left => (0, padding),
1028 rt::v1::Alignment::Right |
1029 rt::v1::Alignment::Unknown => (padding, 0),
1030 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1a4d82fc
JJ
1031 };
1032
c30ab7b3
SL
1033 let mut fill = [0; 4];
1034 let fill = self.fill.encode_utf8(&mut fill);
1a4d82fc 1035
85aaf69f 1036 for _ in 0..pre_pad {
54a0048b 1037 self.buf.write_str(fill)?;
1a4d82fc
JJ
1038 }
1039
54a0048b 1040 f(self)?;
1a4d82fc 1041
85aaf69f 1042 for _ in 0..post_pad {
54a0048b 1043 self.buf.write_str(fill)?;
1a4d82fc
JJ
1044 }
1045
1046 Ok(())
1047 }
1048
d9579d0f
AL
1049 /// Takes the formatted parts and applies the padding.
1050 /// Assumes that the caller already has rendered the parts with required precision,
1051 /// so that `self.precision` can be ignored.
1052 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1053 if let Some(mut width) = self.width {
1054 // for the sign-aware zero padding, we render the sign first and
1055 // behave as if we had no sign from the beginning.
1056 let mut formatted = formatted.clone();
1057 let mut align = self.align;
1058 let old_fill = self.fill;
b039eaaf 1059 if self.sign_aware_zero_pad() {
d9579d0f
AL
1060 // a sign always goes first
1061 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
54a0048b 1062 self.buf.write_str(sign)?;
d9579d0f
AL
1063
1064 // remove the sign from the formatted parts
1065 formatted.sign = b"";
1066 width = if width < sign.len() { 0 } else { width - sign.len() };
54a0048b 1067 align = rt::v1::Alignment::Right;
d9579d0f
AL
1068 self.fill = '0';
1069 }
1070
1071 // remaining parts go through the ordinary padding process.
1072 let len = formatted.len();
1073 let ret = if width <= len { // no padding
1074 self.write_formatted_parts(&formatted)
1075 } else {
1076 self.with_padding(width - len, align, |f| {
1077 f.write_formatted_parts(&formatted)
1078 })
1079 };
1080 self.fill = old_fill;
1081 ret
1082 } else {
1083 // this is the common case and we take a shortcut
1084 self.write_formatted_parts(formatted)
1085 }
1086 }
1087
1088 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1089 fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1090 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1091 }
1092
1093 if !formatted.sign.is_empty() {
54a0048b 1094 write_bytes(self.buf, formatted.sign)?;
d9579d0f
AL
1095 }
1096 for part in formatted.parts {
1097 match *part {
1098 flt2dec::Part::Zero(mut nzeroes) => {
1099 const ZEROES: &'static str = // 64 zeroes
1100 "0000000000000000000000000000000000000000000000000000000000000000";
1101 while nzeroes > ZEROES.len() {
54a0048b 1102 self.buf.write_str(ZEROES)?;
d9579d0f
AL
1103 nzeroes -= ZEROES.len();
1104 }
1105 if nzeroes > 0 {
54a0048b 1106 self.buf.write_str(&ZEROES[..nzeroes])?;
d9579d0f
AL
1107 }
1108 }
1109 flt2dec::Part::Num(mut v) => {
1110 let mut s = [0; 5];
1111 let len = part.len();
1112 for c in s[..len].iter_mut().rev() {
1113 *c = b'0' + (v % 10) as u8;
1114 v /= 10;
1115 }
54a0048b 1116 write_bytes(self.buf, &s[..len])?;
d9579d0f
AL
1117 }
1118 flt2dec::Part::Copy(buf) => {
54a0048b 1119 write_bytes(self.buf, buf)?;
d9579d0f
AL
1120 }
1121 }
1122 }
1123 Ok(())
1124 }
1125
1a4d82fc
JJ
1126 /// Writes some data to the underlying buffer contained within this
1127 /// formatter.
85aaf69f 1128 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1129 pub fn write_str(&mut self, data: &str) -> Result {
1130 self.buf.write_str(data)
1131 }
1132
1133 /// Writes some formatted information into this instance
85aaf69f 1134 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1135 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1136 write(self.buf, fmt)
1137 }
1138
1139 /// Flags for formatting (packed version of rt::Flag)
85aaf69f 1140 #[stable(feature = "rust1", since = "1.0.0")]
c34b1796 1141 pub fn flags(&self) -> u32 { self.flags }
1a4d82fc
JJ
1142
1143 /// Character used as 'fill' whenever there is alignment
b039eaaf 1144 #[stable(feature = "fmt_flags", since = "1.5.0")]
1a4d82fc
JJ
1145 pub fn fill(&self) -> char { self.fill }
1146
1147 /// Flag indicating what form of alignment was requested
b039eaaf 1148 #[unstable(feature = "fmt_flags_align", reason = "method was just created",
e9174d1e 1149 issue = "27726")]
54a0048b
SL
1150 pub fn align(&self) -> Alignment {
1151 match self.align {
1152 rt::v1::Alignment::Left => Alignment::Left,
1153 rt::v1::Alignment::Right => Alignment::Right,
1154 rt::v1::Alignment::Center => Alignment::Center,
1155 rt::v1::Alignment::Unknown => Alignment::Unknown,
1156 }
1157 }
1a4d82fc
JJ
1158
1159 /// Optionally specified integer width that the output should be
b039eaaf 1160 #[stable(feature = "fmt_flags", since = "1.5.0")]
c34b1796 1161 pub fn width(&self) -> Option<usize> { self.width }
1a4d82fc
JJ
1162
1163 /// Optionally specified precision for numeric types
b039eaaf 1164 #[stable(feature = "fmt_flags", since = "1.5.0")]
c34b1796
AL
1165 pub fn precision(&self) -> Option<usize> { self.precision }
1166
b039eaaf
SL
1167 /// Determines if the `+` flag was specified.
1168 #[stable(feature = "fmt_flags", since = "1.5.0")]
1169 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1170
1171 /// Determines if the `-` flag was specified.
1172 #[stable(feature = "fmt_flags", since = "1.5.0")]
1173 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1174
1175 /// Determines if the `#` flag was specified.
1176 #[stable(feature = "fmt_flags", since = "1.5.0")]
1177 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1178
1179 /// Determines if the `0` flag was specified.
1180 #[stable(feature = "fmt_flags", since = "1.5.0")]
1181 pub fn sign_aware_zero_pad(&self) -> bool {
1182 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1183 }
1184
c34b1796
AL
1185 /// Creates a `DebugStruct` builder designed to assist with creation of
1186 /// `fmt::Debug` implementations for structs.
1187 ///
1188 /// # Examples
1189 ///
1190 /// ```rust
c34b1796
AL
1191 /// use std::fmt;
1192 ///
1193 /// struct Foo {
1194 /// bar: i32,
1195 /// baz: String,
1196 /// }
1197 ///
1198 /// impl fmt::Debug for Foo {
1199 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1200 /// fmt.debug_struct("Foo")
1201 /// .field("bar", &self.bar)
1202 /// .field("baz", &self.baz)
1203 /// .finish()
1204 /// }
1205 /// }
1206 ///
1207 /// // prints "Foo { bar: 10, baz: "Hello World" }"
1208 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
1209 /// ```
62682a34 1210 #[stable(feature = "debug_builders", since = "1.2.0")]
c34b1796
AL
1211 #[inline]
1212 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1213 builders::debug_struct_new(self, name)
1214 }
1215
1216 /// Creates a `DebugTuple` builder designed to assist with creation of
1217 /// `fmt::Debug` implementations for tuple structs.
1218 ///
1219 /// # Examples
1220 ///
1221 /// ```rust
c34b1796
AL
1222 /// use std::fmt;
1223 ///
1224 /// struct Foo(i32, String);
1225 ///
1226 /// impl fmt::Debug for Foo {
1227 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1228 /// fmt.debug_tuple("Foo")
1229 /// .field(&self.0)
1230 /// .field(&self.1)
1231 /// .finish()
1232 /// }
1233 /// }
1234 ///
1235 /// // prints "Foo(10, "Hello World")"
1236 /// println!("{:?}", Foo(10, "Hello World".to_string()));
1237 /// ```
62682a34 1238 #[stable(feature = "debug_builders", since = "1.2.0")]
c34b1796
AL
1239 #[inline]
1240 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1241 builders::debug_tuple_new(self, name)
1242 }
1243
1244 /// Creates a `DebugList` builder designed to assist with creation of
1245 /// `fmt::Debug` implementations for list-like structures.
1246 ///
1247 /// # Examples
1248 ///
1249 /// ```rust
c34b1796
AL
1250 /// use std::fmt;
1251 ///
1252 /// struct Foo(Vec<i32>);
1253 ///
1254 /// impl fmt::Debug for Foo {
1255 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
62682a34 1256 /// fmt.debug_list().entries(self.0.iter()).finish()
c34b1796
AL
1257 /// }
1258 /// }
1259 ///
1260 /// // prints "[10, 11]"
1261 /// println!("{:?}", Foo(vec![10, 11]));
1262 /// ```
62682a34 1263 #[stable(feature = "debug_builders", since = "1.2.0")]
c34b1796
AL
1264 #[inline]
1265 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1266 builders::debug_list_new(self)
1267 }
1268
1269 /// Creates a `DebugSet` builder designed to assist with creation of
1270 /// `fmt::Debug` implementations for set-like structures.
1271 ///
1272 /// # Examples
1273 ///
1274 /// ```rust
c34b1796
AL
1275 /// use std::fmt;
1276 ///
1277 /// struct Foo(Vec<i32>);
1278 ///
1279 /// impl fmt::Debug for Foo {
1280 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
62682a34 1281 /// fmt.debug_set().entries(self.0.iter()).finish()
c34b1796
AL
1282 /// }
1283 /// }
1284 ///
1285 /// // prints "{10, 11}"
1286 /// println!("{:?}", Foo(vec![10, 11]));
1287 /// ```
62682a34 1288 #[stable(feature = "debug_builders", since = "1.2.0")]
c34b1796
AL
1289 #[inline]
1290 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1291 builders::debug_set_new(self)
1292 }
1293
1294 /// Creates a `DebugMap` builder designed to assist with creation of
1295 /// `fmt::Debug` implementations for map-like structures.
1296 ///
1297 /// # Examples
1298 ///
1299 /// ```rust
c34b1796
AL
1300 /// use std::fmt;
1301 ///
1302 /// struct Foo(Vec<(String, i32)>);
1303 ///
1304 /// impl fmt::Debug for Foo {
1305 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
62682a34 1306 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
c34b1796
AL
1307 /// }
1308 /// }
1309 ///
1310 /// // prints "{"A": 10, "B": 11}"
1311 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1312 /// ```
62682a34 1313 #[stable(feature = "debug_builders", since = "1.2.0")]
c34b1796
AL
1314 #[inline]
1315 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1316 builders::debug_map_new(self)
1317 }
1a4d82fc
JJ
1318}
1319
62682a34
SL
1320#[stable(since = "1.2.0", feature = "formatter_write")]
1321impl<'a> Write for Formatter<'a> {
1322 fn write_str(&mut self, s: &str) -> Result {
1323 self.buf.write_str(s)
1324 }
1325
1326 fn write_char(&mut self, c: char) -> Result {
1327 self.buf.write_char(c)
1328 }
1329
1330 fn write_fmt(&mut self, args: Arguments) -> Result {
1331 write(self.buf, args)
1332 }
1333}
1334
85aaf69f
SL
1335#[stable(feature = "rust1", since = "1.0.0")]
1336impl Display for Error {
1a4d82fc 1337 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1338 Display::fmt("an error occurred when formatting an argument", f)
1a4d82fc
JJ
1339 }
1340}
1341
1a4d82fc
JJ
1342// Implementations of the core formatting traits
1343
1344macro_rules! fmt_refs {
1345 ($($tr:ident),*) => {
1346 $(
85aaf69f 1347 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1348 impl<'a, T: ?Sized + $tr> $tr for &'a T {
1349 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1350 }
85aaf69f 1351 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1352 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1353 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1354 }
1355 )*
1356 }
1357}
1358
85aaf69f 1359fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1a4d82fc 1360
c30ab7b3 1361#[unstable(feature = "never_type_impls", issue = "35121")]
9e0c209e
SL
1362impl Debug for ! {
1363 fn fmt(&self, _: &mut Formatter) -> Result {
1364 *self
5bcae85e
SL
1365 }
1366}
1367
c30ab7b3 1368#[unstable(feature = "never_type_impls", issue = "35121")]
9e0c209e
SL
1369impl Display for ! {
1370 fn fmt(&self, _: &mut Formatter) -> Result {
1371 *self
1372 }
1373}
5bcae85e 1374
85aaf69f
SL
1375#[stable(feature = "rust1", since = "1.0.0")]
1376impl Debug for bool {
1a4d82fc 1377 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1378 Display::fmt(self, f)
1a4d82fc
JJ
1379 }
1380}
1381
85aaf69f
SL
1382#[stable(feature = "rust1", since = "1.0.0")]
1383impl Display for bool {
1a4d82fc 1384 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1385 Display::fmt(if *self { "true" } else { "false" }, f)
1a4d82fc
JJ
1386 }
1387}
1388
85aaf69f
SL
1389#[stable(feature = "rust1", since = "1.0.0")]
1390impl Debug for str {
1a4d82fc 1391 fn fmt(&self, f: &mut Formatter) -> Result {
54a0048b 1392 f.write_char('"')?;
b039eaaf
SL
1393 let mut from = 0;
1394 for (i, c) in self.char_indices() {
5bcae85e 1395 let esc = c.escape_debug();
b039eaaf 1396 // If char needs escaping, flush backlog so far and write, else skip
3157f602 1397 if esc.len() != 1 {
54a0048b 1398 f.write_str(&self[from..i])?;
b039eaaf 1399 for c in esc {
54a0048b 1400 f.write_char(c)?;
b039eaaf
SL
1401 }
1402 from = i + c.len_utf8();
1403 }
1a4d82fc 1404 }
54a0048b 1405 f.write_str(&self[from..])?;
b039eaaf 1406 f.write_char('"')
1a4d82fc
JJ
1407 }
1408}
1409
85aaf69f
SL
1410#[stable(feature = "rust1", since = "1.0.0")]
1411impl Display for str {
1a4d82fc
JJ
1412 fn fmt(&self, f: &mut Formatter) -> Result {
1413 f.pad(self)
1414 }
1415}
1416
85aaf69f
SL
1417#[stable(feature = "rust1", since = "1.0.0")]
1418impl Debug for char {
1a4d82fc 1419 fn fmt(&self, f: &mut Formatter) -> Result {
54a0048b 1420 f.write_char('\'')?;
5bcae85e 1421 for c in self.escape_debug() {
54a0048b 1422 f.write_char(c)?
1a4d82fc 1423 }
b039eaaf 1424 f.write_char('\'')
1a4d82fc
JJ
1425 }
1426}
1427
85aaf69f
SL
1428#[stable(feature = "rust1", since = "1.0.0")]
1429impl Display for char {
1a4d82fc 1430 fn fmt(&self, f: &mut Formatter) -> Result {
62682a34
SL
1431 if f.width.is_none() && f.precision.is_none() {
1432 f.write_char(*self)
1433 } else {
c30ab7b3 1434 f.pad(self.encode_utf8(&mut [0; 4]))
62682a34 1435 }
1a4d82fc
JJ
1436 }
1437}
1438
85aaf69f 1439#[stable(feature = "rust1", since = "1.0.0")]
7453a54e 1440impl<T: ?Sized> Pointer for *const T {
1a4d82fc 1441 fn fmt(&self, f: &mut Formatter) -> Result {
9346a6ac
AL
1442 let old_width = f.width;
1443 let old_flags = f.flags;
1444
1445 // The alternate flag is already treated by LowerHex as being special-
1446 // it denotes whether to prefix with 0x. We use it to work out whether
1447 // or not to zero extend, and then unconditionally set it to get the
1448 // prefix.
b039eaaf 1449 if f.alternate() {
9346a6ac
AL
1450 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1451
1452 if let None = f.width {
9cc50fc6 1453 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
9346a6ac
AL
1454 }
1455 }
c34b1796 1456 f.flags |= 1 << (FlagV1::Alternate as u32);
9346a6ac 1457
7453a54e 1458 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
9346a6ac
AL
1459
1460 f.width = old_width;
1461 f.flags = old_flags;
1462
1a4d82fc
JJ
1463 ret
1464 }
1465}
1466
85aaf69f 1467#[stable(feature = "rust1", since = "1.0.0")]
7453a54e 1468impl<T: ?Sized> Pointer for *mut T {
1a4d82fc
JJ
1469 fn fmt(&self, f: &mut Formatter) -> Result {
1470 Pointer::fmt(&(*self as *const T), f)
1471 }
1472}
1473
85aaf69f 1474#[stable(feature = "rust1", since = "1.0.0")]
7453a54e 1475impl<'a, T: ?Sized> Pointer for &'a T {
1a4d82fc
JJ
1476 fn fmt(&self, f: &mut Formatter) -> Result {
1477 Pointer::fmt(&(*self as *const T), f)
1478 }
1479}
1480
85aaf69f 1481#[stable(feature = "rust1", since = "1.0.0")]
7453a54e 1482impl<'a, T: ?Sized> Pointer for &'a mut T {
1a4d82fc
JJ
1483 fn fmt(&self, f: &mut Formatter) -> Result {
1484 Pointer::fmt(&(&**self as *const T), f)
1485 }
1486}
1487
9346a6ac 1488// Common code of floating point Debug and Display.
d9579d0f
AL
1489fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
1490 where T: flt2dec::DecodableFloat
1491{
b039eaaf 1492 let force_sign = fmt.sign_plus();
d9579d0f
AL
1493 let sign = match (force_sign, negative_zero) {
1494 (false, false) => flt2dec::Sign::Minus,
1495 (false, true) => flt2dec::Sign::MinusRaw,
1496 (true, false) => flt2dec::Sign::MinusPlus,
1497 (true, true) => flt2dec::Sign::MinusPlusRaw,
1498 };
1499
1500 let mut buf = [0; 1024]; // enough for f32 and f64
1501 let mut parts = [flt2dec::Part::Zero(0); 16];
1502 let formatted = if let Some(precision) = fmt.precision {
1503 flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1504 precision, false, &mut buf, &mut parts)
1505 } else {
1506 flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1507 0, false, &mut buf, &mut parts)
1508 };
1509 fmt.pad_formatted_parts(&formatted)
1510}
1511
1512// Common code of floating point LowerExp and UpperExp.
1513fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
1514 where T: flt2dec::DecodableFloat
1515{
b039eaaf 1516 let force_sign = fmt.sign_plus();
d9579d0f
AL
1517 let sign = match force_sign {
1518 false => flt2dec::Sign::Minus,
1519 true => flt2dec::Sign::MinusPlus,
1520 };
1521
1522 let mut buf = [0; 1024]; // enough for f32 and f64
1523 let mut parts = [flt2dec::Part::Zero(0); 16];
1524 let formatted = if let Some(precision) = fmt.precision {
1525 // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
1526 flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1527 precision + 1, upper, &mut buf, &mut parts)
1528 } else {
1529 flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1530 (0, 0), upper, &mut buf, &mut parts)
9346a6ac 1531 };
d9579d0f 1532 fmt.pad_formatted_parts(&formatted)
9346a6ac
AL
1533}
1534
1a4d82fc
JJ
1535macro_rules! floating { ($ty:ident) => {
1536
85aaf69f
SL
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl Debug for $ty {
1a4d82fc 1539 fn fmt(&self, fmt: &mut Formatter) -> Result {
d9579d0f 1540 float_to_decimal_common(fmt, self, true)
1a4d82fc
JJ
1541 }
1542 }
1543
85aaf69f
SL
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 impl Display for $ty {
1a4d82fc 1546 fn fmt(&self, fmt: &mut Formatter) -> Result {
d9579d0f 1547 float_to_decimal_common(fmt, self, false)
1a4d82fc
JJ
1548 }
1549 }
1550
85aaf69f 1551 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1552 impl LowerExp for $ty {
1553 fn fmt(&self, fmt: &mut Formatter) -> Result {
d9579d0f 1554 float_to_exponential_common(fmt, self, false)
1a4d82fc
JJ
1555 }
1556 }
1557
85aaf69f 1558 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1559 impl UpperExp for $ty {
1560 fn fmt(&self, fmt: &mut Formatter) -> Result {
d9579d0f 1561 float_to_exponential_common(fmt, self, true)
1a4d82fc
JJ
1562 }
1563 }
1564} }
1565floating! { f32 }
1566floating! { f64 }
1567
85aaf69f 1568// Implementation of Display/Debug for various core types
1a4d82fc 1569
85aaf69f 1570#[stable(feature = "rust1", since = "1.0.0")]
c30ab7b3 1571impl<T: ?Sized> Debug for *const T {
1a4d82fc
JJ
1572 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1573}
85aaf69f 1574#[stable(feature = "rust1", since = "1.0.0")]
c30ab7b3 1575impl<T: ?Sized> Debug for *mut T {
1a4d82fc
JJ
1576 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1577}
1578
1579macro_rules! peel {
1580 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1581}
1582
1583macro_rules! tuple {
1584 () => ();
1585 ( $($name:ident,)+ ) => (
85aaf69f
SL
1586 #[stable(feature = "rust1", since = "1.0.0")]
1587 impl<$($name:Debug),*> Debug for ($($name,)*) {
9cc50fc6 1588 #[allow(non_snake_case, unused_assignments, deprecated)]
1a4d82fc 1589 fn fmt(&self, f: &mut Formatter) -> Result {
c1a9b12d 1590 let mut builder = f.debug_tuple("");
1a4d82fc 1591 let ($(ref $name,)*) = *self;
1a4d82fc 1592 $(
c1a9b12d 1593 builder.field($name);
1a4d82fc 1594 )*
c1a9b12d 1595
c1a9b12d 1596 builder.finish()
1a4d82fc
JJ
1597 }
1598 }
1599 peel! { $($name,)* }
1600 )
1601}
1602
1603tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1604
85aaf69f
SL
1605#[stable(feature = "rust1", since = "1.0.0")]
1606impl<T: Debug> Debug for [T] {
1a4d82fc 1607 fn fmt(&self, f: &mut Formatter) -> Result {
62682a34 1608 f.debug_list().entries(self.iter()).finish()
1a4d82fc
JJ
1609 }
1610}
1611
85aaf69f
SL
1612#[stable(feature = "rust1", since = "1.0.0")]
1613impl Debug for () {
1a4d82fc
JJ
1614 fn fmt(&self, f: &mut Formatter) -> Result {
1615 f.pad("()")
1616 }
1617}
92a42be0 1618#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6 1619impl<T: ?Sized> Debug for PhantomData<T> {
1a4d82fc 1620 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1621 f.pad("PhantomData")
1a4d82fc
JJ
1622 }
1623}
1624
85aaf69f
SL
1625#[stable(feature = "rust1", since = "1.0.0")]
1626impl<T: Copy + Debug> Debug for Cell<T> {
1a4d82fc 1627 fn fmt(&self, f: &mut Formatter) -> Result {
54a0048b
SL
1628 f.debug_struct("Cell")
1629 .field("value", &self.get())
1630 .finish()
1a4d82fc
JJ
1631 }
1632}
1633
85aaf69f 1634#[stable(feature = "rust1", since = "1.0.0")]
d9579d0f 1635impl<T: ?Sized + Debug> Debug for RefCell<T> {
1a4d82fc 1636 fn fmt(&self, f: &mut Formatter) -> Result {
476ff2be
SL
1637 match self.try_borrow() {
1638 Ok(borrow) => {
54a0048b 1639 f.debug_struct("RefCell")
476ff2be 1640 .field("value", &borrow)
54a0048b
SL
1641 .finish()
1642 }
476ff2be 1643 Err(_) => {
54a0048b
SL
1644 f.debug_struct("RefCell")
1645 .field("value", &"<borrowed>")
1646 .finish()
85aaf69f 1647 }
85aaf69f 1648 }
1a4d82fc
JJ
1649 }
1650}
1651
85aaf69f 1652#[stable(feature = "rust1", since = "1.0.0")]
d9579d0f 1653impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1a4d82fc 1654 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1655 Debug::fmt(&**self, f)
1a4d82fc
JJ
1656 }
1657}
1658
85aaf69f 1659#[stable(feature = "rust1", since = "1.0.0")]
d9579d0f 1660impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1a4d82fc 1661 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1662 Debug::fmt(&*(self.deref()), f)
1a4d82fc
JJ
1663 }
1664}
1665
54a0048b
SL
1666#[stable(feature = "core_impl_debug", since = "1.9.0")]
1667impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
1668 fn fmt(&self, f: &mut Formatter) -> Result {
1669 f.pad("UnsafeCell")
1670 }
1671}
1672
1a4d82fc
JJ
1673// If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1674// it's a lot easier than creating all of the rt::Piece structures here.