Crates.io | display_with_options |
lib.rs | display_with_options |
version | 0.1.3 |
source | src |
created_at | 2024-04-25 17:54:32.453849 |
updated_at | 2024-04-26 11:31:51.826466 |
description | Display and Debug with options passed around. Indentation functionality. |
homepage | |
repository | https://github.com/Ivorforce/display-with-options |
max_upload_size | |
id | 1220608 |
size | 15,364 |
This tiny (< 200 LOC) crate allows you to pass options around in Display and Debug.
It also adds a way to indent a formatter implicitly on fresh new lines.
Both components are technically separate, but interact in useful ways to provide a customizable indentation and pretty printing pipeline. In contrast to similar crates, this one gives you full control while maintaining a close relationship with rust core functionality.
use display_with_options::IndentingFormatter;
fn main() {
let mut dst: Vec<u8> = vec![];
writeln!(dst, "A").unwrap();
let mut f = IndentingFormatter::new(&mut dst, " ");
writeln!(f, "B").unwrap();
}
Result:
A
B
use std::fmt::{Formatter, Write};
use display_with_options::{DisplayWithOptions, IndentingFormatter, IndentOptions, with_options};
/// Tree-like structure
struct Node {
name: String,
children: Vec<Box<Node>>
}
impl Node {
pub fn new(name: &str, children: Vec<Box<Node>>) -> Box<Node> {
Box::new(Node {
name: name.to_string(),
children
})
}
}
impl<'a> DisplayWithOptions<IndentOptions<'a>> for Node {
fn fmt(&self, f: &mut Formatter, options: &IndentOptions) -> std::fmt::Result {
writeln!(f, "{}{}", options, self.name)?;
let options = options.deeper();
let mut f = IndentingFormatter::new(f, &options.full_indentation);
let options = options.restart();
for child in self.children.iter() {
write!(f, "{}", with_options(child.as_ref(), &options))?;
}
Ok(())
}
}
// Test the Code
fn main() {
let tree = Node::new("A", vec![
Node::new("B", vec![
Node::new("C", vec![]),
]),
Node::new("D", vec![]),
]);
let options = IndentOptions::new(" ");
println!("{}", with_options(tree.as_ref(), &options));
}
Result:
A
B
C
D