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
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;

use fastobo_derive_internal::FromStr;

use crate::ast::*;
use crate::error::SyntaxError;
use crate::parser::Cache;
use crate::parser::FromPair;
use crate::syntax::pest::iterators::Pair;
use crate::syntax::Rule;

/// An inline comment without semantic value.
#[derive(Clone, Debug, Eq, FromStr, Hash, Ord, PartialEq, PartialOrd)]
pub struct Comment {
    value: StringType,
}

impl Comment {
    pub fn new<S>(value: S) -> Self
    where
        S: Into<StringType>,
    {
        Comment {
            value: value.into(),
        }
    }
}

impl Display for Comment {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f.write_str("! ").and(self.value.fmt(f)) // FIXME(@althonos): escape newlines
    }
}

impl<'i> FromPair<'i> for Comment {
    const RULE: Rule = Rule::Comment;
    unsafe fn from_pair_unchecked(
        pair: Pair<'i, Rule>,
        _cache: &Cache,
    ) -> Result<Self, SyntaxError> {
        let txt = pair
            .into_inner()
            .next()
            .unwrap()
            .as_str()
            .trim()
            .to_string();
        Ok(Comment::new(txt))
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use pretty_assertions::assert_eq;
    use std::str::FromStr;
    use std::string::ToString;

    #[test]
    fn from_str() {
        let comment = Comment::from_str("! something").unwrap();
        assert_eq!(comment, Comment::new("something"));
    }

    #[test]
    fn to_string() {
        let comment = Comment::new("something");
        assert_eq!(comment.to_string(), "! something");
    }
}