display_with_options/lib.rs
1//! # display-with-options
2//!
3//! This tiny (< 200 LOC) crate allows you to pass options around in Display and Debug.
4//!
5//! It also adds a way to indent a formatter implicitly on fresh new lines.
6//!
7//! Both components are technically separate, but interact in useful ways to provide a customizable
8//! indentation and pretty printing pipeline. In contrast to similar crates, this one gives you full
9//! control while maintaining a close relationship with rust core functionality.
10//!
11//!
12//! ## Usage Examples
13//!
14//! ### IndentingFormatter
15//!
16//! ```rust
17//! use display_with_options::IndentingFormatter;
18//!
19//! fn main() {
20//! let mut dst: Vec<u8> = vec![];
21//!
22//! writeln!(dst, "A").unwrap();
23//!
24//! let mut f = IndentingFormatter::new(&mut dst, " ");
25//! writeln!(f, "B").unwrap();
26//! }
27//! ```
28//!
29//! Result:
30//! ```text
31//! A
32//! B
33//! ```
34//!
35//! ### DisplayWithOptions
36//!
37//! ```rust
38//! use std::fmt::{Formatter, Write};
39//! use display_with_options::{DisplayWithOptions, IndentingFormatter, IndentOptions, with_options};
40//!
41//! /// Tree-like structure
42//! struct Node {
43//! name: String,
44//! children: Vec<Box<Node>>
45//! }
46//!
47//! impl Node {
48//! pub fn new(name: &str, children: Vec<Box<Node>>) -> Box<Node> {
49//! Box::new(Node {
50//! name: name.to_string(),
51//! children
52//! })
53//! }
54//! }
55//!
56//! impl<'a> DisplayWithOptions<IndentOptions<'a>> for Node {
57//! fn fmt(&self, f: &mut Formatter, options: &IndentOptions) -> std::fmt::Result {
58//! writeln!(f, "{}{}", options, self.name)?;
59//!
60//! let options = options.deeper();
61//! let mut f = IndentingFormatter::new(f, &options.full_indentation);
62//! let options = options.restart();
63//!
64//! for child in self.children.iter() {
65//! write!(f, "{}", with_options(child.as_ref(), &options))?;
66//! }
67//!
68//! Ok(())
69//! }
70//! }
71//!
72//! // Test the Code
73//!
74//! fn main() {
75//! let tree = Node::new("A", vec![
76//! Node::new("B", vec![
77//! Node::new("C", vec![]),
78//! ]),
79//! Node::new("D", vec![]),
80//! ]);
81//!
82//! let options = IndentOptions::new(" ");
83//! println!("{}", with_options(tree.as_ref(), &options));
84//! }
85//! ```
86//!
87//! Result:
88//! ```text
89//! A
90//! B
91//! C
92//! D
93//! ```
94//!
95
96
97mod debug;
98mod display;
99mod indenting_formatter;
100mod options;
101mod tests;
102
103pub use debug::DebugWithOptions;
104pub use display::DisplayWithOptions;
105pub use indenting_formatter::IndentingFormatter;
106pub use options::{with_options, IndentOptions};