3 releases

Uses old Rust 2015

0.1.2 Mar 16, 2018
0.1.1 Mar 12, 2018
0.1.0 Mar 11, 2018

#21 in #pretty

MIT license

25KB
288 lines

pretty-trait

pretty-trait is a simple trait-based pretty-printing library for Rust.

Package information is available at crates.io.

You can find official documentation at docs.rs.


lib.rs:

pretty-trait is a simple trait-based library for producing pretty debug output. It is intended to make it easy to render large tree-like structures (such as program syntax trees) in such a way that long items are broken across multiple lines and indented.

The core feature of this crate is the Pretty trait, which represents types that can be pretty-printed. This crate provides a number of built-in types implementing Pretty, which be combined to implement a wide variety of formatting and layout strategies. For many purposes, you will not need to implement Pretty for your own types, but can instead convert your type into a structure composed out of these built-in types.

Examples

Converting a custom type to built-in Pretty types:

use pretty_trait::{Pretty, JoinExt, Group, Indent, Sep, delimited, Conditional, to_string, block};

enum NestList {
    Atom(i32),
    List(Vec<NestList>),
}

fn to_pretty(nest_list: &NestList) -> Box<Pretty> {
    match nest_list {
        &NestList::Atom(val) => Box::new(val.to_string()),
        &NestList::List(ref children) => {
            Box::new(Group::new(
                "["
                    .join(block(
                        delimited(&",".join(Sep(1)), children.iter().map(to_pretty))
                            .join(Conditional::OnlyBroken(",")),
                    )).join("]"),
            ))
        }
    }
}

let max_line = Some(40);
let tab_size = 4;

let small_list = NestList::List(vec![NestList::Atom(1), NestList::Atom(2), NestList::Atom(3)]);
assert_eq!(to_string(&to_pretty(&small_list), max_line, tab_size), "[1, 2, 3]");

let large_list = NestList::List(vec![
    NestList::List(vec![
        NestList::Atom(1),
        NestList::Atom(2),
        NestList::Atom(3),
        NestList::Atom(4),
        NestList::Atom(5),
    ]),
    NestList::List(vec![
        NestList::Atom(6),
        NestList::Atom(7),
        NestList::Atom(8),
        NestList::Atom(9),
        NestList::Atom(10),
    ]),
    NestList::List(vec![
        NestList::List(vec![NestList::Atom(11), NestList::Atom(12), NestList::Atom(13)]),
        NestList::List(vec![NestList::Atom(14), NestList::Atom(15), NestList::Atom(16)]),
    ]),
]);
let expected = "\
[
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [[11, 12, 13], [14, 15, 16]],
]";
assert_eq!(to_string(&to_pretty(&large_list), max_line, tab_size), expected);

No runtime deps