forked from ordinals/ord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrune_id.rs
132 lines (115 loc) Β· 2.52 KB
/
rune_id.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
use {super::*, std::num::TryFromIntError};
#[derive(Debug, PartialEq, Copy, Clone, Hash, Eq, Ord, PartialOrd)]
pub struct RuneId {
pub height: u32,
pub index: u16,
}
impl TryFrom<u128> for RuneId {
type Error = TryFromIntError;
fn try_from(n: u128) -> Result<Self, Self::Error> {
Ok(Self {
height: u32::try_from(n >> 16)?,
index: u16::try_from(n & 0xFFFF).unwrap(),
})
}
}
impl From<RuneId> for u128 {
fn from(id: RuneId) -> Self {
u128::from(id.height) << 16 | u128::from(id.index)
}
}
impl Display for RuneId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}/{}", self.height, self.index,)
}
}
impl FromStr for RuneId {
type Err = crate::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (height, index) = s
.split_once('/')
.ok_or_else(|| anyhow!("invalid rune ID: {s}"))?;
Ok(Self {
height: height.parse()?,
index: index.parse()?,
})
}
}
impl Serialize for RuneId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for RuneId {
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 rune_id_to_128() {
assert_eq!(
0b11_0000_0000_0000_0001u128,
RuneId {
height: 3,
index: 1,
}
.into()
);
}
#[test]
fn display() {
assert_eq!(
RuneId {
height: 1,
index: 2
}
.to_string(),
"1/2"
);
}
#[test]
fn from_str() {
assert!("/".parse::<RuneId>().is_err());
assert!("1/".parse::<RuneId>().is_err());
assert!("/2".parse::<RuneId>().is_err());
assert!("a/2".parse::<RuneId>().is_err());
assert!("1/a".parse::<RuneId>().is_err());
assert_eq!(
"1/2".parse::<RuneId>().unwrap(),
RuneId {
height: 1,
index: 2
}
);
}
#[test]
fn try_from() {
assert_eq!(
RuneId::try_from(0x060504030201).unwrap(),
RuneId {
height: 0x06050403,
index: 0x0201
}
);
assert!(RuneId::try_from(0x07060504030201).is_err());
}
#[test]
fn serde() {
let rune_id = RuneId {
height: 1,
index: 2,
};
let json = "\"1/2\"";
assert_eq!(serde_json::to_string(&rune_id).unwrap(), json);
assert_eq!(serde_json::from_str::<RuneId>(json).unwrap(), rune_id);
}
}