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