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