forked from multiformats/rust-cid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcid.rs
More file actions
202 lines (168 loc) · 5.24 KB
/
cid.rs
File metadata and controls
202 lines (168 loc) · 5.24 KB
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use std::convert::TryFrom;
use multibase::Base;
use multihash::{Code, Multihash, MultihashRef};
use unsigned_varint::{decode as varint_decode, encode as varint_encode};
use crate::codec::Codec;
use crate::error::{Error, Result};
use crate::prefix::Prefix;
use crate::version::Version;
/// Representation of a CID.
#[derive(PartialEq, Eq, Clone, Debug, PartialOrd, Ord)]
pub struct Cid {
/// The version of CID.
pub version: Version,
/// The codec of CID.
pub codec: Codec,
/// The multihash of CID.
pub hash: Multihash,
}
impl Cid {
/// Create a new CIDv0.
pub fn new_v0(hash: Multihash) -> Result<Cid> {
if hash.algorithm() != Code::Sha2_256 {
return Err(Error::InvalidCidV0Multihash);
}
Ok(Cid {
version: Version::V0,
codec: Codec::DagProtobuf,
hash,
})
}
/// Create a new CIDv1.
pub fn new_v1(codec: Codec, hash: Multihash) -> Cid {
Cid {
version: Version::V1,
codec,
hash,
}
}
/// Create a new CID.
pub fn new(version: Version, codec: Codec, hash: Multihash) -> Result<Cid> {
match version {
Version::V0 => {
if codec != Codec::DagProtobuf {
return Err(Error::InvalidCidV0Codec);
}
Self::new_v0(hash)
}
Version::V1 => Ok(Self::new_v1(codec, hash)),
}
}
/// Create a new CID from a prefix and some data.
pub fn new_from_prefix(prefix: &Prefix, data: &[u8]) -> Cid {
let mut hash = prefix.mh_type.hasher().unwrap().digest(data);
if prefix.mh_len < hash.digest().len() {
hash = multihash::wrap(hash.algorithm(), &hash.digest()[..prefix.mh_len]);
}
Cid {
version: prefix.version,
codec: prefix.codec,
hash,
}
}
fn to_string_v0(&self) -> String {
Base::Base58Btc.encode(self.hash.as_bytes())
}
fn to_string_v1(&self) -> String {
multibase::encode(Base::Base32Lower, self.to_bytes().as_slice())
}
fn to_bytes_v0(&self) -> Vec<u8> {
self.hash.to_vec()
}
fn to_bytes_v1(&self) -> Vec<u8> {
let mut res = Vec::with_capacity(16);
let mut buf = varint_encode::u64_buffer();
let version = varint_encode::u64(self.version.into(), &mut buf);
res.extend_from_slice(version);
let mut buf = varint_encode::u64_buffer();
let codec = varint_encode::u64(self.codec.into(), &mut buf);
res.extend_from_slice(codec);
res.extend_from_slice(&self.hash);
res
}
/// Convert CID to encoded bytes.
pub fn to_bytes(&self) -> Vec<u8> {
match self.version {
Version::V0 => self.to_bytes_v0(),
Version::V1 => self.to_bytes_v1(),
}
}
/// Return the prefix of the CID.
pub fn prefix(&self) -> Prefix {
Prefix {
version: self.version,
codec: self.codec,
mh_type: self.hash.algorithm(),
mh_len: self.hash.digest().len(),
}
}
}
#[allow(clippy::derive_hash_xor_eq)]
impl std::hash::Hash for Cid {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.to_bytes().hash(state);
}
}
impl std::fmt::Display for Cid {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let output = match self.version {
Version::V0 => self.to_string_v0(),
Version::V1 => self.to_string_v1(),
};
write!(f, "{}", output)
}
}
impl std::str::FromStr for Cid {
type Err = Error;
fn from_str(cid_str: &str) -> Result<Self> {
Cid::try_from(cid_str)
}
}
impl TryFrom<String> for Cid {
type Error = Error;
fn try_from(cid_str: String) -> Result<Self> {
Self::try_from(cid_str.as_str())
}
}
impl TryFrom<&str> for Cid {
type Error = Error;
fn try_from(cid_str: &str) -> Result<Self> {
static IPFS_DELIMETER: &str = "/ipfs/";
let hash = match cid_str.find(IPFS_DELIMETER) {
Some(index) => &cid_str[index + IPFS_DELIMETER.len()..],
_ => cid_str,
};
if hash.len() < 2 {
return Err(Error::InputTooShort);
}
let decoded = if Version::is_v0_str(hash) {
Base::Base58Btc.decode(hash)?
} else {
let (_, decoded) = multibase::decode(hash)?;
decoded
};
Self::try_from(decoded)
}
}
impl TryFrom<Vec<u8>> for Cid {
type Error = Error;
fn try_from(bytes: Vec<u8>) -> Result<Self> {
Self::try_from(bytes.as_slice())
}
}
impl TryFrom<&[u8]> for Cid {
type Error = Error;
fn try_from(bytes: &[u8]) -> Result<Self> {
if Version::is_v0_binary(bytes) {
let mh = MultihashRef::from_slice(bytes)?.to_owned();
Cid::new_v0(mh)
} else {
let (raw_version, remain) = varint_decode::u64(&bytes)?;
let version = Version::from(raw_version)?;
let (raw_codec, hash) = varint_decode::u64(&remain)?;
let codec = Codec::try_from(raw_codec)?;
let mh = MultihashRef::from_slice(hash)?.to_owned();
Cid::new(version, codec, mh)
}
}
}