1use std::{error, fmt, str::FromStr};
4use std::ops::Deref;
5
6use bincode::{Decode, Encode};
7#[cfg(feature = "serde")]
8use serde::{Deserialize, Serialize};
9
10#[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#[derive(Clone, Debug, Eq, PartialEq)]
28pub enum ParseError {
29 Parse(lexical::Error),
31 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 Ok(Self::try_from(n).unwrap_or(Score(1000)))
52 }
54}
55
56#[derive(Clone, Debug, Eq, PartialEq)]
58pub struct TryFromIntError(u32);
59
60impl error::Error for TryFromIntError {}
61
62impl fmt::Display for TryFromIntError {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "invalid value: {}", self.0)
65 }
66}
67
68impl TryFrom<u32> for Score {
69 type Error = TryFromIntError;
70
71 fn try_from(n: u32) -> Result<Self, Self::Error> {
72 if n > 1000 {
73 Err(TryFromIntError(n))
74 } else {
75 Ok(Self(n as u16))
76 }
77 }
78}
79
80impl TryFrom<u16> for Score {
81 type Error = TryFromIntError;
82
83 fn try_from(n: u16) -> Result<Self, Self::Error> {
84 Self::try_from(n as u32)
85 }
86}
87
88impl From<Score> for u16 {
89 fn from(score: Score) -> Self {
90 score.0
91 }
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97
98 #[test]
99 fn test_fmt() {
100 assert_eq!(Score(1).to_string(), "1");
101 assert_eq!(Score(1000).to_string(), "1000");
102 }
103
104 #[test]
105 fn test_try_from_u16_for_score() {
106 assert_eq!(Score::try_from(1u16), Ok(Score(1)));
107 assert_eq!(Score::try_from(1000u16), Ok(Score(1000)));
108 }
109
110 #[test]
111 fn test_from_score_for_u16() {
112 assert_eq!(u16::from(Score(8)), 8);
113 }
114}