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
|
use regex::Regex;
#[derive(PartialOrd, Ord, PartialEq, Eq, Clone, Copy, Debug)]
pub enum Org<'a> {
Unknown,
Header(u16, &'a str),
}
#[derive(PartialOrd, Ord, PartialEq, Eq, Clone, Debug)]
pub struct OrgNode<'a> {
pub raw: &'a str,
pub e: Org<'a>,
}
type OrgDocument<'a> = Vec<OrgNode<'a>>;
struct Parser<'a> {
doc: OrgDocument<'a>
}
impl<'a> Parser<'a> {
fn parse_line(&mut self, line: &'a str) {
lazy_static! {
static ref header: Regex = Regex::new(r"(\*)+ (.*)").unwrap();
}
if let Some(g) = header.captures(line) {
self.doc.push(OrgNode {
raw: line,
e: Org::Header(
g.get(1).unwrap().as_str().len() as u16,
g.get(2).unwrap().as_str()
)});
} else {
self.doc.push(OrgNode {
raw: line,
e: Org::Unknown
});
}
}
pub fn parse(input: &'a str) -> OrgDocument<'a> {
let mut parser = Parser{doc: vec!()};
for line in input.split('\n') {
parser.parse_line(line);
}
parser.doc
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_unknown() {
let doc = "hello\nhello";
assert_eq!(Parser::parse(doc),
vec!(OrgNode {
raw: "hello",
e: Org::Unknown
}, OrgNode {
raw: "hello",
e: Org::Unknown
}));
}
#[test]
fn parse_header() {
let doc = "* hello";
assert_eq!(Parser::parse(doc),
vec!(OrgNode {
raw: doc,
e: Org::Header(1, "hello")
}));
}
}
|