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