bed_utils/bed/
strand.rs

1//! BED record feature strand.
2
3use std::{error, fmt, str::FromStr};
4
5use bincode::{Decode, Encode};
6
7/// A BED record feature strand.
8#[derive(Encode, Decode, Clone, Copy, Debug, Eq, PartialEq)]
9pub enum Strand {
10    /// Forward (sense or coding) strand (`+`).
11    Forward,
12    /// Reverse (antisense or complementary) strand (`-`).
13    Reverse,
14}
15
16impl AsRef<str> for Strand {
17    fn as_ref(&self) -> &str {
18        match self {
19            Self::Forward => "+",
20            Self::Reverse => "-",
21        }
22    }
23}
24
25impl fmt::Display for Strand {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        f.write_str(self.as_ref())
28    }
29}
30
31/// An error returned when a raw BED record strand fails to parse.
32#[derive(Clone, Debug, Eq, PartialEq)]
33pub enum ParseError {
34    /// The input is empty.
35    Empty,
36    /// The input is invalid.
37    Invalid,
38}
39
40impl error::Error for ParseError {}
41
42impl fmt::Display for ParseError {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        match self {
45            Self::Empty => f.write_str("empty input"),
46            Self::Invalid => f.write_str("invalid input"),
47        }
48    }
49}
50
51impl FromStr for Strand {
52    type Err = ParseError;
53
54    fn from_str(s: &str) -> Result<Self, Self::Err> {
55        match s {
56            "" => Err(ParseError::Empty),
57            "+" => Ok(Self::Forward),
58            "-" => Ok(Self::Reverse),
59            _ => Err(ParseError::Invalid),
60        }
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn test_fmt() {
70        assert_eq!(Strand::Forward.to_string(), "+");
71        assert_eq!(Strand::Reverse.to_string(), "-");
72    }
73
74    #[test]
75    fn test_from_str() {
76        assert_eq!("+".parse(), Ok(Strand::Forward));
77        assert_eq!("-".parse(), Ok(Strand::Reverse));
78
79        assert_eq!("".parse::<Strand>(), Err(ParseError::Empty));
80        assert_eq!("ndls".parse::<Strand>(), Err(ParseError::Invalid));
81    }
82}