]> git.proxmox.com Git - rustc.git/blame - src/libcore/fmt/mod.rs
New upstream version 1.13.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
54a0048b 15use cell::{UnsafeCell, Cell, RefCell, Ref, RefMut, BorrowState};
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 {
54a0048b
SL
100 self.write_str(unsafe {
101 str::from_utf8_unchecked(c.encode_utf8().as_slice())
102 })
d9579d0f
AL
103 }
104
b039eaaf 105 /// Glue for usage of the `write!` macro with implementors of this trait.
1a4d82fc
JJ
106 ///
107 /// This method should generally not be invoked manually, but rather through
108 /// the `write!` macro itself.
85aaf69f 109 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
110 fn write_fmt(&mut self, args: Arguments) -> Result {
111 // This Adapter is needed to allow `self` (of type `&mut
85aaf69f 112 // Self`) to be cast to a Write (below) without
1a4d82fc
JJ
113 // requiring a `Sized` bound.
114 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
115
85aaf69f
SL
116 impl<'a, T: ?Sized> Write for Adapter<'a, T>
117 where T: Write
1a4d82fc
JJ
118 {
119 fn write_str(&mut self, s: &str) -> Result {
120 self.0.write_str(s)
121 }
122
7453a54e
SL
123 fn write_char(&mut self, c: char) -> Result {
124 self.0.write_char(c)
125 }
126
1a4d82fc
JJ
127 fn write_fmt(&mut self, args: Arguments) -> Result {
128 self.0.write_fmt(args)
129 }
130 }
131
132 write(&mut Adapter(self), args)
133 }
134}
135
e9174d1e
SL
136#[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")]
137impl<'a, W: Write + ?Sized> Write for &'a mut W {
138 fn write_str(&mut self, s: &str) -> Result {
139 (**self).write_str(s)
140 }
141
142 fn write_char(&mut self, c: char) -> Result {
143 (**self).write_char(c)
144 }
145
146 fn write_fmt(&mut self, args: Arguments) -> Result {
147 (**self).write_fmt(args)
148 }
149}
150
1a4d82fc
JJ
151/// A struct to represent both where to emit formatting strings to and how they
152/// should be formatted. A mutable version of this is passed to all formatting
153/// traits.
54a0048b 154#[allow(missing_debug_implementations)]
85aaf69f 155#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 156pub struct Formatter<'a> {
c34b1796 157 flags: u32,
1a4d82fc 158 fill: char,
85aaf69f 159 align: rt::v1::Alignment,
c34b1796
AL
160 width: Option<usize>,
161 precision: Option<usize>,
1a4d82fc 162
85aaf69f
SL
163 buf: &'a mut (Write+'a),
164 curarg: slice::Iter<'a, ArgumentV1<'a>>,
165 args: &'a [ArgumentV1<'a>],
1a4d82fc
JJ
166}
167
168// NB. Argument is essentially an optimized partially applied formatting function,
169// equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
170
171enum Void {}
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///
799/// Please note that using [`write!`][write_macro] might be preferrable. Example:
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///
810/// [write_macro]: ../../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 {
54a0048b
SL
927 f.buf.write_str(unsafe {
928 str::from_utf8_unchecked(c.encode_utf8().as_slice())
929 })?;
1a4d82fc
JJ
930 }
931 if prefixed { f.buf.write_str(prefix) }
932 else { Ok(()) }
933 };
934
935 // The `width` field is more of a `min-width` parameter at this point.
936 match self.width {
937 // If there's no minimum length requirements then we can just
938 // write the bytes.
939 None => {
54a0048b 940 write_prefix(self)?; self.buf.write_str(buf)
1a4d82fc
JJ
941 }
942 // Check if we're over the minimum width, if so then we can also
943 // just write the bytes.
944 Some(min) if width >= min => {
54a0048b 945 write_prefix(self)?; self.buf.write_str(buf)
1a4d82fc
JJ
946 }
947 // The sign and prefix goes before the padding if the fill character
948 // is zero
b039eaaf 949 Some(min) if self.sign_aware_zero_pad() => {
1a4d82fc 950 self.fill = '0';
54a0048b
SL
951 write_prefix(self)?;
952 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
1a4d82fc
JJ
953 f.buf.write_str(buf)
954 })
955 }
956 // Otherwise, the sign and prefix goes after the padding
957 Some(min) => {
54a0048b
SL
958 self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
959 write_prefix(f)?; f.buf.write_str(buf)
1a4d82fc
JJ
960 })
961 }
962 }
963 }
964
965 /// This function takes a string slice and emits it to the internal buffer
966 /// after applying the relevant formatting flags specified. The flags
967 /// recognized for generic strings are:
968 ///
969 /// * width - the minimum width of what to emit
970 /// * fill/align - what to emit and where to emit it if the string
971 /// provided needs to be padded
972 /// * precision - the maximum length to emit, the string is truncated if it
973 /// is longer than this length
974 ///
975 /// Notably this function ignored the `flag` parameters
85aaf69f 976 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
977 pub fn pad(&mut self, s: &str) -> Result {
978 // Make sure there's a fast path up front
979 if self.width.is_none() && self.precision.is_none() {
980 return self.buf.write_str(s);
981 }
982 // The `precision` field can be interpreted as a `max-width` for the
5bcae85e
SL
983 // string being formatted.
984 let s = if let Some(max) = self.precision {
985 // If our string is longer that the precision, then we must have
986 // truncation. However other flags like `fill`, `width` and `align`
987 // must act as always.
92a42be0 988 if let Some((i, _)) = s.char_indices().skip(max).next() {
5bcae85e
SL
989 &s[..i]
990 } else {
991 &s
1a4d82fc 992 }
5bcae85e
SL
993 } else {
994 &s
995 };
1a4d82fc
JJ
996 // The `width` field is more of a `min-width` parameter at this point.
997 match self.width {
998 // If we're under the maximum length, and there's no minimum length
999 // requirements, then we can just emit the string
1000 None => self.buf.write_str(s),
1001 // If we're under the maximum width, check if we're over the minimum
1002 // width, if so it's as easy as just emitting the string.
92a42be0 1003 Some(width) if s.chars().count() >= width => {
1a4d82fc
JJ
1004 self.buf.write_str(s)
1005 }
1006 // If we're under both the maximum and the minimum width, then fill
1007 // up the minimum width with the specified string + some alignment.
1008 Some(width) => {
54a0048b
SL
1009 let align = rt::v1::Alignment::Left;
1010 self.with_padding(width - s.chars().count(), align, |me| {
1a4d82fc
JJ
1011 me.buf.write_str(s)
1012 })
1013 }
1014 }
1015 }
1016
1017 /// Runs a callback, emitting the correct padding either before or
1018 /// afterwards depending on whether right or left alignment is requested.
54a0048b 1019 fn with_padding<F>(&mut self, padding: usize, default: rt::v1::Alignment,
85aaf69f
SL
1020 f: F) -> Result
1021 where F: FnOnce(&mut Formatter) -> Result,
1a4d82fc 1022 {
1a4d82fc 1023 let align = match self.align {
54a0048b 1024 rt::v1::Alignment::Unknown => default,
1a4d82fc
JJ
1025 _ => self.align
1026 };
1027
1028 let (pre_pad, post_pad) = match align {
54a0048b
SL
1029 rt::v1::Alignment::Left => (0, padding),
1030 rt::v1::Alignment::Right |
1031 rt::v1::Alignment::Unknown => (padding, 0),
1032 rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
1a4d82fc
JJ
1033 };
1034
54a0048b
SL
1035 let fill = self.fill.encode_utf8();
1036 let fill = unsafe {
1037 str::from_utf8_unchecked(fill.as_slice())
1038 };
1a4d82fc 1039
85aaf69f 1040 for _ in 0..pre_pad {
54a0048b 1041 self.buf.write_str(fill)?;
1a4d82fc
JJ
1042 }
1043
54a0048b 1044 f(self)?;
1a4d82fc 1045
85aaf69f 1046 for _ in 0..post_pad {
54a0048b 1047 self.buf.write_str(fill)?;
1a4d82fc
JJ
1048 }
1049
1050 Ok(())
1051 }
1052
d9579d0f
AL
1053 /// Takes the formatted parts and applies the padding.
1054 /// Assumes that the caller already has rendered the parts with required precision,
1055 /// so that `self.precision` can be ignored.
1056 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1057 if let Some(mut width) = self.width {
1058 // for the sign-aware zero padding, we render the sign first and
1059 // behave as if we had no sign from the beginning.
1060 let mut formatted = formatted.clone();
1061 let mut align = self.align;
1062 let old_fill = self.fill;
b039eaaf 1063 if self.sign_aware_zero_pad() {
d9579d0f
AL
1064 // a sign always goes first
1065 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
54a0048b 1066 self.buf.write_str(sign)?;
d9579d0f
AL
1067
1068 // remove the sign from the formatted parts
1069 formatted.sign = b"";
1070 width = if width < sign.len() { 0 } else { width - sign.len() };
54a0048b 1071 align = rt::v1::Alignment::Right;
d9579d0f
AL
1072 self.fill = '0';
1073 }
1074
1075 // remaining parts go through the ordinary padding process.
1076 let len = formatted.len();
1077 let ret = if width <= len { // no padding
1078 self.write_formatted_parts(&formatted)
1079 } else {
1080 self.with_padding(width - len, align, |f| {
1081 f.write_formatted_parts(&formatted)
1082 })
1083 };
1084 self.fill = old_fill;
1085 ret
1086 } else {
1087 // this is the common case and we take a shortcut
1088 self.write_formatted_parts(formatted)
1089 }
1090 }
1091
1092 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
1093 fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
1094 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
1095 }
1096
1097 if !formatted.sign.is_empty() {
54a0048b 1098 write_bytes(self.buf, formatted.sign)?;
d9579d0f
AL
1099 }
1100 for part in formatted.parts {
1101 match *part {
1102 flt2dec::Part::Zero(mut nzeroes) => {
1103 const ZEROES: &'static str = // 64 zeroes
1104 "0000000000000000000000000000000000000000000000000000000000000000";
1105 while nzeroes > ZEROES.len() {
54a0048b 1106 self.buf.write_str(ZEROES)?;
d9579d0f
AL
1107 nzeroes -= ZEROES.len();
1108 }
1109 if nzeroes > 0 {
54a0048b 1110 self.buf.write_str(&ZEROES[..nzeroes])?;
d9579d0f
AL
1111 }
1112 }
1113 flt2dec::Part::Num(mut v) => {
1114 let mut s = [0; 5];
1115 let len = part.len();
1116 for c in s[..len].iter_mut().rev() {
1117 *c = b'0' + (v % 10) as u8;
1118 v /= 10;
1119 }
54a0048b 1120 write_bytes(self.buf, &s[..len])?;
d9579d0f
AL
1121 }
1122 flt2dec::Part::Copy(buf) => {
54a0048b 1123 write_bytes(self.buf, buf)?;
d9579d0f
AL
1124 }
1125 }
1126 }
1127 Ok(())
1128 }
1129
1a4d82fc
JJ
1130 /// Writes some data to the underlying buffer contained within this
1131 /// formatter.
85aaf69f 1132 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1133 pub fn write_str(&mut self, data: &str) -> Result {
1134 self.buf.write_str(data)
1135 }
1136
1137 /// Writes some formatted information into this instance
85aaf69f 1138 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1139 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
1140 write(self.buf, fmt)
1141 }
1142
1143 /// Flags for formatting (packed version of rt::Flag)
85aaf69f 1144 #[stable(feature = "rust1", since = "1.0.0")]
c34b1796 1145 pub fn flags(&self) -> u32 { self.flags }
1a4d82fc
JJ
1146
1147 /// Character used as 'fill' whenever there is alignment
b039eaaf 1148 #[stable(feature = "fmt_flags", since = "1.5.0")]
1a4d82fc
JJ
1149 pub fn fill(&self) -> char { self.fill }
1150
1151 /// Flag indicating what form of alignment was requested
b039eaaf 1152 #[unstable(feature = "fmt_flags_align", reason = "method was just created",
e9174d1e 1153 issue = "27726")]
54a0048b
SL
1154 pub fn align(&self) -> Alignment {
1155 match self.align {
1156 rt::v1::Alignment::Left => Alignment::Left,
1157 rt::v1::Alignment::Right => Alignment::Right,
1158 rt::v1::Alignment::Center => Alignment::Center,
1159 rt::v1::Alignment::Unknown => Alignment::Unknown,
1160 }
1161 }
1a4d82fc
JJ
1162
1163 /// Optionally specified integer width that the output should be
b039eaaf 1164 #[stable(feature = "fmt_flags", since = "1.5.0")]
c34b1796 1165 pub fn width(&self) -> Option<usize> { self.width }
1a4d82fc
JJ
1166
1167 /// Optionally specified precision for numeric types
b039eaaf 1168 #[stable(feature = "fmt_flags", since = "1.5.0")]
c34b1796
AL
1169 pub fn precision(&self) -> Option<usize> { self.precision }
1170
b039eaaf
SL
1171 /// Determines if the `+` flag was specified.
1172 #[stable(feature = "fmt_flags", since = "1.5.0")]
1173 pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 }
1174
1175 /// Determines if the `-` flag was specified.
1176 #[stable(feature = "fmt_flags", since = "1.5.0")]
1177 pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 }
1178
1179 /// Determines if the `#` flag was specified.
1180 #[stable(feature = "fmt_flags", since = "1.5.0")]
1181 pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 }
1182
1183 /// Determines if the `0` flag was specified.
1184 #[stable(feature = "fmt_flags", since = "1.5.0")]
1185 pub fn sign_aware_zero_pad(&self) -> bool {
1186 self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0
1187 }
1188
c34b1796
AL
1189 /// Creates a `DebugStruct` builder designed to assist with creation of
1190 /// `fmt::Debug` implementations for structs.
1191 ///
1192 /// # Examples
1193 ///
1194 /// ```rust
c34b1796
AL
1195 /// use std::fmt;
1196 ///
1197 /// struct Foo {
1198 /// bar: i32,
1199 /// baz: String,
1200 /// }
1201 ///
1202 /// impl fmt::Debug for Foo {
1203 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1204 /// fmt.debug_struct("Foo")
1205 /// .field("bar", &self.bar)
1206 /// .field("baz", &self.baz)
1207 /// .finish()
1208 /// }
1209 /// }
1210 ///
1211 /// // prints "Foo { bar: 10, baz: "Hello World" }"
1212 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
1213 /// ```
62682a34 1214 #[stable(feature = "debug_builders", since = "1.2.0")]
c34b1796
AL
1215 #[inline]
1216 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
1217 builders::debug_struct_new(self, name)
1218 }
1219
1220 /// Creates a `DebugTuple` builder designed to assist with creation of
1221 /// `fmt::Debug` implementations for tuple structs.
1222 ///
1223 /// # Examples
1224 ///
1225 /// ```rust
c34b1796
AL
1226 /// use std::fmt;
1227 ///
1228 /// struct Foo(i32, String);
1229 ///
1230 /// impl fmt::Debug for Foo {
1231 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1232 /// fmt.debug_tuple("Foo")
1233 /// .field(&self.0)
1234 /// .field(&self.1)
1235 /// .finish()
1236 /// }
1237 /// }
1238 ///
1239 /// // prints "Foo(10, "Hello World")"
1240 /// println!("{:?}", Foo(10, "Hello World".to_string()));
1241 /// ```
62682a34 1242 #[stable(feature = "debug_builders", since = "1.2.0")]
c34b1796
AL
1243 #[inline]
1244 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
1245 builders::debug_tuple_new(self, name)
1246 }
1247
1248 /// Creates a `DebugList` builder designed to assist with creation of
1249 /// `fmt::Debug` implementations for list-like structures.
1250 ///
1251 /// # Examples
1252 ///
1253 /// ```rust
c34b1796
AL
1254 /// use std::fmt;
1255 ///
1256 /// struct Foo(Vec<i32>);
1257 ///
1258 /// impl fmt::Debug for Foo {
1259 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
62682a34 1260 /// fmt.debug_list().entries(self.0.iter()).finish()
c34b1796
AL
1261 /// }
1262 /// }
1263 ///
1264 /// // prints "[10, 11]"
1265 /// println!("{:?}", Foo(vec![10, 11]));
1266 /// ```
62682a34 1267 #[stable(feature = "debug_builders", since = "1.2.0")]
c34b1796
AL
1268 #[inline]
1269 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
1270 builders::debug_list_new(self)
1271 }
1272
1273 /// Creates a `DebugSet` builder designed to assist with creation of
1274 /// `fmt::Debug` implementations for set-like structures.
1275 ///
1276 /// # Examples
1277 ///
1278 /// ```rust
c34b1796
AL
1279 /// use std::fmt;
1280 ///
1281 /// struct Foo(Vec<i32>);
1282 ///
1283 /// impl fmt::Debug for Foo {
1284 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
62682a34 1285 /// fmt.debug_set().entries(self.0.iter()).finish()
c34b1796
AL
1286 /// }
1287 /// }
1288 ///
1289 /// // prints "{10, 11}"
1290 /// println!("{:?}", Foo(vec![10, 11]));
1291 /// ```
62682a34 1292 #[stable(feature = "debug_builders", since = "1.2.0")]
c34b1796
AL
1293 #[inline]
1294 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
1295 builders::debug_set_new(self)
1296 }
1297
1298 /// Creates a `DebugMap` builder designed to assist with creation of
1299 /// `fmt::Debug` implementations for map-like structures.
1300 ///
1301 /// # Examples
1302 ///
1303 /// ```rust
c34b1796
AL
1304 /// use std::fmt;
1305 ///
1306 /// struct Foo(Vec<(String, i32)>);
1307 ///
1308 /// impl fmt::Debug for Foo {
1309 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
62682a34 1310 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
c34b1796
AL
1311 /// }
1312 /// }
1313 ///
1314 /// // prints "{"A": 10, "B": 11}"
1315 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
1316 /// ```
62682a34 1317 #[stable(feature = "debug_builders", since = "1.2.0")]
c34b1796
AL
1318 #[inline]
1319 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
1320 builders::debug_map_new(self)
1321 }
1a4d82fc
JJ
1322}
1323
62682a34
SL
1324#[stable(since = "1.2.0", feature = "formatter_write")]
1325impl<'a> Write for Formatter<'a> {
1326 fn write_str(&mut self, s: &str) -> Result {
1327 self.buf.write_str(s)
1328 }
1329
1330 fn write_char(&mut self, c: char) -> Result {
1331 self.buf.write_char(c)
1332 }
1333
1334 fn write_fmt(&mut self, args: Arguments) -> Result {
1335 write(self.buf, args)
1336 }
1337}
1338
85aaf69f
SL
1339#[stable(feature = "rust1", since = "1.0.0")]
1340impl Display for Error {
1a4d82fc 1341 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1342 Display::fmt("an error occurred when formatting an argument", f)
1a4d82fc
JJ
1343 }
1344}
1345
1a4d82fc
JJ
1346// Implementations of the core formatting traits
1347
1348macro_rules! fmt_refs {
1349 ($($tr:ident),*) => {
1350 $(
85aaf69f 1351 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1352 impl<'a, T: ?Sized + $tr> $tr for &'a T {
1353 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1354 }
85aaf69f 1355 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1356 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
1357 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
1358 }
1359 )*
1360 }
1361}
1362
85aaf69f 1363fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
1a4d82fc 1364
9e0c209e
SL
1365#[unstable(feature = "never_type", issue = "35121")]
1366impl Debug for ! {
1367 fn fmt(&self, _: &mut Formatter) -> Result {
1368 *self
5bcae85e
SL
1369 }
1370}
1371
9e0c209e
SL
1372#[unstable(feature = "never_type", issue = "35121")]
1373impl Display for ! {
1374 fn fmt(&self, _: &mut Formatter) -> Result {
1375 *self
1376 }
1377}
5bcae85e 1378
85aaf69f
SL
1379#[stable(feature = "rust1", since = "1.0.0")]
1380impl Debug for bool {
1a4d82fc 1381 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1382 Display::fmt(self, f)
1a4d82fc
JJ
1383 }
1384}
1385
85aaf69f
SL
1386#[stable(feature = "rust1", since = "1.0.0")]
1387impl Display for bool {
1a4d82fc 1388 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1389 Display::fmt(if *self { "true" } else { "false" }, f)
1a4d82fc
JJ
1390 }
1391}
1392
85aaf69f
SL
1393#[stable(feature = "rust1", since = "1.0.0")]
1394impl Debug for str {
1a4d82fc 1395 fn fmt(&self, f: &mut Formatter) -> Result {
54a0048b 1396 f.write_char('"')?;
b039eaaf
SL
1397 let mut from = 0;
1398 for (i, c) in self.char_indices() {
5bcae85e 1399 let esc = c.escape_debug();
b039eaaf 1400 // If char needs escaping, flush backlog so far and write, else skip
3157f602 1401 if esc.len() != 1 {
54a0048b 1402 f.write_str(&self[from..i])?;
b039eaaf 1403 for c in esc {
54a0048b 1404 f.write_char(c)?;
b039eaaf
SL
1405 }
1406 from = i + c.len_utf8();
1407 }
1a4d82fc 1408 }
54a0048b 1409 f.write_str(&self[from..])?;
b039eaaf 1410 f.write_char('"')
1a4d82fc
JJ
1411 }
1412}
1413
85aaf69f
SL
1414#[stable(feature = "rust1", since = "1.0.0")]
1415impl Display for str {
1a4d82fc
JJ
1416 fn fmt(&self, f: &mut Formatter) -> Result {
1417 f.pad(self)
1418 }
1419}
1420
85aaf69f
SL
1421#[stable(feature = "rust1", since = "1.0.0")]
1422impl Debug for char {
1a4d82fc 1423 fn fmt(&self, f: &mut Formatter) -> Result {
54a0048b 1424 f.write_char('\'')?;
5bcae85e 1425 for c in self.escape_debug() {
54a0048b 1426 f.write_char(c)?
1a4d82fc 1427 }
b039eaaf 1428 f.write_char('\'')
1a4d82fc
JJ
1429 }
1430}
1431
85aaf69f
SL
1432#[stable(feature = "rust1", since = "1.0.0")]
1433impl Display for char {
1a4d82fc 1434 fn fmt(&self, f: &mut Formatter) -> Result {
62682a34
SL
1435 if f.width.is_none() && f.precision.is_none() {
1436 f.write_char(*self)
1437 } else {
54a0048b
SL
1438 f.pad(unsafe {
1439 str::from_utf8_unchecked(self.encode_utf8().as_slice())
1440 })
62682a34 1441 }
1a4d82fc
JJ
1442 }
1443}
1444
85aaf69f 1445#[stable(feature = "rust1", since = "1.0.0")]
7453a54e 1446impl<T: ?Sized> Pointer for *const T {
1a4d82fc 1447 fn fmt(&self, f: &mut Formatter) -> Result {
9346a6ac
AL
1448 let old_width = f.width;
1449 let old_flags = f.flags;
1450
1451 // The alternate flag is already treated by LowerHex as being special-
1452 // it denotes whether to prefix with 0x. We use it to work out whether
1453 // or not to zero extend, and then unconditionally set it to get the
1454 // prefix.
b039eaaf 1455 if f.alternate() {
9346a6ac
AL
1456 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1457
1458 if let None = f.width {
9cc50fc6 1459 f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
9346a6ac
AL
1460 }
1461 }
c34b1796 1462 f.flags |= 1 << (FlagV1::Alternate as u32);
9346a6ac 1463
7453a54e 1464 let ret = LowerHex::fmt(&(*self as *const () as usize), f);
9346a6ac
AL
1465
1466 f.width = old_width;
1467 f.flags = old_flags;
1468
1a4d82fc
JJ
1469 ret
1470 }
1471}
1472
85aaf69f 1473#[stable(feature = "rust1", since = "1.0.0")]
7453a54e 1474impl<T: ?Sized> Pointer for *mut T {
1a4d82fc
JJ
1475 fn fmt(&self, f: &mut Formatter) -> Result {
1476 Pointer::fmt(&(*self as *const T), f)
1477 }
1478}
1479
85aaf69f 1480#[stable(feature = "rust1", since = "1.0.0")]
7453a54e 1481impl<'a, T: ?Sized> Pointer for &'a T {
1a4d82fc
JJ
1482 fn fmt(&self, f: &mut Formatter) -> Result {
1483 Pointer::fmt(&(*self as *const T), f)
1484 }
1485}
1486
85aaf69f 1487#[stable(feature = "rust1", since = "1.0.0")]
7453a54e 1488impl<'a, T: ?Sized> Pointer for &'a mut T {
1a4d82fc
JJ
1489 fn fmt(&self, f: &mut Formatter) -> Result {
1490 Pointer::fmt(&(&**self as *const T), f)
1491 }
1492}
1493
9346a6ac 1494// Common code of floating point Debug and Display.
d9579d0f
AL
1495fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
1496 where T: flt2dec::DecodableFloat
1497{
b039eaaf 1498 let force_sign = fmt.sign_plus();
d9579d0f
AL
1499 let sign = match (force_sign, negative_zero) {
1500 (false, false) => flt2dec::Sign::Minus,
1501 (false, true) => flt2dec::Sign::MinusRaw,
1502 (true, false) => flt2dec::Sign::MinusPlus,
1503 (true, true) => flt2dec::Sign::MinusPlusRaw,
1504 };
1505
1506 let mut buf = [0; 1024]; // enough for f32 and f64
1507 let mut parts = [flt2dec::Part::Zero(0); 16];
1508 let formatted = if let Some(precision) = fmt.precision {
1509 flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1510 precision, false, &mut buf, &mut parts)
1511 } else {
1512 flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1513 0, false, &mut buf, &mut parts)
1514 };
1515 fmt.pad_formatted_parts(&formatted)
1516}
1517
1518// Common code of floating point LowerExp and UpperExp.
1519fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
1520 where T: flt2dec::DecodableFloat
1521{
b039eaaf 1522 let force_sign = fmt.sign_plus();
d9579d0f
AL
1523 let sign = match force_sign {
1524 false => flt2dec::Sign::Minus,
1525 true => flt2dec::Sign::MinusPlus,
1526 };
1527
1528 let mut buf = [0; 1024]; // enough for f32 and f64
1529 let mut parts = [flt2dec::Part::Zero(0); 16];
1530 let formatted = if let Some(precision) = fmt.precision {
1531 // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
1532 flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1533 precision + 1, upper, &mut buf, &mut parts)
1534 } else {
1535 flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1536 (0, 0), upper, &mut buf, &mut parts)
9346a6ac 1537 };
d9579d0f 1538 fmt.pad_formatted_parts(&formatted)
9346a6ac
AL
1539}
1540
1a4d82fc
JJ
1541macro_rules! floating { ($ty:ident) => {
1542
85aaf69f
SL
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 impl Debug for $ty {
1a4d82fc 1545 fn fmt(&self, fmt: &mut Formatter) -> Result {
d9579d0f 1546 float_to_decimal_common(fmt, self, true)
1a4d82fc
JJ
1547 }
1548 }
1549
85aaf69f
SL
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 impl Display for $ty {
1a4d82fc 1552 fn fmt(&self, fmt: &mut Formatter) -> Result {
d9579d0f 1553 float_to_decimal_common(fmt, self, false)
1a4d82fc
JJ
1554 }
1555 }
1556
85aaf69f 1557 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1558 impl LowerExp for $ty {
1559 fn fmt(&self, fmt: &mut Formatter) -> Result {
d9579d0f 1560 float_to_exponential_common(fmt, self, false)
1a4d82fc
JJ
1561 }
1562 }
1563
85aaf69f 1564 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1565 impl UpperExp for $ty {
1566 fn fmt(&self, fmt: &mut Formatter) -> Result {
d9579d0f 1567 float_to_exponential_common(fmt, self, true)
1a4d82fc
JJ
1568 }
1569 }
1570} }
1571floating! { f32 }
1572floating! { f64 }
1573
85aaf69f 1574// Implementation of Display/Debug for various core types
1a4d82fc 1575
85aaf69f
SL
1576#[stable(feature = "rust1", since = "1.0.0")]
1577impl<T> Debug for *const T {
1a4d82fc
JJ
1578 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1579}
85aaf69f
SL
1580#[stable(feature = "rust1", since = "1.0.0")]
1581impl<T> Debug for *mut T {
1a4d82fc
JJ
1582 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1583}
1584
1585macro_rules! peel {
1586 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1587}
1588
1589macro_rules! tuple {
1590 () => ();
1591 ( $($name:ident,)+ ) => (
85aaf69f
SL
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 impl<$($name:Debug),*> Debug for ($($name,)*) {
9cc50fc6 1594 #[allow(non_snake_case, unused_assignments, deprecated)]
1a4d82fc 1595 fn fmt(&self, f: &mut Formatter) -> Result {
c1a9b12d 1596 let mut builder = f.debug_tuple("");
1a4d82fc 1597 let ($(ref $name,)*) = *self;
1a4d82fc 1598 $(
c1a9b12d 1599 builder.field($name);
1a4d82fc 1600 )*
c1a9b12d 1601
c1a9b12d 1602 builder.finish()
1a4d82fc
JJ
1603 }
1604 }
1605 peel! { $($name,)* }
1606 )
1607}
1608
1609tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1610
85aaf69f
SL
1611#[stable(feature = "rust1", since = "1.0.0")]
1612impl<T: Debug> Debug for [T] {
1a4d82fc 1613 fn fmt(&self, f: &mut Formatter) -> Result {
62682a34 1614 f.debug_list().entries(self.iter()).finish()
1a4d82fc
JJ
1615 }
1616}
1617
85aaf69f
SL
1618#[stable(feature = "rust1", since = "1.0.0")]
1619impl Debug for () {
1a4d82fc
JJ
1620 fn fmt(&self, f: &mut Formatter) -> Result {
1621 f.pad("()")
1622 }
1623}
92a42be0 1624#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6 1625impl<T: ?Sized> Debug for PhantomData<T> {
1a4d82fc 1626 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1627 f.pad("PhantomData")
1a4d82fc
JJ
1628 }
1629}
1630
85aaf69f
SL
1631#[stable(feature = "rust1", since = "1.0.0")]
1632impl<T: Copy + Debug> Debug for Cell<T> {
1a4d82fc 1633 fn fmt(&self, f: &mut Formatter) -> Result {
54a0048b
SL
1634 f.debug_struct("Cell")
1635 .field("value", &self.get())
1636 .finish()
1a4d82fc
JJ
1637 }
1638}
1639
85aaf69f 1640#[stable(feature = "rust1", since = "1.0.0")]
d9579d0f 1641impl<T: ?Sized + Debug> Debug for RefCell<T> {
1a4d82fc 1642 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f
SL
1643 match self.borrow_state() {
1644 BorrowState::Unused | BorrowState::Reading => {
54a0048b
SL
1645 f.debug_struct("RefCell")
1646 .field("value", &self.borrow())
1647 .finish()
1648 }
1649 BorrowState::Writing => {
1650 f.debug_struct("RefCell")
1651 .field("value", &"<borrowed>")
1652 .finish()
85aaf69f 1653 }
85aaf69f 1654 }
1a4d82fc
JJ
1655 }
1656}
1657
85aaf69f 1658#[stable(feature = "rust1", since = "1.0.0")]
d9579d0f 1659impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1a4d82fc 1660 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1661 Debug::fmt(&**self, f)
1a4d82fc
JJ
1662 }
1663}
1664
85aaf69f 1665#[stable(feature = "rust1", since = "1.0.0")]
d9579d0f 1666impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1a4d82fc 1667 fn fmt(&self, f: &mut Formatter) -> Result {
85aaf69f 1668 Debug::fmt(&*(self.deref()), f)
1a4d82fc
JJ
1669 }
1670}
1671
54a0048b
SL
1672#[stable(feature = "core_impl_debug", since = "1.9.0")]
1673impl<T: ?Sized + Debug> Debug for UnsafeCell<T> {
1674 fn fmt(&self, f: &mut Formatter) -> Result {
1675 f.pad("UnsafeCell")
1676 }
1677}
1678
1a4d82fc
JJ
1679// If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1680// it's a lot easier than creating all of the rt::Piece structures here.