fastobo 0.15.5

Faultless AST for Open Biomedical Ontologies.
Documentation
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 {
    /// Create a new `Comment` from a string.
    pub fn new<S>(value: S) -> Self
    where
        S: Into<StringType>,
    {
        Comment {
            value: value.into(),
        }
    }

    /// Extracts a string slice containing the `Comment` value.
    pub fn as_str(&self) -> &str {
        &self.value
    }

    /// Retrieve the underlying string from the `Comment`.
    pub fn into_string(self) -> String {
        self.value.into()
    }

    /// Retrieve the underlying string from the `Comment`.
    pub fn into_inner(self) -> StringType {
        self.value
    }
}

impl AsRef<str> for Comment {
    fn as_ref(&self) -> &str {
        self.value.as_ref()
    }
}

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))
    }
}

impl PartialEq<str> for Comment {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<StringType> for Comment {
    fn eq(&self, other: &StringType) -> bool {
        self.as_str() == other.as_str()
    }
}

#[cfg(feature = "smartstring")]
impl PartialEq<String> for Comment {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other.as_str()
    }
}

#[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");
    }
}