]> git.proxmox.com Git - rustc.git/blob - src/libcore/fmt/mod.rs
a87f6619fe8772e7e36127d9b06f705856e0e8ac
[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 = "core", 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 `FormatError` 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 `FormatError` 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 = "core", 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 = "core", 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 = "core", 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 = "core", 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 = "core", 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 #[stable(feature = "rust1", since = "1.0.0")]
273 #[rustc_on_unimplemented = "`{Self}` cannot be formatted using `:?`; if it is \
274 defined in your crate, add `#[derive(Debug)]` or \
275 manually implement it"]
276 #[lang = "debug_trait"]
277 pub trait Debug {
278 /// Formats the value using the given formatter.
279 #[stable(feature = "rust1", since = "1.0.0")]
280 fn fmt(&self, &mut Formatter) -> Result;
281 }
282
283 /// When a value can be semantically expressed as a String, this trait may be
284 /// used. It corresponds to the default format, `{}`.
285 #[rustc_on_unimplemented = "`{Self}` cannot be formatted with the default \
286 formatter; try using `:?` instead if you are using \
287 a format string"]
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub trait Display {
290 /// Formats the value using the given formatter.
291 #[stable(feature = "rust1", since = "1.0.0")]
292 fn fmt(&self, &mut Formatter) -> Result;
293 }
294
295 /// Format trait for the `o` character
296 #[stable(feature = "rust1", since = "1.0.0")]
297 pub trait Octal {
298 /// Formats the value using the given formatter.
299 #[stable(feature = "rust1", since = "1.0.0")]
300 fn fmt(&self, &mut Formatter) -> Result;
301 }
302
303 /// Format trait for the `b` character
304 #[stable(feature = "rust1", since = "1.0.0")]
305 pub trait Binary {
306 /// Formats the value using the given formatter.
307 #[stable(feature = "rust1", since = "1.0.0")]
308 fn fmt(&self, &mut Formatter) -> Result;
309 }
310
311 /// Format trait for the `x` character
312 #[stable(feature = "rust1", since = "1.0.0")]
313 pub trait LowerHex {
314 /// Formats the value using the given formatter.
315 #[stable(feature = "rust1", since = "1.0.0")]
316 fn fmt(&self, &mut Formatter) -> Result;
317 }
318
319 /// Format trait for the `X` character
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub trait UpperHex {
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 /// Format trait for the `p` character
328 #[stable(feature = "rust1", since = "1.0.0")]
329 pub trait Pointer {
330 /// Formats the value using the given formatter.
331 #[stable(feature = "rust1", since = "1.0.0")]
332 fn fmt(&self, &mut Formatter) -> Result;
333 }
334
335 /// Format trait for the `e` character
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub trait LowerExp {
338 /// Formats the value using the given formatter.
339 #[stable(feature = "rust1", since = "1.0.0")]
340 fn fmt(&self, &mut Formatter) -> Result;
341 }
342
343 /// Format trait for the `E` character
344 #[stable(feature = "rust1", since = "1.0.0")]
345 pub trait UpperExp {
346 /// Formats the value using the given formatter.
347 #[stable(feature = "rust1", since = "1.0.0")]
348 fn fmt(&self, &mut Formatter) -> Result;
349 }
350
351 /// The `write` function takes an output stream, a precompiled format string,
352 /// and a list of arguments. The arguments will be formatted according to the
353 /// specified format string into the output stream provided.
354 ///
355 /// # Arguments
356 ///
357 /// * output - the buffer to write output to
358 /// * args - the precompiled arguments generated by `format_args!`
359 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn write(output: &mut Write, args: Arguments) -> Result {
361 let mut formatter = Formatter {
362 flags: 0,
363 width: None,
364 precision: None,
365 buf: output,
366 align: Alignment::Unknown,
367 fill: ' ',
368 args: args.args,
369 curarg: args.args.iter(),
370 };
371
372 let mut pieces = args.pieces.iter();
373
374 match args.fmt {
375 None => {
376 // We can use default formatting parameters for all arguments.
377 for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
378 try!(formatter.buf.write_str(*piece));
379 try!((arg.formatter)(arg.value, &mut formatter));
380 }
381 }
382 Some(fmt) => {
383 // Every spec has a corresponding argument that is preceded by
384 // a string piece.
385 for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
386 try!(formatter.buf.write_str(*piece));
387 try!(formatter.run(arg));
388 }
389 }
390 }
391
392 // There can be only one trailing string piece left.
393 match pieces.next() {
394 Some(piece) => {
395 try!(formatter.buf.write_str(*piece));
396 }
397 None => {}
398 }
399
400 Ok(())
401 }
402
403 impl<'a> Formatter<'a> {
404
405 // First up is the collection of functions used to execute a format string
406 // at runtime. This consumes all of the compile-time statics generated by
407 // the format! syntax extension.
408 fn run(&mut self, arg: &rt::v1::Argument) -> Result {
409 // Fill in the format parameters into the formatter
410 self.fill = arg.format.fill;
411 self.align = arg.format.align;
412 self.flags = arg.format.flags;
413 self.width = self.getcount(&arg.format.width);
414 self.precision = self.getcount(&arg.format.precision);
415
416 // Extract the correct argument
417 let value = match arg.position {
418 rt::v1::Position::Next => { *self.curarg.next().unwrap() }
419 rt::v1::Position::At(i) => self.args[i],
420 };
421
422 // Then actually do some printing
423 (value.formatter)(value.value, self)
424 }
425
426 fn getcount(&mut self, cnt: &rt::v1::Count) -> Option<usize> {
427 match *cnt {
428 rt::v1::Count::Is(n) => Some(n),
429 rt::v1::Count::Implied => None,
430 rt::v1::Count::Param(i) => {
431 self.args[i].as_usize()
432 }
433 rt::v1::Count::NextParam => {
434 self.curarg.next().and_then(|arg| arg.as_usize())
435 }
436 }
437 }
438
439 // Helper methods used for padding and processing formatting arguments that
440 // all formatting traits can use.
441
442 /// Performs the correct padding for an integer which has already been
443 /// emitted into a str. The str should *not* contain the sign for the
444 /// integer, that will be added by this method.
445 ///
446 /// # Arguments
447 ///
448 /// * is_positive - whether the original integer was positive or not.
449 /// * prefix - if the '#' character (Alternate) is provided, this
450 /// is the prefix to put in front of the number.
451 /// * buf - the byte array that the number has been formatted into
452 ///
453 /// This function will correctly account for the flags provided as well as
454 /// the minimum width. It will not take precision into account.
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn pad_integral(&mut self,
457 is_positive: bool,
458 prefix: &str,
459 buf: &str)
460 -> Result {
461 use char::CharExt;
462
463 let mut width = buf.len();
464
465 let mut sign = None;
466 if !is_positive {
467 sign = Some('-'); width += 1;
468 } else if self.flags & (1 << (FlagV1::SignPlus as u32)) != 0 {
469 sign = Some('+'); width += 1;
470 }
471
472 let mut prefixed = false;
473 if self.flags & (1 << (FlagV1::Alternate as u32)) != 0 {
474 prefixed = true; width += prefix.char_len();
475 }
476
477 // Writes the sign if it exists, and then the prefix if it was requested
478 let write_prefix = |f: &mut Formatter| {
479 if let Some(c) = sign {
480 let mut b = [0; 4];
481 let n = c.encode_utf8(&mut b).unwrap_or(0);
482 let b = unsafe { str::from_utf8_unchecked(&b[..n]) };
483 try!(f.buf.write_str(b));
484 }
485 if prefixed { f.buf.write_str(prefix) }
486 else { Ok(()) }
487 };
488
489 // The `width` field is more of a `min-width` parameter at this point.
490 match self.width {
491 // If there's no minimum length requirements then we can just
492 // write the bytes.
493 None => {
494 try!(write_prefix(self)); self.buf.write_str(buf)
495 }
496 // Check if we're over the minimum width, if so then we can also
497 // just write the bytes.
498 Some(min) if width >= min => {
499 try!(write_prefix(self)); self.buf.write_str(buf)
500 }
501 // The sign and prefix goes before the padding if the fill character
502 // is zero
503 Some(min) if self.flags & (1 << (FlagV1::SignAwareZeroPad as u32)) != 0 => {
504 self.fill = '0';
505 try!(write_prefix(self));
506 self.with_padding(min - width, Alignment::Right, |f| {
507 f.buf.write_str(buf)
508 })
509 }
510 // Otherwise, the sign and prefix goes after the padding
511 Some(min) => {
512 self.with_padding(min - width, Alignment::Right, |f| {
513 try!(write_prefix(f)); f.buf.write_str(buf)
514 })
515 }
516 }
517 }
518
519 /// This function takes a string slice and emits it to the internal buffer
520 /// after applying the relevant formatting flags specified. The flags
521 /// recognized for generic strings are:
522 ///
523 /// * width - the minimum width of what to emit
524 /// * fill/align - what to emit and where to emit it if the string
525 /// provided needs to be padded
526 /// * precision - the maximum length to emit, the string is truncated if it
527 /// is longer than this length
528 ///
529 /// Notably this function ignored the `flag` parameters
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn pad(&mut self, s: &str) -> Result {
532 // Make sure there's a fast path up front
533 if self.width.is_none() && self.precision.is_none() {
534 return self.buf.write_str(s);
535 }
536 // The `precision` field can be interpreted as a `max-width` for the
537 // string being formatted
538 match self.precision {
539 Some(max) => {
540 // If there's a maximum width and our string is longer than
541 // that, then we must always have truncation. This is the only
542 // case where the maximum length will matter.
543 let char_len = s.char_len();
544 if char_len >= max {
545 let nchars = ::cmp::min(max, char_len);
546 return self.buf.write_str(s.slice_chars(0, nchars));
547 }
548 }
549 None => {}
550 }
551 // The `width` field is more of a `min-width` parameter at this point.
552 match self.width {
553 // If we're under the maximum length, and there's no minimum length
554 // requirements, then we can just emit the string
555 None => self.buf.write_str(s),
556 // If we're under the maximum width, check if we're over the minimum
557 // width, if so it's as easy as just emitting the string.
558 Some(width) if s.char_len() >= width => {
559 self.buf.write_str(s)
560 }
561 // If we're under both the maximum and the minimum width, then fill
562 // up the minimum width with the specified string + some alignment.
563 Some(width) => {
564 self.with_padding(width - s.char_len(), Alignment::Left, |me| {
565 me.buf.write_str(s)
566 })
567 }
568 }
569 }
570
571 /// Runs a callback, emitting the correct padding either before or
572 /// afterwards depending on whether right or left alignment is requested.
573 fn with_padding<F>(&mut self, padding: usize, default: Alignment,
574 f: F) -> Result
575 where F: FnOnce(&mut Formatter) -> Result,
576 {
577 use char::CharExt;
578 let align = match self.align {
579 Alignment::Unknown => default,
580 _ => self.align
581 };
582
583 let (pre_pad, post_pad) = match align {
584 Alignment::Left => (0, padding),
585 Alignment::Right | Alignment::Unknown => (padding, 0),
586 Alignment::Center => (padding / 2, (padding + 1) / 2),
587 };
588
589 let mut fill = [0; 4];
590 let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
591 let fill = unsafe { str::from_utf8_unchecked(&fill[..len]) };
592
593 for _ in 0..pre_pad {
594 try!(self.buf.write_str(fill));
595 }
596
597 try!(f(self));
598
599 for _ in 0..post_pad {
600 try!(self.buf.write_str(fill));
601 }
602
603 Ok(())
604 }
605
606 /// Takes the formatted parts and applies the padding.
607 /// Assumes that the caller already has rendered the parts with required precision,
608 /// so that `self.precision` can be ignored.
609 fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
610 if let Some(mut width) = self.width {
611 // for the sign-aware zero padding, we render the sign first and
612 // behave as if we had no sign from the beginning.
613 let mut formatted = formatted.clone();
614 let mut align = self.align;
615 let old_fill = self.fill;
616 if self.flags & (1 << (FlagV1::SignAwareZeroPad as u32)) != 0 {
617 // a sign always goes first
618 let sign = unsafe { str::from_utf8_unchecked(formatted.sign) };
619 try!(self.buf.write_str(sign));
620
621 // remove the sign from the formatted parts
622 formatted.sign = b"";
623 width = if width < sign.len() { 0 } else { width - sign.len() };
624 align = Alignment::Right;
625 self.fill = '0';
626 }
627
628 // remaining parts go through the ordinary padding process.
629 let len = formatted.len();
630 let ret = if width <= len { // no padding
631 self.write_formatted_parts(&formatted)
632 } else {
633 self.with_padding(width - len, align, |f| {
634 f.write_formatted_parts(&formatted)
635 })
636 };
637 self.fill = old_fill;
638 ret
639 } else {
640 // this is the common case and we take a shortcut
641 self.write_formatted_parts(formatted)
642 }
643 }
644
645 fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
646 fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
647 buf.write_str(unsafe { str::from_utf8_unchecked(s) })
648 }
649
650 if !formatted.sign.is_empty() {
651 try!(write_bytes(self.buf, formatted.sign));
652 }
653 for part in formatted.parts {
654 match *part {
655 flt2dec::Part::Zero(mut nzeroes) => {
656 const ZEROES: &'static str = // 64 zeroes
657 "0000000000000000000000000000000000000000000000000000000000000000";
658 while nzeroes > ZEROES.len() {
659 try!(self.buf.write_str(ZEROES));
660 nzeroes -= ZEROES.len();
661 }
662 if nzeroes > 0 {
663 try!(self.buf.write_str(&ZEROES[..nzeroes]));
664 }
665 }
666 flt2dec::Part::Num(mut v) => {
667 let mut s = [0; 5];
668 let len = part.len();
669 for c in s[..len].iter_mut().rev() {
670 *c = b'0' + (v % 10) as u8;
671 v /= 10;
672 }
673 try!(write_bytes(self.buf, &s[..len]));
674 }
675 flt2dec::Part::Copy(buf) => {
676 try!(write_bytes(self.buf, buf));
677 }
678 }
679 }
680 Ok(())
681 }
682
683 /// Writes some data to the underlying buffer contained within this
684 /// formatter.
685 #[stable(feature = "rust1", since = "1.0.0")]
686 pub fn write_str(&mut self, data: &str) -> Result {
687 self.buf.write_str(data)
688 }
689
690 /// Writes some formatted information into this instance
691 #[stable(feature = "rust1", since = "1.0.0")]
692 pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
693 write(self.buf, fmt)
694 }
695
696 /// Flags for formatting (packed version of rt::Flag)
697 #[stable(feature = "rust1", since = "1.0.0")]
698 pub fn flags(&self) -> u32 { self.flags }
699
700 /// Character used as 'fill' whenever there is alignment
701 #[unstable(feature = "core", reason = "method was just created")]
702 pub fn fill(&self) -> char { self.fill }
703
704 /// Flag indicating what form of alignment was requested
705 #[unstable(feature = "core", reason = "method was just created")]
706 pub fn align(&self) -> Alignment { self.align }
707
708 /// Optionally specified integer width that the output should be
709 #[unstable(feature = "core", reason = "method was just created")]
710 pub fn width(&self) -> Option<usize> { self.width }
711
712 /// Optionally specified precision for numeric types
713 #[unstable(feature = "core", reason = "method was just created")]
714 pub fn precision(&self) -> Option<usize> { self.precision }
715
716 /// Creates a `DebugStruct` builder designed to assist with creation of
717 /// `fmt::Debug` implementations for structs.
718 ///
719 /// # Examples
720 ///
721 /// ```rust
722 /// # #![feature(debug_builders, core)]
723 /// use std::fmt;
724 ///
725 /// struct Foo {
726 /// bar: i32,
727 /// baz: String,
728 /// }
729 ///
730 /// impl fmt::Debug for Foo {
731 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
732 /// fmt.debug_struct("Foo")
733 /// .field("bar", &self.bar)
734 /// .field("baz", &self.baz)
735 /// .finish()
736 /// }
737 /// }
738 ///
739 /// // prints "Foo { bar: 10, baz: "Hello World" }"
740 /// println!("{:?}", Foo { bar: 10, baz: "Hello World".to_string() });
741 /// ```
742 #[unstable(feature = "debug_builders", reason = "method was just created")]
743 #[inline]
744 pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> {
745 builders::debug_struct_new(self, name)
746 }
747
748 /// Creates a `DebugTuple` builder designed to assist with creation of
749 /// `fmt::Debug` implementations for tuple structs.
750 ///
751 /// # Examples
752 ///
753 /// ```rust
754 /// # #![feature(debug_builders, core)]
755 /// use std::fmt;
756 ///
757 /// struct Foo(i32, String);
758 ///
759 /// impl fmt::Debug for Foo {
760 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
761 /// fmt.debug_tuple("Foo")
762 /// .field(&self.0)
763 /// .field(&self.1)
764 /// .finish()
765 /// }
766 /// }
767 ///
768 /// // prints "Foo(10, "Hello World")"
769 /// println!("{:?}", Foo(10, "Hello World".to_string()));
770 /// ```
771 #[unstable(feature = "debug_builders", reason = "method was just created")]
772 #[inline]
773 pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> {
774 builders::debug_tuple_new(self, name)
775 }
776
777 /// Creates a `DebugList` builder designed to assist with creation of
778 /// `fmt::Debug` implementations for list-like structures.
779 ///
780 /// # Examples
781 ///
782 /// ```rust
783 /// # #![feature(debug_builders, core)]
784 /// use std::fmt;
785 ///
786 /// struct Foo(Vec<i32>);
787 ///
788 /// impl fmt::Debug for Foo {
789 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
790 /// self.0.iter().fold(fmt.debug_list(), |b, e| b.entry(e)).finish()
791 /// }
792 /// }
793 ///
794 /// // prints "[10, 11]"
795 /// println!("{:?}", Foo(vec![10, 11]));
796 /// ```
797 #[unstable(feature = "debug_builders", reason = "method was just created")]
798 #[inline]
799 pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> {
800 builders::debug_list_new(self)
801 }
802
803 /// Creates a `DebugSet` builder designed to assist with creation of
804 /// `fmt::Debug` implementations for set-like structures.
805 ///
806 /// # Examples
807 ///
808 /// ```rust
809 /// # #![feature(debug_builders, core)]
810 /// use std::fmt;
811 ///
812 /// struct Foo(Vec<i32>);
813 ///
814 /// impl fmt::Debug for Foo {
815 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
816 /// self.0.iter().fold(fmt.debug_set(), |b, e| b.entry(e)).finish()
817 /// }
818 /// }
819 ///
820 /// // prints "{10, 11}"
821 /// println!("{:?}", Foo(vec![10, 11]));
822 /// ```
823 #[unstable(feature = "debug_builders", reason = "method was just created")]
824 #[inline]
825 pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> {
826 builders::debug_set_new(self)
827 }
828
829 /// Creates a `DebugMap` builder designed to assist with creation of
830 /// `fmt::Debug` implementations for map-like structures.
831 ///
832 /// # Examples
833 ///
834 /// ```rust
835 /// # #![feature(debug_builders, core)]
836 /// use std::fmt;
837 ///
838 /// struct Foo(Vec<(String, i32)>);
839 ///
840 /// impl fmt::Debug for Foo {
841 /// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
842 /// self.0.iter().fold(fmt.debug_map(), |b, &(ref k, ref v)| b.entry(k, v)).finish()
843 /// }
844 /// }
845 ///
846 /// // prints "{"A": 10, "B": 11}"
847 /// println!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)]));
848 /// ```
849 #[unstable(feature = "debug_builders", reason = "method was just created")]
850 #[inline]
851 pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> {
852 builders::debug_map_new(self)
853 }
854 }
855
856 #[stable(feature = "rust1", since = "1.0.0")]
857 impl Display for Error {
858 fn fmt(&self, f: &mut Formatter) -> Result {
859 Display::fmt("an error occurred when formatting an argument", f)
860 }
861 }
862
863 // Implementations of the core formatting traits
864
865 macro_rules! fmt_refs {
866 ($($tr:ident),*) => {
867 $(
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl<'a, T: ?Sized + $tr> $tr for &'a T {
870 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
871 }
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
874 fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
875 }
876 )*
877 }
878 }
879
880 fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
881
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl Debug for bool {
884 fn fmt(&self, f: &mut Formatter) -> Result {
885 Display::fmt(self, f)
886 }
887 }
888
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl Display for bool {
891 fn fmt(&self, f: &mut Formatter) -> Result {
892 Display::fmt(if *self { "true" } else { "false" }, f)
893 }
894 }
895
896 #[stable(feature = "rust1", since = "1.0.0")]
897 impl Debug for str {
898 fn fmt(&self, f: &mut Formatter) -> Result {
899 try!(write!(f, "\""));
900 for c in self.chars().flat_map(|c| c.escape_default()) {
901 try!(write!(f, "{}", c));
902 }
903 write!(f, "\"")
904 }
905 }
906
907 #[stable(feature = "rust1", since = "1.0.0")]
908 impl Display for str {
909 fn fmt(&self, f: &mut Formatter) -> Result {
910 f.pad(self)
911 }
912 }
913
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl Debug for char {
916 fn fmt(&self, f: &mut Formatter) -> Result {
917 use char::CharExt;
918 try!(write!(f, "'"));
919 for c in self.escape_default() {
920 try!(write!(f, "{}", c));
921 }
922 write!(f, "'")
923 }
924 }
925
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl Display for char {
928 fn fmt(&self, f: &mut Formatter) -> Result {
929 let mut utf8 = [0; 4];
930 let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
931 let s: &str = unsafe { mem::transmute(&utf8[..amt]) };
932 Display::fmt(s, f)
933 }
934 }
935
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<T> Pointer for *const T {
938 fn fmt(&self, f: &mut Formatter) -> Result {
939 let old_width = f.width;
940 let old_flags = f.flags;
941
942 // The alternate flag is already treated by LowerHex as being special-
943 // it denotes whether to prefix with 0x. We use it to work out whether
944 // or not to zero extend, and then unconditionally set it to get the
945 // prefix.
946 if f.flags & 1 << (FlagV1::Alternate as u32) > 0 {
947 f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
948
949 if let None = f.width {
950 // The formats need two extra bytes, for the 0x
951 if cfg!(target_pointer_width = "32") {
952 f.width = Some(10);
953 } else {
954 f.width = Some(18);
955 }
956 }
957 }
958 f.flags |= 1 << (FlagV1::Alternate as u32);
959
960 let ret = LowerHex::fmt(&(*self as usize), f);
961
962 f.width = old_width;
963 f.flags = old_flags;
964
965 ret
966 }
967 }
968
969 #[stable(feature = "rust1", since = "1.0.0")]
970 impl<T> Pointer for *mut T {
971 fn fmt(&self, f: &mut Formatter) -> Result {
972 // FIXME(#23542) Replace with type ascription.
973 #![allow(trivial_casts)]
974 Pointer::fmt(&(*self as *const T), f)
975 }
976 }
977
978 #[stable(feature = "rust1", since = "1.0.0")]
979 impl<'a, T> Pointer for &'a T {
980 fn fmt(&self, f: &mut Formatter) -> Result {
981 // FIXME(#23542) Replace with type ascription.
982 #![allow(trivial_casts)]
983 Pointer::fmt(&(*self as *const T), f)
984 }
985 }
986
987 #[stable(feature = "rust1", since = "1.0.0")]
988 impl<'a, T> Pointer for &'a mut T {
989 fn fmt(&self, f: &mut Formatter) -> Result {
990 // FIXME(#23542) Replace with type ascription.
991 #![allow(trivial_casts)]
992 Pointer::fmt(&(&**self as *const T), f)
993 }
994 }
995
996 // Common code of floating point Debug and Display.
997 fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
998 where T: flt2dec::DecodableFloat
999 {
1000 let force_sign = fmt.flags & (1 << (FlagV1::SignPlus as u32)) != 0;
1001 let sign = match (force_sign, negative_zero) {
1002 (false, false) => flt2dec::Sign::Minus,
1003 (false, true) => flt2dec::Sign::MinusRaw,
1004 (true, false) => flt2dec::Sign::MinusPlus,
1005 (true, true) => flt2dec::Sign::MinusPlusRaw,
1006 };
1007
1008 let mut buf = [0; 1024]; // enough for f32 and f64
1009 let mut parts = [flt2dec::Part::Zero(0); 16];
1010 let formatted = if let Some(precision) = fmt.precision {
1011 flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1012 precision, false, &mut buf, &mut parts)
1013 } else {
1014 flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1015 0, false, &mut buf, &mut parts)
1016 };
1017 fmt.pad_formatted_parts(&formatted)
1018 }
1019
1020 // Common code of floating point LowerExp and UpperExp.
1021 fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
1022 where T: flt2dec::DecodableFloat
1023 {
1024 let force_sign = fmt.flags & (1 << (FlagV1::SignPlus as u32)) != 0;
1025 let sign = match force_sign {
1026 false => flt2dec::Sign::Minus,
1027 true => flt2dec::Sign::MinusPlus,
1028 };
1029
1030 let mut buf = [0; 1024]; // enough for f32 and f64
1031 let mut parts = [flt2dec::Part::Zero(0); 16];
1032 let formatted = if let Some(precision) = fmt.precision {
1033 // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
1034 flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact, *num, sign,
1035 precision + 1, upper, &mut buf, &mut parts)
1036 } else {
1037 flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest, *num, sign,
1038 (0, 0), upper, &mut buf, &mut parts)
1039 };
1040 fmt.pad_formatted_parts(&formatted)
1041 }
1042
1043 macro_rules! floating { ($ty:ident) => {
1044
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl Debug for $ty {
1047 fn fmt(&self, fmt: &mut Formatter) -> Result {
1048 float_to_decimal_common(fmt, self, true)
1049 }
1050 }
1051
1052 #[stable(feature = "rust1", since = "1.0.0")]
1053 impl Display for $ty {
1054 fn fmt(&self, fmt: &mut Formatter) -> Result {
1055 float_to_decimal_common(fmt, self, false)
1056 }
1057 }
1058
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 impl LowerExp for $ty {
1061 fn fmt(&self, fmt: &mut Formatter) -> Result {
1062 float_to_exponential_common(fmt, self, false)
1063 }
1064 }
1065
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 impl UpperExp for $ty {
1068 fn fmt(&self, fmt: &mut Formatter) -> Result {
1069 float_to_exponential_common(fmt, self, true)
1070 }
1071 }
1072 } }
1073 floating! { f32 }
1074 floating! { f64 }
1075
1076 // Implementation of Display/Debug for various core types
1077
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 impl<T> Debug for *const T {
1080 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1081 }
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 impl<T> Debug for *mut T {
1084 fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
1085 }
1086
1087 macro_rules! peel {
1088 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1089 }
1090
1091 macro_rules! tuple {
1092 () => ();
1093 ( $($name:ident,)+ ) => (
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 impl<$($name:Debug),*> Debug for ($($name,)*) {
1096 #[allow(non_snake_case, unused_assignments)]
1097 fn fmt(&self, f: &mut Formatter) -> Result {
1098 try!(write!(f, "("));
1099 let ($(ref $name,)*) = *self;
1100 let mut n = 0;
1101 $(
1102 if n > 0 {
1103 try!(write!(f, ", "));
1104 }
1105 try!(write!(f, "{:?}", *$name));
1106 n += 1;
1107 )*
1108 if n == 1 {
1109 try!(write!(f, ","));
1110 }
1111 write!(f, ")")
1112 }
1113 }
1114 peel! { $($name,)* }
1115 )
1116 }
1117
1118 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1119
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 impl<T: Debug> Debug for [T] {
1122 fn fmt(&self, f: &mut Formatter) -> Result {
1123 self.iter().fold(f.debug_list(), |b, e| b.entry(e)).finish()
1124 }
1125 }
1126
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 impl Debug for () {
1129 fn fmt(&self, f: &mut Formatter) -> Result {
1130 f.pad("()")
1131 }
1132 }
1133 impl<T> Debug for PhantomData<T> {
1134 fn fmt(&self, f: &mut Formatter) -> Result {
1135 f.pad("PhantomData")
1136 }
1137 }
1138
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 impl<T: Copy + Debug> Debug for Cell<T> {
1141 fn fmt(&self, f: &mut Formatter) -> Result {
1142 write!(f, "Cell {{ value: {:?} }}", self.get())
1143 }
1144 }
1145
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 impl<T: ?Sized + Debug> Debug for RefCell<T> {
1148 fn fmt(&self, f: &mut Formatter) -> Result {
1149 match self.borrow_state() {
1150 BorrowState::Unused | BorrowState::Reading => {
1151 write!(f, "RefCell {{ value: {:?} }}", self.borrow())
1152 }
1153 BorrowState::Writing => write!(f, "RefCell {{ <borrowed> }}"),
1154 }
1155 }
1156 }
1157
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl<'b, T: ?Sized + Debug> Debug for Ref<'b, T> {
1160 fn fmt(&self, f: &mut Formatter) -> Result {
1161 Debug::fmt(&**self, f)
1162 }
1163 }
1164
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 impl<'b, T: ?Sized + Debug> Debug for RefMut<'b, T> {
1167 fn fmt(&self, f: &mut Formatter) -> Result {
1168 Debug::fmt(&*(self.deref()), f)
1169 }
1170 }
1171
1172 // If you expected tests to be here, look instead at the run-pass/ifmt.rs test,
1173 // it's a lot easier than creating all of the rt::Piece structures here.