to_debug/
lib.rs

1//! This crate exports the [`ToDebug`]  trait, which is an alternative to
2//! [`ToString`] that uses [`Debug`] instead of [`Display`].
3//!
4//! This can be useful for writing doctests, as it allows you to inspect
5//! the values of private fields:
6//!
7//! ```
8//! # use to_debug::ToDebug;
9//! mod private {
10//!     #[derive(Debug)]
11//!     pub struct Person { name: String, age: u16 }
12//!     // constructor boilerplate...
13//! #   impl Person {
14//! #       pub fn new(name: impl Into<String>, age: u16) -> Self {
15//! #           Self { name: name.into(), age }
16//! #       }
17//! #   }
18//! }
19//! let p = private::Person::new("Joseph", 20);
20//! // assert_eq!(p.name, "Joseph"); // This would fail since `name` is private.
21//! assert_eq!(p.to_debug(), r#"Person { name: "Joseph", age: 20 }"#);
22//! ```
23//!
24//! [`Debug`]: core::fmt::Debug
25//! [`Display`]: core::fmt::Display
26
27use std::fmt;
28/// A trait for converting a value to a `String` using the [`Debug`] trait.
29///
30/// This trait is automatically implemented for any type which implements the
31/// [`Debug`] trait. As such, `ToDebug` shouldn’t be implemented directly:
32/// [`Debug`] should be implemented instead, and you get the `ToDebug`
33/// implementation for free.
34///
35/// [`Debug`]: core::fmt::Debug
36pub trait ToDebug {
37    /// Converts the given value to a `String` using the [`Debug`] trait.
38    ///
39    /// # Examples
40    ///
41    /// ```
42    /// # use to_debug::ToDebug;
43    /// #[derive(Debug)]
44    /// struct Years(u64);
45    /// 
46    /// let y = Years(18);
47    /// assert_eq!(y.to_debug(), "Years(18)");
48    /// ```
49    ///
50    /// [`Debug`]: core::fmt::Debug
51    fn to_debug(&self) -> String;
52}
53impl<T: fmt::Debug + ?Sized> ToDebug for T {
54    #[inline]
55    fn to_debug(&self) -> String {
56        // Code shamelessly stolen from https://internals.rust-lang.org/t/to-debug-a-debug-counterpart-of-to-string/11228
57        use fmt::Write;
58        let mut buf = String::new();
59        buf.write_fmt(format_args!("{:?}", self))
60           .expect("a Debug implementation returned an error unexpectedly");
61        buf.shrink_to_fit();
62        buf
63    }
64}