File: custom_formatter_user.rs

package info (click to toggle)
rust-comrak 0.41.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,016 kB
  • sloc: sh: 5; makefile: 2
file content (47 lines) | stat: -rw-r--r-- 1,349 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
use comrak::html::ChildRendering;
use comrak::{create_formatter, nodes::NodeValue};
use std::io::Write;

create_formatter!(CustomFormatter<usize>, {
    NodeValue::Emph => |context, entering| {
        context.user += 1;
        if entering {
            context.write_all(b"<i>")?;
        } else {
            context.write_all(b"</i>")?;
        }
    },
    NodeValue::Strong => |context, entering| {
        context.user += 1;
        context.write_all(if entering { b"<b>" } else { b"</b>" })?;
    },
    NodeValue::Image(ref nl) => |context, node, entering| {
        assert!(node.data.borrow().sourcepos == (3, 1, 3, 18).into());
        if entering {
            context.write_all(nl.url.to_uppercase().as_bytes())?;
        }
        return Ok(ChildRendering::Skip);
    },
});

fn main() {
    use comrak::{parse_document, Arena, Options};

    let options = Options::default();
    let arena = Arena::new();
    let doc = parse_document(
        &arena,
        "_Hello_, **world**.\n\n![title](/img.png)",
        &options,
    );

    let mut buf: Vec<u8> = vec![];
    let converted_count = CustomFormatter::format_document(doc, &options, &mut buf, 0).unwrap();

    assert_eq!(
        std::str::from_utf8(&buf).unwrap(),
        "<p><i>Hello</i>, <b>world</b>.</p>\n<p>/IMG.PNG</p>\n"
    );

    assert_eq!(converted_count, 4);
}