Rust文本树结构处理库text_trees的使用,高效构建和操作树形文本数据结构

Rust文本树结构处理库text_trees的使用,高效构建和操作树形文本数据结构

text_trees是一个用于输出树形结构的简单文本库。它类似于现有的ascii_tree crate,但在格式化选项上更加灵活。

示例

以下示例展示了如何使用with_child_nodeswith_children方法来构建一个StringTreeNode树结构:

use text_trees::StringTreeNode;

// 构建树结构的函数
fn make_tree() -> StringTreeNode {
    // 使用with_child_nodes创建根节点和子节点
    StringTreeNode::with_child_nodes(
        "root".to_string(),  // 根节点文本
        vec![
            // 第一个子节点(简单节点)
            "Uncle".into(),
            // 第二个子节点(包含孙子节点的复杂节点)
            StringTreeNode::with_child_nodes(
                "Parent".to_string(),
                vec![
                    // 第一个孙子节点
                    StringTreeNode::with_children(
                        "Child 1".to_string(),
                        vec!["Grand Child 1".into()].into_iter(),
                    ),
                    // 第二个孙子节点(包含多级子节点)
                    StringTreeNode::with_child_nodes(
                        "Child 2".to_string(),
                        vec![StringTreeNode::with_child_nodes(
                            "Grand Child 2".to_string(),
                            vec![StringTreeNode::with_children(
                                "Great Grand Child 2".to_string(),
                                vec!["Great Great Grand Child 2".to_string()].into_iter(),
                            )]
                            .into_iter(),
                        )]
                        .into_iter(),
                    ),
                ]
                .into_iter(),
            ),
            // 第三个子节点
            StringTreeNode::with_children(
                "Aunt".to_string(),
                vec!["Child 3".to_string()].into_iter(),
            ),
        ]
        .into_iter(),
    )
}

树结构实现了Display特性,因此提供了to_string方法。它还有一个to_string_with_format方法,允许自定义输出格式。

use text_trees::{FormatCharacters, TreeFormatting, TreeNode};

// 使用ASCII格式输出树的函数
fn ascii_tree(tree: TreeNode<String>) {
    // 创建ASCII格式的树形格式化选项
    let result = tree.to_string_with_format(
        &TreeFormatting::dir_tree(FormatCharacters::ascii())
    );
    assert!(result.is_ok());

    // 可以在这里处理结果或做其他操作
}

这将生成如下树形文本表示:

root
+-- Uncle
+-- Parent
|   +-- Child 1
|   |   '-- Grand Child 1
|   '-- Child 2
|       '-- Grand Child 2
|           '-- Great Grand Child 2
|               '-- Great Great Grand Child 2
'-- Aunt
    '-- Child 3

完整示例代码

use text_trees::{StringTreeNode, FormatCharacters, TreeFormatting};

fn main() {
    // 创建树结构
    let tree = make_tree();
    
    // 使用默认格式输出树
    println!("默认树格式:");
    println!("{}", tree);
    
    // 使用ASCII格式输出树
    println!("\nASCII树格式:");
    let format = TreeFormatting::dir_tree(FormatCharacters::ascii());
    match tree.to_string_with_format(&format) {
        Ok(s) => println!("{}", s),
        Err(e) => println!("错误: {}", e),
    }
}

// 构建树结构的函数
fn make_tree() -> StringTreeNode {
    StringTreeNode::with_child_nodes(
        "root".to_string(),
        vec![
            "Uncle".into(),
            StringTreeNode::with_child_nodes(
                "Parent".to_string(),
                vec![
                    StringTreeNode::with_children(
                        "Child 1".to_string(),
                        vec!["Grand Child 1".into()].into_iter(),
                    ),
                    StringTreeNode::with_child_nodes(
                        "Child 2".to_string(),
                        vec![StringTreeNode::with_child_nodes(
                            "Grand Child 2".to_string(),
                            vec![StringTreeNode::with_children(
                                "Great Grand Child 2".to_string(),
                                vec!["Great Great Grand Child 2".to_string()].into_iter(),
                            )]
                            .into_iter(),
                        )]
                        .into_iter(),
                    ),
                ]
                .into_iter(),
            ),
            StringTreeNode::with_children(
                "Aunt".to_string(),
                vec!["Child 3".to_string()].into_iter(),
            ),
        ]
        .into_iter(),
    )
}

版本变更

版本0.1.2

  • 仅文档变更

版本0.1.1

  • 修复了自上而下、底部锚定树中缺少间距的错误
  • 更新了所有示例以匹配树输出变化
  • 添加了tls树-ls示例

版本0.1.0

  • 初始版本,仅支持目录样式树

1 回复

Rust文本树结构处理库text_trees的使用

主要特性

  • 简单直观的API设计
  • 支持多级嵌套的树形结构
  • 可自定义节点格式和连接符号
  • 高效的内存管理
  • 支持树结构的动态修改

基本使用方法

添加依赖

[dependencies]
text_trees = "0.3.0"

构建简单树结构

use text_trees::TreeNode;

fn main() {
    // 创建根节点
    let mut root = TreeNode::new("Root");
    
    // 添加子节点
    root.push("Child 1");
    root.push("Child 2");
    
    // 构建子树
    let mut subtree = TreeNode::new("Subtree");
    subtree.push("Subchild 1");
    subtree.push("Subchild 2");
    
    // 将子树添加到根节点
    root.push(subtree);
    
    // 打印树结构
    println!("{}", root);
}

输出:

Root
├── Child 1
├── Child 2
└── Subtree
    ├── Subchild 1
    └── Subchild 2

自定义格式

use text_trees::{TreeNode, FormatCharacters};

fn main() {
    let mut root = TreeNode::new_with_format(
        "Root",
        FormatCharacters::boxed(), // 使用方框样式
    );
    
    root.push("Child 1");
    root.push("Child 2");
    
    println!("{}", root);
}

输出:

Root
├─ Child 1
└─ Child 2

动态构建树

use text_trees::TreeNode;

fn build_tree(depth: usize) -> TreeNode<String> {
    let mut node = TreeNode::new(format!("Level {}", depth));
    
    if depth > 0 {
        for i in 1..=3 {
            node.push(build_tree(depth - 1));
        }
    }
    
    node
}

fn main() {
    let tree = build_tree(2);
    println!("{}", tree);
}

输出:

Level 2
├── Level 1
│   ├── Level 0
│   ├── Level 0
│   └── Level 0
├── Level 1
│   ├── Level 0
│   ├── Level 0
│   └── Level 0
└── Level 1
    ├── Level 0
    ├── Level 0
    └── Level 0

高级用法

遍历树节点

use text_trees::TreeNode;

fn main() {
    let mut root = TreeNode::new("Root");
    root.push("Child 1");
    root.push("Child 2");
    
    // 前序遍历
    println!("Pre-order traversal:");
    root.visit_pre_order(|node, depth| {
        println!("{}{}", "  ".repeat(depth), node.data());
    });
}

修改树结构

use text_trees::TreeNode;

fn main() {
    let mut root = TreeNode::new("Root");
    root.push("Old Child");
    
    // 修改节点数据
    if let Some(child) = root.get_child_mut(0) {
        *child.data_mut() = "New Child".to_string();
    }
    
    // 删除节点
    root.remove_child(0);
    
    println!("{}", root);
}

完整示例demo

use text_trees::{TreeNode, FormatCharacters};

fn main() {
    // 示例1: 基本树构建
    println!("=== 基本树结构示例 ===");
    let mut basic_tree = TreeNode::new("公司组织架构");
    basic_tree.push("技术部")
             .push("产品部")
             .push("市场部");
    
    // 添加技术部的子部门
    if let Some(tech_dept) = basic_tree.get_child_mut(0) {
        tech_dept.push("前端组")
                 .push("后端组")
                 .push("测试组");
    }
    
    println!("{}", basic_tree);

    // 示例2: 自定义格式
    println!("\n=== 自定义格式示例 ===");
    let mut custom_tree = TreeNode::new_with_format(
        "项目结构",
        FormatCharacters::boxed()
    );
    custom_tree.push("src")
               .push("tests")
               .push("docs");
    
    println!("{}", custom_tree);

    // 示例3: 文件系统模拟
    println!("\n=== 文件系统模拟 ===");
    let mut fs_tree = TreeNode::new("/");
    let mut home = TreeNode::new("home");
    home.push("user1")
        .push("user2");
    
    let mut etc = TreeNode::new("etc");
    etc.push("nginx")
       .push("redis");
    
    fs_tree.push(home)
           .push(etc)
           .push("var");
    
    println!("{}", fs_tree);

    // 示例4: 树遍历
    println!("\n=== 树遍历示例 ===");
    println!("前序遍历结果:");
    fs_tree.visit_pre_order(|node, depth| {
        println!("{}[{}] {}", "  ".repeat(depth), depth, node.data());
    });
}

输出结果:

=== 基本树结构示例 ===
公司组织架构
├── 技术部
│   ├── 前端组
│   ├── 后端组
│   └── 测试组
├── 产品部
└── 市场部

=== 自定义格式示例 ===
项目结构
├─ src
├─ tests
└─ docs

=== 文件系统模拟 ===
/
├── home
│   ├── user1
│   └── user2
├── etc
│   ├── nginx
│   └── redis
└── var

=== 树遍历示例 ===
前序遍历结果:
[0] /
  [1] home
    [2] user1
    [2] user2
  [1] etc
    [2] nginx
    [2] redis
  [1] var
回到顶部