forked from apezord/ord-dogecoin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrarity.rs
114 lines (101 loc) Β· 2.46 KB
/
rarity.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
use super::*;
#[derive(Debug, PartialEq, PartialOrd)]
pub enum Rarity {
Common,
Uncommon,
Rare,
Epic,
Legendary,
Mythic,
}
impl Display for Rarity {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::Common => "common",
Self::Uncommon => "uncommon",
Self::Rare => "rare",
Self::Epic => "epic",
Self::Legendary => "legendary",
Self::Mythic => "mythic",
}
)
}
}
impl From<Sat> for Rarity {
fn from(sat: Sat) -> Self {
if sat.0 == 0 {
return Self::Mythic;
} else if sat == sat.epoch().starting_sat() {
return Self::Legendary;
} else if !sat.is_common() {
return Self::Uncommon;
} else {
return Self::Common;
}
}
}
impl FromStr for Rarity {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"common" => Ok(Self::Common),
"uncommon" => Ok(Self::Uncommon),
"rare" => Ok(Self::Rare),
"epic" => Ok(Self::Epic),
"legendary" => Ok(Self::Legendary),
"mythic" => Ok(Self::Mythic),
_ => Err(anyhow!("invalid rarity: {s}")),
}
}
}
impl Serialize for Rarity {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Rarity {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(DeserializeFromStr::deserialize(deserializer)?.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rarity() {
assert_eq!(Sat(0).rarity(), Rarity::Mythic);
assert_eq!(Sat(1).rarity(), Rarity::Common);
}
#[test]
fn from_str_and_deserialize_ok() {
#[track_caller]
fn case(s: &str, expected: Rarity) {
let actual = s.parse::<Rarity>().unwrap();
assert_eq!(actual, expected);
let round_trip = actual.to_string().parse::<Rarity>().unwrap();
assert_eq!(round_trip, expected);
let serialized = serde_json::to_string(&expected).unwrap();
assert!(serde_json::from_str::<Rarity>(&serialized).is_ok());
}
case("common", Rarity::Common);
case("uncommon", Rarity::Uncommon);
case("rare", Rarity::Rare);
case("epic", Rarity::Epic);
case("legendary", Rarity::Legendary);
case("mythic", Rarity::Mythic);
}
#[test]
fn from_str_err() {
"abc".parse::<Rarity>().unwrap_err();
"".parse::<Rarity>().unwrap_err();
}
}