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
//! FASTA record definition and components.

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

const PREFIX: char = '>';

/// A FASTA record definition.
///
/// A definition represents a definition line, i.e, a reference sequence name and, optionally, a
/// description.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Definition {
    name: Vec<u8>,
    description: Option<Vec<u8>>,
}

impl Definition {
    /// Creates a FASTA record definition.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_fasta::record::Definition;
    /// let definition = Definition::new("sq0", None);
    /// ```
    pub fn new<N>(name: N, description: Option<Vec<u8>>) -> Self
    where
        N: Into<Vec<u8>>,
    {
        Self {
            name: name.into(),
            description,
        }
    }

    /// Returns the record name.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_fasta::record::Definition;
    /// let definition = Definition::new("sq0", None);
    /// assert_eq!(definition.name(), b"sq0");
    /// ```
    pub fn name(&self) -> &[u8] {
        &self.name
    }

    /// Returns the description if it is set.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_fasta::record::Definition;
    ///
    /// let definition = Definition::new("sq0", None);
    /// assert_eq!(definition.description(), None);
    ///
    /// let definition = Definition::new("sq0", Some(Vec::from("LN:13")));
    /// assert_eq!(definition.description(), Some(&b"LN:13"[..]));
    /// ```
    pub fn description(&self) -> Option<&[u8]> {
        self.description.as_deref()
    }
}

impl fmt::Display for Definition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = str::from_utf8(self.name()).map_err(|_| fmt::Error)?;
        write!(f, "{PREFIX}{name}")?;

        if let Some(buf) = self.description() {
            let description = str::from_utf8(buf).map_err(|_| fmt::Error)?;
            write!(f, " {description}")?;
        }

        Ok(())
    }
}

/// An error returned when a raw record definition fails to parse.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ParseError {
    /// The input is empty.
    Empty,
    /// The prefix (`>`) is missing.
    MissingPrefix,
    /// The sequence name is missing.
    MissingName,
}

impl error::Error for ParseError {}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => f.write_str("empty input"),
            Self::MissingPrefix => write!(f, "missing prefix ('{PREFIX}')"),
            Self::MissingName => f.write_str("missing name"),
        }
    }
}

impl FromStr for Definition {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            return Err(ParseError::Empty);
        } else if !s.starts_with(PREFIX) {
            return Err(ParseError::MissingPrefix);
        }

        let line = &s[1..];
        let mut components = line.splitn(2, |c: char| c.is_ascii_whitespace());

        let name = components
            .next()
            .and_then(|s| if s.is_empty() { None } else { Some(s.into()) })
            .ok_or(ParseError::MissingName)?;

        let description = components.next().map(|s| s.trim().into());

        Ok(Self { name, description })
    }
}

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

    #[test]
    fn test_fmt() {
        let definition = Definition::new("sq0", None);
        assert_eq!(definition.to_string(), ">sq0");

        let definition = Definition::new("sq0", Some(Vec::from("LN:13")));
        assert_eq!(definition.to_string(), ">sq0 LN:13");
    }

    #[test]
    fn test_from_str() {
        assert_eq!(">sq0".parse(), Ok(Definition::new("sq0", None)));

        assert_eq!(
            ">sq0  LN:13".parse(),
            Ok(Definition::new("sq0", Some(Vec::from("LN:13"))))
        );

        assert_eq!("".parse::<Definition>(), Err(ParseError::Empty));
        assert_eq!("sq0".parse::<Definition>(), Err(ParseError::MissingPrefix));
        assert_eq!(">".parse::<Definition>(), Err(ParseError::MissingName));
    }
}