]> git.proxmox.com Git - rustc.git/blob - src/libcore/fmt/mod.rs
343772c764f817b242c7856dd8b025c35cc2c949
[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 prelude::*;
16
17 use cell::{Cell, RefCell, Ref, RefMut, BorrowState};
18 use marker::PhantomData;
19 use mem;
20 use num::flt2dec;
21 use ops::Deref;
22 use result;
23 use slice;
24 use str;
25 use self::rt::v1::Alignment;
26
27 pub use self::num::radix;
28 pub use self::num::Radix;
29 pub use self::num::RadixFmt;
30
31 pub use self::builders::{DebugStruct, DebugTuple, DebugSet, DebugList, DebugMap};
32
33 mod num;
34 mod builders;
35
36 #[unstable(feature = "fmt_internals", reason = "internal to format_args!")]
37 #[doc(hidden)]
38 pub mod rt {
39 pub mod v1;
40 }
41
42 #[stable(feature = "rust1", since = "1.0.0")]
43 /// The type returned by formatter methods.
44 pub type Result = result::Result<(), Error>;
45
46 /// The error type which is returned from formatting a message into a stream.
47 ///
48 /// This type does not support transmission of an error other than that an error
49 /// occurred. Any extra information must be arranged to be transmitted through
50 /// some other means.
51 #[stable(feature = "rust1", since = "1.0.0")]
52 #[derive(Copy, Clone, Debug)]
53 pub struct Error;
54
55 /// A collection of methods that are required to format a message into a stream.
56 ///
57 /// This trait is the type which this modules requires when formatting
58 /// information. This is similar to the standard library's `io::Write` trait,
59 /// but it is only intended for use in libcore.
60 ///
61 /// This trait should generally not be implemented by consumers of the standard
62 /// library. The `write!` macro accepts an instance of `io::Write`, and the
63 /// `io::Write` trait is favored over implementing this trait.
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub trait Write {
66 /// Writes a slice of bytes into this writer, returning whether the write
67 /// succeeded.
68 ///
69 /// This method can only succeed if the entire byte slice was successfully
70 /// written, and this method will not return until all data has been
71 /// written or an error occurs.
72 ///
73 /// # Errors
74 ///
75 /// This function will return an instance of `Error` on error.
76 #[stable(feature = "rust1", since = "1.0.0")]
77 fn write_str(&mut self, s: &str) -> Result;
78
79 /// Writes a `char` into this writer, returning whether the write succeeded.
80 ///
81 /// A single `char` may be encoded as more than one byte.
82 /// This method can only succeed if the entire byte sequence 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 #[stable(feature = "fmt_write_char", since = "1.1.0")]
90 fn write_char(&mut self, c: char) -> Result {
91 let mut utf_8 = [0u8; 4];
92 let bytes_written = c.encode_utf8(&mut utf_8).unwrap_or(0);
93 self.write_str(unsafe { mem::transmute(&utf_8[..bytes_written]) })
94 }
95
96 /// Glue for usage of the `write!` macro with implementers of this trait.
97 ///
98 /// This method should generally not be invoked manually, but rather through
99 /// the `write!` macro itself.
100 #[stable(feature = "rust1", since = "1.0.0")]
101 fn write_fmt(&mut self, args: Arguments) -> Result {
102 // This Adapter is needed to allow `self` (of type `&mut
103 // Self`) to be cast to a Write (below) without
104 // requiring a `Sized` bound.
105 struct Adapter<'a,T: ?Sized +'a>(&'a mut T);
106
107 impl<'a, T: ?Sized> Write for Adapter<'a, T>
108 where T: Write
109 {
110 fn write_str(&mut self, s: &str) -> Result {
111 self.0.write_str(s)
112 }
113
114 fn write_fmt(&mut self, args: Arguments) -> Result {
115 self.0.write_fmt(args)
116 }
117 }
118
119 write(&mut Adapter(self), args)
120 }
121 }
122
123 /// A struct to represent both where to emit formatting strings to and how they
124 /// should be formatted. A mutable version of this is passed to all formatting
125 /// traits.
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub struct Formatter<'a> {
128 flags: u32,
129 fill: char,
130 align: rt::v1::Alignment,
131 width: Option<usize>,
132 precision: Option<usize>,
133
134 buf: &'a mut (Write+'a),
135 curarg: slice::Iter<'a, ArgumentV1<'a>>,
136 args: &'a [ArgumentV1<'a>],
137 }
138
139 // NB. Argument is essentially an optimized partially applied formatting function,
140 // equivalent to `exists T.(&T, fn(&T, &mut Formatter) -> Result`.
141
142 enum Void {}
143
144 /// This struct represents the generic "argument" which is taken by the Xprintf
145 /// family of functions. It contains a function to format the given value. At
146 /// compile time it is ensured that the function and the value have the correct
147 /// types, and then this struct is used to canonicalize arguments to one type.
148 #[derive(Copy)]
149 #[unstable(feature = "fmt_internals", reason = "internal to format_args!")]
150 #[doc(hidden)]
151 pub struct ArgumentV1<'a> {
152 value: &'a Void,
153 formatter: fn(&Void, &mut Formatter) -> Result,
154 }
155
156 impl<'a> Clone for ArgumentV1<'a> {
157 fn clone(&self) -> ArgumentV1<'a> {
158 *self
159 }
160 }
161
162 impl<'a> ArgumentV1<'a> {
163 #[inline(never)]
164 fn show_usize(x: &usize, f: &mut Formatter) -> Result {
165 Display::fmt(x, f)
166 }
167
168 #[doc(hidden)]
169 #[unstable(feature = "fmt_internals", reason = "internal to format_args!")]
170 pub fn new<'b, T>(x: &'b T,
171 f: fn(&T, &mut Formatter) -> Result) -> ArgumentV1<'b> {
172 unsafe {
173 ArgumentV1 {
174 formatter: mem::transmute(f),
175 value: mem::transmute(x)
176 }
177 }
178 }
179
180 #[doc(hidden)]
181 #[unstable(feature = "fmt_internals", reason = "internal to format_args!")]
182 pub fn from_usize(x: &usize) -> ArgumentV1 {
183 ArgumentV1::new(x, ArgumentV1::show_usize)
184 }
185
186 fn as_usize(&self) -> Option<usize> {
187 if self.formatter as usize == ArgumentV1::show_usize as usize {
188 Some(unsafe { *(self.value as *const _ as *const usize) })
189 } else {
190 None
191 }
192 }
193 }
194
195 // flags available in the v1 format of format_args
196 #[derive(Copy, Clone)]
197 #[allow(dead_code)] // SignMinus isn't currently used
198 enum FlagV1 { SignPlus, SignMinus, Alternate, SignAwareZeroPad, }
199
200 impl<'a> Arguments<'a> {
201 /// When using the format_args!() macro, this function is used to generate the
202 /// Arguments structure.
203 #[doc(hidden)] #[inline]
204 #[unstable(feature = "fmt_internals", reason = "internal to format_args!")]
205 pub fn new_v1(pieces: &'a [&'a str],
206 args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
207 Arguments {
208 pieces: pieces,
209 fmt: None,
210 args: args
211 }
212 }
213
214 /// This function is used to specify nonstandard formatting parameters.
215 /// The `pieces` array must be at least as long as `fmt` to construct
216 /// a valid Arguments structure. Also, any `Count` within `fmt` that is
217 /// `CountIsParam` or `CountIsNextParam` has to point to an argument
218 /// created with `argumentusize`. However, failing to do so doesn't cause
219 /// unsafety, but will ignore invalid .
220 #[doc(hidden)] #[inline]
221 #[unstable(feature = "fmt_internals", reason = "internal to format_args!")]
222 pub fn new_v1_formatted(pieces: &'a [&'a str],
223 args: &'a [ArgumentV1<'a>],
224 fmt: &'a [rt::v1::Argument]) -> Arguments<'a> {
225 Arguments {
226 pieces: pieces,
227 fmt: Some(fmt),
228 args: args
229 }
230 }
231 }
232
233 /// This structure represents a safely precompiled version of a format string
234 /// and its arguments. This cannot be generated at runtime because it cannot
235 /// safely be done so, so no constructors are given and the fields are private
236 /// to prevent modification.
237 ///
238 /// The `format_args!` macro will safely create an instance of this structure
239 /// and pass it to a function or closure, passed as the first argument. The
240 /// macro validates the format string at compile-time so usage of the `write`
241 /// and `format` functions can be safely performed.
242 #[stable(feature = "rust1", since = "1.0.0")]
243 #[derive(Copy, Clone)]
244 pub struct Arguments<'a> {
245 // Format string pieces to print.
246 pieces: &'a [&'a str],
247
248 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
249 fmt: Option<&'a [rt::v1::Argument]>,
250
251 // Dynamic arguments for interpolation, to be interleaved with string
252 // pieces. (Every argument is preceded by a string piece.)
253 args: &'a [ArgumentV1<'a>],
254 }
255
256 #[stable(feature = "rust1", since = "1.0.0")]
257 impl<'a> Debug for Arguments<'a> {
258 fn fmt(&self, fmt: &mut Formatter) -> Result {
259 Display::fmt(self, fmt)
260 }
261 }
262
263 #[stable(feature = "rust1", since = "1.0.0")]
264 impl<'a> Display for Arguments<'a> {
265 fn fmt(&self, fmt: &mut Formatter) -> Result {
266 write(fmt.buf, *self)
267 }
268 }
269
270 /// Format trait for the `:?` format. Useful for debugging, all types
271 /// should implement this.
272 ///
273 /// Generally speaking, you should just `derive` a `Debug` implementation.
274 ///
275 /// # Examples
276 ///
277 /// Deriving an implementation:
278 ///
279 /// ```
280 /// #[derive(Debug)]
281 /// struct Point {
282 /// x: i32,
283 /// y: i32,
284 /// }
285 ///
286 /// let origin = Point { x: 0, y: 0 };
287 ///
288 /// println!("The origin is: {:?}", origin);
289 /// ```
290 ///
291 /// Manually implementing:
292 ///
293 /// ```
294 /// use std::fmt;
295 ///
296 /// struct Point {
297 /// x: i32,
298 /// y: i32,
299 /// }
300 ///
301 /// impl fmt::Debug for Point {
302 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
303 /// write!(f, "({}, {})", self.x, self.y)
304 /// }
305 /// }
306 ///
307 /// let origin = Point { x: 0, y: 0 };
308 ///
309 /// println!("The origin is: {:?}", origin);
310 /// ```
311 ///
312 /// There are a number of `debug_*` methods on `Formatter` to help you with manual
313 /// implementations, such as [`debug_struct`][debug_struct].
314 ///
315 /// [debug_struct]: ../std/fmt/struct.Formatter.html#method.debug_struct
316 #[stable(feature = "rust1", since = "1.0.0")]
317 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
318 defined in your crate, add `#[derive(Debug)]` or \
319 manually implement it"]
320 #[lang = "debug_trait"]
321 pub trait Debug {
322 /// Formats the value using the given formatter.
323 #[stable(feature = "rust1", since = "1.0.0")]
324 fn fmt(&self, &mut Formatter) -> Result;
325 }
326
327 /// When a value can be semantically expressed as a String, this trait may be
328 /// used. It corresponds to the default format, `{}`.
329 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
330 formatter; try using `:?` instead if you are using \
331 a format string"]
332 #[stable(feature = "rust1", since = "1.0.0")]
333 pub trait Display {
334 /// Formats the value using the given formatter.
335 #[stable(feature = "rust1", since = "1.0.0")]
336 fn fmt(&self, &mut Formatter) -> Result;
337 }
338
339 /// Format trait for the `o` character
340 #[stable(feature = "rust1", since = "1.0.0")]
341 pub trait Octal {
342 /// Formats the value using the given formatter.
343 #[stable(feature = "rust1", since = "1.0.0")]
344 fn fmt(&self, &mut Formatter) -> Result;
345 }
346
347 /// Format trait for the `b` character
348 #[stable(feature = "rust1", since = "1.0.0")]
349 pub trait Binary {
350 /// Formats the value using the given formatter.
351 #[stable(feature = "rust1", since = "1.0.0")]
352 fn fmt(&self, &mut Formatter) -> Result;
353 }
354
355 /// Format trait for the `x` character
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub trait LowerHex {
358 /// Formats the value using the given formatter.
359 #[stable(feature = "rust1", since = "1.0.0")]
360 fn fmt(&self, &mut Formatter) -> Result;
361 }
362
363 /// Format trait for the `X` character
364 #[stable(feature = "rust1", since = "1.0.0")]
365 pub trait UpperHex {
366 /// Formats the value using the given formatter.
367 #[stable(feature = "rust1", since = "1.0.0")]
368 fn fmt(&self, &mut Formatter) -> Result;
369 }
370
371 /// Format trait for the `p` character
372 #[stable(feature = "rust1", since = "1.0.0")]
373 pub trait Pointer {
374 /// Formats the value using the given formatter.
375 #[stable(feature = "rust1", since = "1.0.0")]
376 fn fmt(&self, &mut Formatter) -> Result;
377 }
378
379 /// Format trait for the `e` character
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub trait LowerExp {
382 /// Formats the value using the given formatter.
383 #[stable(feature = "rust1", since = "1.0.0")]
384 fn fmt(&self, &mut Formatter) -> Result;
385 }
386
387 /// Format trait for the `E` character
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub trait UpperExp {
390 /// Formats the value using the given formatter.
391 #[stable(feature = "rust1", since = "1.0.0")]
392 fn fmt(&self, &mut Formatter) -> Result;
393 }
394
395 /// The `write` function takes an output stream, a precompiled format string,
396 /// and a list of arguments. The arguments will be formatted according to the
397 /// specified format string into the output stream provided.
398 ///
399 /// # Arguments
400 ///
401 /// * output - the buffer to write output to
402 /// * args - the precompiled arguments generated by `format_args!`
403 #[stable(feature = "rust1", since = "1.0.0")]
404 pub fn write(output: &mut Write, args: Arguments) -> Result {
405 let mut formatter = Formatter {
406 flags: 0,
407 width: None,
408 precision: None,
409 buf: output,
410 align: Alignment::Unknown,
411 fill: ' ',
412 args: args.args,
413 curarg: args.args.iter(),
414 };
415
416 let mut pieces = args.pieces.iter();
417
418 match args.fmt {
419 None => {
420 // We can use default formatting parameters for all arguments.
421 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
422 try!(formatter.buf.write_str(*piece));
423 try!((arg.formatter)(arg.value, &mut formatter));
424 }
425 }
426 Some(fmt) => {
427 // Every spec has a corresponding argument that is preceded by
428 // a string piece.
429 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
430 try!(formatter.buf.write_str(*piece));
431 try!(formatter.run(arg));
432 }
433 }
434 }
435
436 // There can be only one trailing string piece left.
437 match pieces.next() {
438 Some(piece) => {
439 try!(formatter.buf.write_str(*piece));
440 }
441 None => {}
442 }
443
444 Ok(())
445 }
446
447 impl<'a> Formatter<'a> {
448
449 // First up is the collection of functions used to execute a format string
450 // at runtime. This consumes all of the compile-time statics generated by
451 // the format! syntax extension.
452 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
453 // Fill in the format parameters into the formatter
454 self.fill = arg.format.fill;
455 self.align = arg.format.align;
456 self.flags = arg.format.flags;
457 self.width = self.getcount(&arg.format.width);
458 self.precision = self.getcount(&arg.format.precision);
459
460 // Extract the correct argument
461 let value = match arg.position {
462 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
463 rt::v1::Position::At(i) => self.args[i],
464 };
465
466 // Then actually do some printing
467 (value.formatter)(value.value, self)
468 }
469
470 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
471 match *cnt {
472 rt::v1::Count::Is(n) => Some(n),
473 rt::v1::Count::Implied => None,
474 rt::v1::Count::Param(i) => {
475 self.args[i].as_usize()
476 }
477 rt::v1::Count::NextParam => {
478 self.curarg.next().and_then(|arg| arg.as_usize())
479 }
480 }
481 }
482
483 // Helper methods used for padding and processing formatting arguments that
484 // all formatting traits can use.
485
486 /// Performs the correct padding for an integer which has already been
487 /// emitted into a str. The str should *not* contain the sign for the
488 /// integer, that will be added by this method.
489 ///
490 /// # Arguments
491 ///
492 /// * is_positive - whether the original integer was positive or not.
493 /// * prefix - if the '#' character (Alternate) is provided, this
494 /// is the prefix to put in front of the number.
495 /// * buf - the byte array that the number has been formatted into
496 ///
497 /// This function will correctly account for the flags provided as well as
498 /// the minimum width. It will not take precision into account.
499 #[stable(feature = "rust1", since = "1.0.0")]
500 pub fn pad_integral(&mut self,
501 is_positive: bool,
502 prefix: &str,
503 buf: &str)
504 -> Result {
505 use char::CharExt;
506
507 let mut width = buf.len();
508
509 let mut sign = None;
510 if !is_positive {
511 sign = Some('-'); width += 1;
512 } else if self.flags & (1 << (FlagV1::SignPlus as u32)) != 0 {
513 sign = Some('+'); width += 1;
514 }
515
516 let mut prefixed = false;
517 if self.flags & (1 << (FlagV1::Alternate as u32)) != 0 {
518 prefixed = true; width += prefix.char_len();
519 }
520
521 // Writes the sign if it exists, and then the prefix if it was requested
522 let write_prefix = |f: &mut Formatter| {
523 if let Some(c) = sign {
524 let mut b = [0; 4];
525 let n = c.encode_utf8(&mut b).unwrap_or(0);
526 let b = unsafe { str::from_utf8_unchecked(&b[..n]) };
527 try!(f.buf.write_str(b));
528 }
529 if prefixed { f.buf.write_str(prefix) }
530 else { Ok(()) }
531 };
532
533 // The `width` field is more of a `min-width` parameter at this point.
534 match self.width {
535 // If there's no minimum length requirements then we can just
536 // write the bytes.
537 None => {
538 try!(write_prefix(self)); self.buf.write_str(buf)
539 }
540 // Check if we're over the minimum width, if so then we can also
541 // just write the bytes.
542 Some(min) if width >= min => {
543 try!(write_prefix(self)); self.buf.write_str(buf)
544 }
545 // The sign and prefix goes before the padding if the fill character
546 // is zero
547 Some(min) if self.flags & (1 << (FlagV1::SignAwareZeroPad as u32)) != 0 => {
548 self.fill = '0';
549 try!(write_prefix(self));
550 self.with_padding(min - width, Alignment::Right, |f| {
551 f.buf.write_str(buf)
552 })
553 }
554 // Otherwise, the sign and prefix goes after the padding
555 Some(min) => {
556 self.with_padding(min - width, Alignment::Right, |f| {
557 try!(write_prefix(f)); f.buf.write_str(buf)
558 })
559 }
560 }
561 }
562
563 /// This function takes a string slice and emits it to the internal buffer
564 /// after applying the relevant formatting flags specified. The flags
565 /// recognized for generic strings are:
566 ///
567 /// * width - the minimum width of what to emit
568 /// * fill/align - what to emit and where to emit it if the string
569 /// provided needs to be padded
570 /// * precision - the maximum length to emit, the string is truncated if it
571 /// is longer than this length
572 ///
573 /// Notably this function ignored the `flag` parameters
574 #[stable(feature = "rust1", since = "1.0.0")]
575 pub fn pad(&mut self, s: &str) -> Result {
576 // Make sure there's a fast path up front
577 if self.width.is_none() && self.precision.is_none() {
578 return self.buf.write_str(s);
579 }
580 // The `precision` field can be interpreted as a `max-width` for the
581 // string being formatted
582 match self.precision {
583 Some(max) => {
584 // If there's a maximum width and our string is longer than
585 // that, then we must always have truncation. This is the only
586 // case where the maximum length will matter.
587 let char_len = s.char_len();
588 if char_len >= max {
589 let nchars = ::cmp::min(max, char_len);
590 return self.buf.write_str(s.slice_chars(0, nchars));
591 }
592 }
593 None => {}
594 }
595 // The `width` field is more of a `min-width` parameter at this point.
596 match self.width {
597 // If we're under the maximum length, and there's no minimum length
598 // requirements, then we can just emit the string
599 None => self.buf.write_str(s),
600 // If we're under the maximum width, check if we're over the minimum
601 // width, if so it's as easy as just emitting the string.
602 Some(width) if s.char_len() >= width => {
603 self.buf.write_str(s)
604 }
605 // If we're under both the maximum and the minimum width, then fill
606 // up the minimum width with the specified string + some alignment.
607 Some(width) => {
608 self.with_padding(width - s.char_len(), Alignment::Left, |me| {
609 me.buf.write_str(s)
610 })
611 }
612 }
613 }
614
615 /// Runs a callback, emitting the correct padding either before or
616 /// afterwards depending on whether right or left alignment is requested.
617 fn with_padding<F>(&mut self, padding: usize, default: Alignment,
618 f: F) -> Result
619 where F: FnOnce(&mut Formatter) -> Result,
620 {
621 use char::CharExt;
622 let align = match self.align {
623 Alignment::Unknown => default,
624 _ => self.align
625 };
626
627 let (pre_pad, post_pad) = match align {
628 Alignment::Left => (0, padding),
629 Alignment::Right | Alignment::Unknown => (padding, 0),
630 Alignment::Center => (padding / 2, (padding + 1) / 2),
631 };
632
633 let mut fill = [0; 4];
634 let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
635 let fill = unsafe { str::from_utf8_unchecked(&fill[..len]) };
636
637 for _ in 0..pre_pad {
638 try!(self.buf.write_str(fill));
639 }
640
641 try!(f(self));
642
643 for _ in 0..post_pad {
644 try!(self.buf.write_str(fill));
645 }
646
647 Ok(())
648 }
649
650 /// Takes the formatted parts and applies the padding.
651 /// Assumes that the caller already has rendered the parts with required precision,
652 /// so that `self.precision` can be ignored.
653 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
654 if let Some(mut width) = self.width {
655 // for the sign-aware zero padding, we render the sign first and
656 // behave as if we had no sign from the beginning.
657 let mut formatted = formatted.clone();
658 let mut align = self.align;
659 let old_fill = self.fill;
660 if self.flags & (1 << (FlagV1::SignAwareZeroPad as u32)) != 0 {
661 // a sign always goes first
662 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
663 try!(self.buf.write_str(sign));
664
665 // remove the sign from the formatted parts
666 formatted.sign = b"";
667 width = if width < sign.len() { 0 } else { width - sign.len() };
668 align = Alignment::Right;
669 self.fill = '0';
670 }
671
672 // remaining parts go through the ordinary padding process.
673 let len = formatted.len();
674 let ret = if width <= len { // no padding
675 self.write_formatted_parts(&formatted)
676 } else {
677 self.with_padding(width - len, align, |f| {
678 f.write_formatted_parts(&formatted)
679 })
680 };
681 self.fill = old_fill;
682 ret
683 } else {
684 // this is the common case and we take a shortcut
685 self.write_formatted_parts(formatted)
686 }
687 }
688
689 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
690 fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
691 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
692 }
693
694 if !formatted.sign.is_empty() {
695 try!(write_bytes(self.buf, formatted.sign));
696 }
697 for part in formatted.parts {
698 match *part {
699 flt2dec::Part::Zero(mut nzeroes) => {
700 const ZEROES: &'static str = // 64 zeroes
701 "0000000000000000000000000000000000000000000000000000000000000000";
702 while nzeroes > ZEROES.len() {
703 try!(self.buf.write_str(ZEROES));
704 nzeroes -= ZEROES.len();
705 }
706 if nzeroes > 0 {
707 try!(self.buf.write_str(&ZEROES[..nzeroes]));
708 }
709 }
710 flt2dec::Part::Num(mut v) => {
711 let mut s = [0; 5];
712 let len = part.len();
713 for c in s[..len].iter_mut().rev() {
714 *c = b'0' + (v % 10) as u8;
715 v /= 10;
716 }
717 try!(write_bytes(self.buf, &s[..len]));
718 }
719 flt2dec::Part::Copy(buf) => {
720 try!(write_bytes(self.buf, buf));
721 }
722 }
723 }
724 Ok(())
725 }
726
727 /// Writes some data to the underlying buffer contained within this
728 /// formatter.
729 #[stable(feature = "rust1", since = "1.0.0")]
730 pub fn write_str(&mut self, data: &str) -> Result {
731 self.buf.write_str(data)
732 }
733
734 /// Writes some formatted information into this instance
735 #[stable(feature = "rust1", since = "1.0.0")]
736 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
737 write(self.buf, fmt)
738 }
739
740 /// Flags for formatting (packed version of rt::Flag)
741 #[stable(feature = "rust1", since = "1.0.0")]
742 pub fn flags(&self) -> u32 { self.flags }
743
744 /// Character used as 'fill' whenever there is alignment
745 #[unstable(feature = "fmt_flags", reason = "method was just created")]
746 pub fn fill(&self) -> char { self.fill }
747
748 /// Flag indicating what form of alignment was requested
749 #[unstable(feature = "fmt_flags", reason = "method was just created")]
750 pub fn align(&self) -> Alignment { self.align }
751
752 /// Optionally specified integer width that the output should be
753 #[unstable(feature = "fmt_flags", reason = "method was just created")]
754 pub fn width(&self) -> Option<usize> { self.width }
755
756 /// Optionally specified precision for numeric types
757 #[unstable(feature = "fmt_flags", reason = "method was just created")]
758 pub fn precision(&self) -> Option<usize> { self.precision }
759
760 /// Creates a `DebugStruct` builder designed to assist with creation of
761 /// `fmt::Debug` implementations for structs.
762 ///
763 /// # Examples
764 ///
765 /// ```rust
766 /// use std::fmt;
767 ///
768 /// struct Foo {
769 /// bar: i32,
770 /// baz: String,
771 /// }
772 ///
773 /// impl fmt::Debug for Foo {
774 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
775 /// fmt.debug_struct("Foo")
776 /// .field("bar", &self.bar)
777 /// .field("baz", &self.baz)
778 /// .finish()
779 /// }
780 /// }
781 ///
782 /// // prints "Foo { bar: 10, baz: "Hello World" }"
783 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
784 /// ```
785 #[stable(feature = "debug_builders", since = "1.2.0")]
786 #[inline]
787 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
788 builders::debug_struct_new(self, name)
789 }
790
791 /// Creates a `DebugTuple` builder designed to assist with creation of
792 /// `fmt::Debug` implementations for tuple structs.
793 ///
794 /// # Examples
795 ///
796 /// ```rust
797 /// use std::fmt;
798 ///
799 /// struct Foo(i32, String);
800 ///
801 /// impl fmt::Debug for Foo {
802 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
803 /// fmt.debug_tuple("Foo")
804 /// .field(&self.0)
805 /// .field(&self.1)
806 /// .finish()
807 /// }
808 /// }
809 ///
810 /// // prints "Foo(10, "Hello World")"
811 /// println!("{:?}", Foo(10, "Hello World".to_string()));
812 /// ```
813 #[stable(feature = "debug_builders", since = "1.2.0")]
814 #[inline]
815 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
816 builders::debug_tuple_new(self, name)
817 }
818
819 /// Creates a `DebugList` builder designed to assist with creation of
820 /// `fmt::Debug` implementations for list-like structures.
821 ///
822 /// # Examples
823 ///
824 /// ```rust
825 /// use std::fmt;
826 ///
827 /// struct Foo(Vec<i32>);
828 ///
829 /// impl fmt::Debug for Foo {
830 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
831 /// fmt.debug_list().entries(self.0.iter()).finish()
832 /// }
833 /// }
834 ///
835 /// // prints "[10, 11]"
836 /// println!("{:?}", Foo(vec![10, 11]));
837 /// ```
838 #[stable(feature = "debug_builders", since = "1.2.0")]
839 #[inline]
840 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
841 builders::debug_list_new(self)
842 }
843
844 /// Creates a `DebugSet` builder designed to assist with creation of
845 /// `fmt::Debug` implementations for set-like structures.
846 ///
847 /// # Examples
848 ///
849 /// ```rust
850 /// use std::fmt;
851 ///
852 /// struct Foo(Vec<i32>);
853 ///
854 /// impl fmt::Debug for Foo {
855 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
856 /// fmt.debug_set().entries(self.0.iter()).finish()
857 /// }
858 /// }
859 ///
860 /// // prints "{10, 11}"
861 /// println!("{:?}", Foo(vec![10, 11]));
862 /// ```
863 #[stable(feature = "debug_builders", since = "1.2.0")]
864 #[inline]
865 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
866 builders::debug_set_new(self)
867 }
868
869 /// Creates a `DebugMap` builder designed to assist with creation of
870 /// `fmt::Debug` implementations for map-like structures.
871 ///
872 /// # Examples
873 ///
874 /// ```rust
875 /// use std::fmt;
876 ///
877 /// struct Foo(Vec<(String, i32)>);
878 ///
879 /// impl fmt::Debug for Foo {
880 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
881 /// fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
882 /// }
883 /// }
884 ///
885 /// // prints "{"A": 10, "B": 11}"
886 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
887 /// ```
888 #[stable(feature = "debug_builders", since = "1.2.0")]
889 #[inline]
890 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
891 builders::debug_map_new(self)
892 }
893 }
894
895 #[stable(since = "1.2.0", feature = "formatter_write")]
896 impl<'a> Write for Formatter<'a> {
897 fn write_str(&mut self, s: &str) -> Result {
898 self.buf.write_str(s)
899 }
900
901 fn write_char(&mut self, c: char) -> Result {
902 self.buf.write_char(c)
903 }
904
905 fn write_fmt(&mut self, args: Arguments) -> Result {
906 write(self.buf, args)
907 }
908 }
909
910 #[stable(feature = "rust1", since = "1.0.0")]
911 impl Display for Error {
912 fn fmt(&self, f: &mut Formatter) -> Result {
913 Display::fmt("an error occurred when formatting an argument", f)
914 }
915 }
916
917 // Implementations of the core formatting traits
918
919 macro_rules! fmt_refs {
920 ($($tr:ident),*) => {
921 $(
922 #[stable(feature = "rust1", since = "1.0.0")]
923 impl<'a, T: ?Sized + $tr> $tr for &'a T {
924 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
925 }
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
928 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
929 }
930 )*
931 }
932 }
933
934 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
935
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl Debug for bool {
938 fn fmt(&self, f: &mut Formatter) -> Result {
939 Display::fmt(self, f)
940 }
941 }
942
943 #[stable(feature = "rust1", since = "1.0.0")]
944 impl Display for bool {
945 fn fmt(&self, f: &mut Formatter) -> Result {
946 Display::fmt(if *self { "true" } else { "false" }, f)
947 }
948 }
949
950 #[stable(feature = "rust1", since = "1.0.0")]
951 impl Debug for str {
952 fn fmt(&self, f: &mut Formatter) -> Result {
953 try!(write!(f, "\""));
954 for c in self.chars().flat_map(|c| c.escape_default()) {
955 try!(write!(f, "{}", c));
956 }
957 write!(f, "\"")
958 }
959 }
960
961 #[stable(feature = "rust1", since = "1.0.0")]
962 impl Display for str {
963 fn fmt(&self, f: &mut Formatter) -> Result {
964 f.pad(self)
965 }
966 }
967
968 #[stable(feature = "rust1", since = "1.0.0")]
969 impl Debug for char {
970 fn fmt(&self, f: &mut Formatter) -> Result {
971 use char::CharExt;
972 try!(write!(f, "'"));
973 for c in self.escape_default() {
974 try!(write!(f, "{}", c));
975 }
976 write!(f, "'")
977 }
978 }
979
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl Display for char {
982 fn fmt(&self, f: &mut Formatter) -> Result {
983 if f.width.is_none() && f.precision.is_none() {
984 f.write_char(*self)
985 } else {
986 let mut utf8 = [0; 4];
987 let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
988 let s: &str = unsafe { mem::transmute(&utf8[..amt]) };
989 f.pad(s)
990 }
991 }
992 }
993
994 #[stable(feature = "rust1", since = "1.0.0")]
995 impl<T> Pointer for *const T {
996 fn fmt(&self, f: &mut Formatter) -> Result {
997 let old_width = f.width;
998 let old_flags = f.flags;
999
1000 // The alternate flag is already treated by LowerHex as being special-
1001 // it denotes whether to prefix with 0x. We use it to work out whether
1002 // or not to zero extend, and then unconditionally set it to get the
1003 // prefix.
1004 if f.flags & 1 << (FlagV1::Alternate as u32) > 0 {
1005 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
1006
1007 if let None = f.width {
1008 // The formats need two extra bytes, for the 0x
1009 if cfg!(target_pointer_width = "32") {
1010 f.width = Some(10);
1011 } else {
1012 f.width = Some(18);
1013 }
1014 }
1015 }
1016 f.flags |= 1 << (FlagV1::Alternate as u32);
1017
1018 let ret = LowerHex::fmt(&(*self as usize), f);
1019
1020 f.width = old_width;
1021 f.flags = old_flags;
1022
1023 ret
1024 }
1025 }
1026
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl<T> Pointer for *mut T {
1029 fn fmt(&self, f: &mut Formatter) -> Result {
1030 // FIXME(#23542) Replace with type ascription.
1031 #![allow(trivial_casts)]
1032 Pointer::fmt(&(*self as *const T), f)
1033 }
1034 }
1035
1036 #[stable(feature = "rust1", since = "1.0.0")]
1037 impl<'a, T> Pointer for &'a T {
1038 fn fmt(&self, f: &mut Formatter) -> Result {
1039 // FIXME(#23542) Replace with type ascription.
1040 #![allow(trivial_casts)]
1041 Pointer::fmt(&(*self as *const T), f)
1042 }
1043 }
1044
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl<'a, T> Pointer for &'a mut T {
1047 fn fmt(&self, f: &mut Formatter) -> Result {
1048 // FIXME(#23542) Replace with type ascription.
1049 #![allow(trivial_casts)]
1050 Pointer::fmt(&(&**self as *const T), f)
1051 }
1052 }
1053
1054 // Common code of floating point Debug and Display.
1055 fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
1056 where T: flt2dec::DecodableFloat
1057 {
1058 let force_sign = fmt.flags & (1 << (FlagV1::SignPlus as u32)) != 0;
1059 let sign = match (force_sign, negative_zero) {
1060 (false, false) => flt2dec::Sign::Minus,
1061 (false, true) => flt2dec::Sign::MinusRaw,
1062 (true, false) => flt2dec::Sign::MinusPlus,
1063 (true, true) => flt2dec::Sign::MinusPlusRaw,
1064 };
1065
1066 let mut buf = [0; 1024]; // enough for f32 and f64
1067 let mut parts = [flt2dec::Part::Zero(0); 16];
1068 let formatted = if let Some(precision) = fmt.precision {
1069 flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1070 precision, false, &mut buf, &mut parts)
1071 } else {
1072 flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1073 0, false, &mut buf, &mut parts)
1074 };
1075 fmt.pad_formatted_parts(&formatted)
1076 }
1077
1078 // Common code of floating point LowerExp and UpperExp.
1079 fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
1080 where T: flt2dec::DecodableFloat
1081 {
1082 let force_sign = fmt.flags & (1 << (FlagV1::SignPlus as u32)) != 0;
1083 let sign = match force_sign {
1084 false => flt2dec::Sign::Minus,
1085 true => flt2dec::Sign::MinusPlus,
1086 };
1087
1088 let mut buf = [0; 1024]; // enough for f32 and f64
1089 let mut parts = [flt2dec::Part::Zero(0); 16];
1090 let formatted = if let Some(precision) = fmt.precision {
1091 // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
1092 flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1093 precision + 1, upper, &mut buf, &mut parts)
1094 } else {
1095 flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1096 (0, 0), upper, &mut buf, &mut parts)
1097 };
1098 fmt.pad_formatted_parts(&formatted)
1099 }
1100
1101 macro_rules! floating { ($ty:ident) => {
1102
1103 #[stable(feature = "rust1", since = "1.0.0")]
1104 impl Debug for $ty {
1105 fn fmt(&self, fmt: &mut Formatter) -> Result {
1106 float_to_decimal_common(fmt, self, true)
1107 }
1108 }
1109
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 impl Display for $ty {
1112 fn fmt(&self, fmt: &mut Formatter) -> Result {
1113 float_to_decimal_common(fmt, self, false)
1114 }
1115 }
1116
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 impl LowerExp for $ty {
1119 fn fmt(&self, fmt: &mut Formatter) -> Result {
1120 float_to_exponential_common(fmt, self, false)
1121 }
1122 }
1123
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 impl UpperExp for $ty {
1126 fn fmt(&self, fmt: &mut Formatter) -> Result {
1127 float_to_exponential_common(fmt, self, true)
1128 }
1129 }
1130 } }
1131 floating! { f32 }
1132 floating! { f64 }
1133
1134 // Implementation of Display/Debug for various core types
1135
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<T> Debug for *const T {
1138 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1139 }
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 impl<T> Debug for *mut T {
1142 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1143 }
1144
1145 macro_rules! peel {
1146 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1147 }
1148
1149 macro_rules! tuple {
1150 () => ();
1151 ( $($name:ident,)+ ) => (
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 impl<$($name:Debug),*> Debug for ($($name,)*) {
1154 #[allow(non_snake_case, unused_assignments)]
1155 fn fmt(&self, f: &mut Formatter) -> Result {
1156 try!(write!(f, "("));
1157 let ($(ref $name,)*) = *self;
1158 let mut n = 0;
1159 $(
1160 if n > 0 {
1161 try!(write!(f, ", "));
1162 }
1163 try!(write!(f, "{:?}", *$name));
1164 n += 1;
1165 )*
1166 if n == 1 {
1167 try!(write!(f, ","));
1168 }
1169 write!(f, ")")
1170 }
1171 }
1172 peel! { $($name,)* }
1173 )
1174 }
1175
1176 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1177
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 impl<T: Debug> Debug for [T] {
1180 fn fmt(&self, f: &mut Formatter) -> Result {
1181 f.debug_list().entries(self.iter()).finish()
1182 }
1183 }
1184
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 impl Debug for () {
1187 fn fmt(&self, f: &mut Formatter) -> Result {
1188 f.pad("()")
1189 }
1190 }
1191 impl<T> Debug for PhantomData<T> {
1192 fn fmt(&self, f: &mut Formatter) -> Result {
1193 f.pad("PhantomData")
1194 }
1195 }
1196
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 impl<T: Copy + Debug> Debug for Cell<T> {
1199 fn fmt(&self, f: &mut Formatter) -> Result {
1200 write!(f, "Cell {{ value: {:?} }}", self.get())
1201 }
1202 }
1203
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 impl<T: ?Sized + Debug> Debug for RefCell<T> {
1206 fn fmt(&self, f: &mut Formatter) -> Result {
1207 match self.borrow_state() {
1208 BorrowState::Unused | BorrowState::Reading => {
1209 write!(f, "RefCell {{ value: {:?} }}", self.borrow())
1210 }
1211 BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"),
1212 }
1213 }
1214 }
1215
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1218 fn fmt(&self, f: &mut Formatter) -> Result {
1219 Debug::fmt(&**self, f)
1220 }
1221 }
1222
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1225 fn fmt(&self, f: &mut Formatter) -> Result {
1226 Debug::fmt(&*(self.deref()), f)
1227 }
1228 }
1229
1230 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1231 // it's a lot easier than creating all of the rt::Piece structures here.