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
133
134
use amplify::Wrapper;
use std::io;
use super::{Error, StrictDecode, StrictEncode};
pub struct HashFixedBytes;
pub struct BitcoinConsensus;
pub struct Wrapped;
pub trait Strategy {
type Strategy;
}
impl<T> StrictEncode for T
where
T: Strategy + Clone,
amplify::Holder<T, <T as Strategy>::Strategy>: StrictEncode,
{
#[inline]
fn strict_encode<E: io::Write>(&self, e: E) -> Result<usize, Error> {
amplify::Holder::new(self.clone()).strict_encode(e)
}
}
impl<T> StrictDecode for T
where
T: Strategy,
amplify::Holder<T, <T as Strategy>::Strategy>: StrictDecode,
{
#[inline]
fn strict_decode<D: io::Read>(d: D) -> Result<Self, Error> {
Ok(amplify::Holder::strict_decode(d)?.into_inner())
}
}
impl<T> StrictEncode for amplify::Holder<T, Wrapped>
where
T: Wrapper,
T::Inner: StrictEncode,
{
#[inline]
fn strict_encode<E: io::Write>(&self, e: E) -> Result<usize, Error> {
Ok(self.as_inner().to_inner().strict_encode(e)?)
}
}
impl<T> StrictDecode for amplify::Holder<T, Wrapped>
where
T: Wrapper,
T::Inner: StrictDecode,
{
#[inline]
fn strict_decode<D: io::Read>(d: D) -> Result<Self, Error> {
Ok(Self::new(T::from_inner(T::Inner::strict_decode(d)?)))
}
}
impl<T> StrictEncode for amplify::Holder<T, HashFixedBytes>
where
T: bitcoin::hashes::Hash,
{
#[inline]
fn strict_encode<E: io::Write>(&self, mut e: E) -> Result<usize, Error> {
e.write_all(&self.as_inner()[..])?;
Ok(T::LEN)
}
}
impl<T> StrictDecode for amplify::Holder<T, HashFixedBytes>
where
T: bitcoin::hashes::Hash,
{
#[inline]
fn strict_decode<D: io::Read>(mut d: D) -> Result<Self, Error> {
let mut buf = vec![0u8; T::LEN];
d.read_exact(&mut buf)?;
Ok(Self::new(T::from_slice(&buf)?))
}
}
impl<T> StrictEncode for amplify::Holder<T, BitcoinConsensus>
where
T: bitcoin::consensus::Encodable,
{
#[inline]
fn strict_encode<E: io::Write>(&self, e: E) -> Result<usize, Error> {
self.as_inner().consensus_encode(e).map_err(Error::from)
}
}
impl<T> StrictDecode for amplify::Holder<T, BitcoinConsensus>
where
T: bitcoin::consensus::Decodable,
{
#[inline]
fn strict_decode<D: io::Read>(d: D) -> Result<Self, Error> {
Ok(Self::new(T::consensus_decode(d).map_err(Error::from)?))
}
}
impl From<bitcoin::hashes::Error> for Error {
#[inline]
fn from(_: bitcoin::hashes::Error) -> Self {
Error::DataIntegrityError("Incorrect hash length".to_string())
}
}
impl From<bitcoin::consensus::encode::Error> for Error {
#[inline]
fn from(e: bitcoin::consensus::encode::Error) -> Self {
if let bitcoin::consensus::encode::Error::Io(err) = e {
err.into()
} else {
Error::DataIntegrityError(e.to_string())
}
}
}