org_rust_parser/element/
comment.rs1use crate::constants::NEWLINE;
2use crate::node_pool::NodeID;
3use crate::types::{Cursor, ParseOpts, Parseable, Parser, Result};
4use crate::utils::bytes_to_str;
5
6#[derive(Debug, Clone, Copy)]
7pub struct Comment<'a>(pub &'a str);
8
9impl<'a> Parseable<'a> for Comment<'a> {
10 fn parse(
11 parser: &mut Parser<'a>,
12 mut cursor: Cursor<'a>,
13 parent: Option<NodeID>,
14 parse_opts: ParseOpts,
15 ) -> Result<NodeID> {
16 let start = cursor.index;
17 if cursor.peek(1)?.is_ascii_whitespace() {
18 let prev = cursor.index;
19 cursor.adv_till_byte(NEWLINE);
20 let val = bytes_to_str(&cursor.byte_arr[(prev + 2)..cursor.index]);
21 Ok(parser.alloc(Self(val), start, cursor.index + 1, parent))
24 } else {
25 Err(crate::types::MatchError::InvalidLogic)
26 }
27 }
28}
29
30#[cfg(test)]
31mod tests {
32 use crate::types::Expr;
33 use crate::{expr_in_pool, parse_org};
34
35 #[test]
36 fn basic_comment() {
37 let inp = "# this is a comment\n";
38
39 let parsed = parse_org(inp);
40
41 let l = expr_in_pool!(parsed, Comment).unwrap();
42 assert_eq!(l.0, "this is a comment")
43 }
44
45 #[test]
46 fn comment_eof() {
47 let inp = "# this is a comment";
48
49 let parsed = parse_org(inp);
50
51 let l = expr_in_pool!(parsed, Comment).unwrap();
52 assert_eq!(l.0, "this is a comment")
53 }
54
55 #[test]
56 fn basic_comment_not() {
57 let inp = "#this is not a comment";
58 let parsed = parse_org(inp);
59 let c = expr_in_pool!(parsed, Comment);
60 assert!(c.is_none());
61 }
62}