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