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