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