debug3
A space effiecent replacement for [std::fmt::Debug
]
The Pitch
Lets say you have data that looks like this:
let complex_structure = vec!;
And you want to format it as a string. You could use format!("{:?}", complex_structure)
and get something like
But this is too much one one line, and is hard to read. And it gets worse for larger structures.
Fortunaly theirs an alternative format!("{:#?}", complex_structure)
, which gives
This has the oposite problem, where it uses too much space, even when the code could be packed denser.
debug3
provides a third option that is denser than :#?
but more readable than :?
. If you use debug3::pprint(complex_structure)
, you get
Overview
The main entrypoint is the [Debug
] trait, which is the equivalent to [std::fmt::Debug
], and has a similar API.
This can be either #[derive]
d, or implemented manually.
use ;
assert_eq!;
assert_eq!;
Once your type implements [Debug
], you have several options to format it
- [
pprint
]: Convert it to a [String
] - [
dbg
]: Print it to stderr
Comparison to std::fmt::Debug
:
While the main advantage of debug3
is the superior output quality, it has several drawbacks compared to [std::fmt
] that you should know
- Commonness: Virtually every type in Rust implements [
std::fmt::Debug
], vitrualy no types outside of [std
] implement [debug3::Debug
][Debug
]. - Availibility: [
std::fmt
] is also availible as [core::fmt
], which allows you to use it inno_std
environments.debug3
requires several allocated data structures, so cannot support these environments. - Versitility: [
std::fmt::Formatter
] has many more API's for implementing [std::fmt::Debug
]. In order to achive nice formatting, we cannot accept arbitrary strings, but must have items in the form of Structs, Tuples, Maps, Lists and Sets. - Configurabiliy: We dont suport stuff like
format!("{:x?}, 1)
to configure how numbers are printed. - Ease of use: We don't have a macro like [
std::format
] to easily create a string from several elements which implement [Debug
]
Prior Art
debug3
would not be possible without all of the following excelent work
core::fmt
- The public API of [Formatter
] and[builders]
prettyplease
- Most of the prety printing algorithm is lifted directly from this cratecustom_debug
- The derive macro for [Debug
] is based on this crate.- python's
pprint
- Inspiration for this type of formatting for debug output.