noodles_gtf/record/
attributes.rs

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
//! GTF record attributes.

pub mod entry;

pub use self::entry::Entry;

use std::{
    error,
    fmt::{self, Write},
    str::FromStr,
};

const DELIMITER: char = ' ';

/// GTF record attributes.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Attributes(Vec<Entry>);

impl Attributes {
    /// Returns whether there are any entries.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_gtf::record::Attributes;
    /// let attributes = Attributes::default();
    /// assert!(attributes.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the number of entries.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_gtf::record::Attributes;
    /// let attributes = Attributes::default();
    /// assert_eq!(attributes.len(), 0);
    /// ```
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns the value at the given key.
    ///
    /// This returns the first match of the key.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_gtf::record::{attributes::Entry, Attributes};
    /// let attributes = Attributes::from(vec![Entry::new("id", "g0")]);
    /// assert_eq!(attributes.get("id"), Some("g0"));
    /// assert!(attributes.get("source").is_none());
    /// ```
    pub fn get<'a>(&'a self, key: &str) -> Option<&'a str> {
        self.0
            .iter()
            .find(|entry| entry.key() == key)
            .map(|entry| entry.value())
    }
}

impl AsRef<[Entry]> for Attributes {
    fn as_ref(&self) -> &[Entry] {
        &self.0
    }
}

impl From<Vec<Entry>> for Attributes {
    fn from(entries: Vec<Entry>) -> Self {
        Self(entries)
    }
}

impl fmt::Display for Attributes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, entry) in self.0.iter().enumerate() {
            write!(f, "{entry}")?;

            f.write_char(entry::DELIMITER)?;

            if i < self.0.len() - 1 {
                f.write_char(DELIMITER)?;
            }
        }

        Ok(())
    }
}

/// An error returned when raw GTF attributes fail to parse.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParseError {
    /// The input is empty.
    Empty,
    /// The input is invalid.
    Invalid,
    /// The input has an invalid entry.
    InvalidEntry(entry::ParseError),
}

impl error::Error for ParseError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Self::InvalidEntry(e) => Some(e),
            _ => None,
        }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "empty input"),
            Self::Invalid => write!(f, "invalid input"),
            Self::InvalidEntry(_) => write!(f, "invalid entry"),
        }
    }
}

impl FromStr for Attributes {
    type Err = ParseError;

    fn from_str(mut s: &str) -> Result<Self, Self::Err> {
        use self::entry::parse_entry;

        if s.is_empty() {
            return Err(ParseError::Empty);
        }

        let mut entries = Vec::new();

        while !s.is_empty() {
            let entry = parse_entry(&mut s).map_err(ParseError::InvalidEntry)?;
            entries.push(entry);
        }

        Ok(Self(entries))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_fmt() {
        let attributes = Attributes::from(vec![Entry::new("gene_id", "g0")]);
        assert_eq!(attributes.to_string(), r#"gene_id "g0";"#);

        let attributes = Attributes::from(vec![
            Entry::new("gene_id", "g0"),
            Entry::new("transcript_id", "t0"),
        ]);
        assert_eq!(
            attributes.to_string(),
            r#"gene_id "g0"; transcript_id "t0";"#
        );
    }

    #[test]
    fn test_from_str() {
        assert_eq!(
            r#"gene_id "g0";"#.parse(),
            Ok(Attributes::from(vec![Entry::new("gene_id", "g0")]))
        );

        assert_eq!(
            r#"gene_id "g0""#.parse::<Attributes>(),
            Ok(Attributes::from(vec![Entry::new("gene_id", "g0")]))
        );

        assert_eq!(
            r#"gene_id "g0"; transcript_id "t0";"#.parse(),
            Ok(Attributes::from(vec![
                Entry::new("gene_id", "g0"),
                Entry::new("transcript_id", "t0")
            ]))
        );

        assert_eq!(
            r#"gene_id "g0";transcript_id "t0";"#.parse::<Attributes>(),
            Ok(Attributes::from(vec![
                Entry::new("gene_id", "g0"),
                Entry::new("transcript_id", "t0")
            ]))
        );

        assert_eq!(
            r#"gene_id "g0";  transcript_id "t0";"#.parse::<Attributes>(),
            Ok(Attributes::from(vec![
                Entry::new("gene_id", "g0"),
                Entry::new("transcript_id", "t0")
            ]))
        );

        assert_eq!("".parse::<Attributes>(), Err(ParseError::Empty));
        assert!(matches!(
            r#";"#.parse::<Attributes>(),
            Err(ParseError::InvalidEntry(_))
        ));
    }
}