forked from ordinals/ord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsat_point.rs
115 lines (99 loc) Β· 2.58 KB
/
sat_point.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
use super::*;
#[derive(Debug, PartialEq, Copy, Clone, Eq, PartialOrd, Ord)]
pub struct SatPoint {
pub(crate) outpoint: OutPoint,
pub(crate) offset: u64,
}
impl Display for SatPoint {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}:{}", self.outpoint, self.offset)
}
}
impl Encodable for SatPoint {
fn consensus_encode<S: io::Write + ?Sized>(&self, s: &mut S) -> Result<usize, io::Error> {
let len = self.outpoint.consensus_encode(s)?;
Ok(len + self.offset.consensus_encode(s)?)
}
}
impl Decodable for SatPoint {
fn consensus_decode<D: io::Read + ?Sized>(
d: &mut D,
) -> Result<Self, bitcoin::consensus::encode::Error> {
Ok(SatPoint {
outpoint: Decodable::consensus_decode(d)?,
offset: Decodable::consensus_decode(d)?,
})
}
}
impl Serialize for SatPoint {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for SatPoint {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(DeserializeFromStr::deserialize(deserializer)?.0)
}
}
impl FromStr for SatPoint {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (outpoint, offset) = s
.rsplit_once(':')
.ok_or_else(|| anyhow!("invalid satpoint: {s}"))?;
Ok(SatPoint {
outpoint: outpoint.parse()?,
offset: offset.parse()?,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_str_ok() {
assert_eq!(
"1111111111111111111111111111111111111111111111111111111111111111:1:1"
.parse::<SatPoint>()
.unwrap(),
SatPoint {
outpoint: "1111111111111111111111111111111111111111111111111111111111111111:1"
.parse()
.unwrap(),
offset: 1,
}
);
}
#[test]
fn from_str_err() {
"abc".parse::<SatPoint>().unwrap_err();
"abc:xyz".parse::<SatPoint>().unwrap_err();
"1111111111111111111111111111111111111111111111111111111111111111:1"
.parse::<SatPoint>()
.unwrap_err();
"1111111111111111111111111111111111111111111111111111111111111111:1:foo"
.parse::<SatPoint>()
.unwrap_err();
}
#[test]
fn deserialize_ok() {
assert_eq!(
serde_json::from_str::<SatPoint>(
"\"1111111111111111111111111111111111111111111111111111111111111111:1:1\""
)
.unwrap(),
SatPoint {
outpoint: "1111111111111111111111111111111111111111111111111111111111111111:1"
.parse()
.unwrap(),
offset: 1,
}
);
}
}