File: trees.rs

package info (click to toggle)
rust-pretty 0.12.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 392 kB
  • sloc: sh: 10; makefile: 2
file content (116 lines) | stat: -rw-r--r-- 3,123 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
use pretty::{BoxAllocator, DocAllocator, DocBuilder};
use std::io;
use std::str;

#[derive(Clone, Debug)]
pub struct Forest<'a>(&'a [Tree<'a>]);

impl<'a> Forest<'a> {
    fn forest(forest: &'a [Tree<'a>]) -> Forest<'a> {
        Forest(forest)
    }

    fn nil() -> Forest<'a> {
        Forest(&[])
    }

    fn bracket<'b, D, A>(&'b self, allocator: &'b D) -> DocBuilder<'b, D, A>
    where
        D: DocAllocator<'b, A>,
        D::Doc: Clone,
        A: Clone,
    {
        if (self.0).is_empty() {
            allocator.nil()
        } else {
            allocator
                .text("[")
                .append(allocator.hardline().append(self.pretty(allocator)).nest(2))
                .append(allocator.hardline())
                .append(allocator.text("]"))
        }
    }

    fn pretty<'b, D, A>(&'b self, allocator: &'b D) -> DocBuilder<'b, D, A>
    where
        D: DocAllocator<'b, A>,
        D::Doc: Clone,
        A: Clone,
    {
        let forest = self.0;
        let separator = allocator.text(",").append(allocator.hardline());
        allocator.intersperse(forest.iter().map(|tree| tree.pretty(allocator)), separator)
    }
}

#[derive(Clone, Debug)]
pub struct Tree<'a> {
    node: String,
    forest: Forest<'a>,
}

impl<'a> Tree<'a> {
    pub fn node(node: &str) -> Tree<'a> {
        Tree {
            node: node.to_string(),
            forest: Forest::nil(),
        }
    }

    pub fn node_with_forest(node: &str, forest: &'a [Tree<'a>]) -> Tree<'a> {
        Tree {
            node: node.to_string(),
            forest: Forest::forest(forest),
        }
    }

    pub fn pretty<'b, D, A>(&'b self, allocator: &'b D) -> DocBuilder<'b, D, A>
    where
        D: DocAllocator<'b, A>,
        D::Doc: Clone,
        A: Clone,
    {
        allocator
            .text(&self.node[..])
            .append((self.forest).bracket(allocator))
            .group()
    }
}

#[allow(dead_code)]
pub fn main() {
    let allocator = BoxAllocator;
    let bbbbbbs = [Tree::node("ccc"), Tree::node("dd")];
    let ffffs = [Tree::node("gg"), Tree::node("hhh"), Tree::node("ii")];
    let aaas = [
        Tree::node_with_forest("bbbbbb", &bbbbbbs),
        Tree::node("eee"),
        Tree::node_with_forest("ffff", &ffffs),
    ];
    let example = Tree::node_with_forest("aaaa", &aaas);

    let err_msg = "<buffer is not a utf-8 encoded string>";

    // try writing to stdout
    {
        print!("\nwriting to stdout directly:\n");
        let mut out = io::stdout();
        example.pretty::<_, ()>(&allocator).1.render(70, &mut out)
        // try writing to memory
    }
    .and_then(|()| {
        print!("\nwriting to string then printing:\n");
        let mut mem = Vec::new();
        example
            .pretty::<_, ()>(&allocator)
            .1
            .render(70, &mut mem)
            // print to console from memory
            .map(|()| {
                let res = str::from_utf8(&mem).unwrap_or(err_msg);
                println!("{}", res)
            })
        // print an error if anything failed
    })
    .unwrap_or_else(|err| println!("error: {}", err));
}