#display #debugging #indentation #indent #pretty

display_with_options

使用选项进行显示和调试。缩进功能。

4 个版本

0.1.3 2024年4月26日
0.1.2 2024年4月25日
0.1.1 2024年4月25日
0.1.0 2024年4月25日

开发工具 中排名第 556

每月下载量 49

MIT 许可证

14KB
184

display_with_options

这个小型(< 200 LOC)crate 允许你在 Display 和 Debug 中传递选项。

它还提供了一种方法,在新的空白行上隐式缩进格式化器。

这两个组件在技术上都是独立的,但以有用的方式交互,提供可定制的缩进和美观打印流程。与类似的 crate 相比,这个提供了对 rust 核心功能的完全控制,同时保持紧密的关系。

使用示例

缩进格式化器

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();
}

结果

A
    B

DisplayWithOptions

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));
}

结果

A
    B
        C
    D

无运行时依赖