Skip to main content

bed_utils/bed/
score.rs

1//! BED record score.
2
3use std::{error, fmt, str::FromStr};
4use std::ops::Deref;
5
6use bincode_next::{Decode, Encode};
7#[cfg(feature = "serde")]
8use serde::{Deserialize, Serialize};
9
10/// A BED record score.
11#[derive(Encode, Decode, Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
12#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13pub struct Score(u16);
14
15impl fmt::Display for Score {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        write!(f, "{}", self.0)
18    }
19}
20
21impl Deref for Score {
22    type Target = u16;
23    fn deref(&self) -> &Self::Target { &self.0 }
24}
25
26/// An error returned when a raw BED record score fails to parse.
27#[derive(Clone, Debug, Eq, PartialEq)]
28pub enum ParseError {
29    /// The input failed to be parsed as an integer.
30    Parse(lexical::Error),
31    /// The input is invalid.
32    Invalid(TryFromIntError),
33}
34
35impl error::Error for ParseError {}
36
37impl fmt::Display for ParseError {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        match self {
40            Self::Parse(e) => write!(f, "parse error: {}", e),
41            Self::Invalid(e) => write!(f, "invalid input: {}", e),
42        }
43    }
44}
45
46impl FromStr for Score {
47    type Err = ParseError;
48
49    fn from_str(s: &str) -> Result<Self, Self::Err> {
50        let n: u32 = lexical::parse(s).map_err(ParseError::Parse)?;
51        Self::try_from(n).map_err(ParseError::Invalid)
52    }
53}
54
55/// An error returned when a raw BED record score fails to convert.
56#[derive(Clone, Debug, Eq, PartialEq)]
57pub struct TryFromIntError(u32);
58
59impl error::Error for TryFromIntError {}
60
61impl fmt::Display for TryFromIntError {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        write!(f, "invalid value: {}", self.0)
64    }
65}
66
67impl TryFrom<u32> for Score {
68    type Error = TryFromIntError;
69
70    fn try_from(n: u32) -> Result<Self, Self::Error> {
71        u16::try_from(n)
72            .map(|n| Self(n))
73            .map_err(|_| TryFromIntError(n))
74    }
75}
76
77impl From<u16> for Score {
78    fn from(n: u16) -> Self {
79        Self(n)
80    }
81}
82
83impl From<Score> for u16 {
84    fn from(score: Score) -> Self {
85        score.0
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    #[test]
94    fn test_fmt() {
95        assert_eq!(Score(1).to_string(), "1");
96        assert_eq!(Score(1000).to_string(), "1000");
97    }
98
99    #[test]
100    fn test_try_from_u16_for_score() {
101        assert_eq!(Score::try_from(1u16), Ok(Score(1)));
102        assert_eq!(Score::try_from(1000u16), Ok(Score(1000)));
103        assert_eq!(Score::try_from(2000u16), Ok(Score(2000)));
104    }
105
106    #[test]
107    fn test_from_score_for_u16() {
108        assert_eq!(u16::from(Score(8)), 8);
109    }
110}