Skip to content

Commit b418132

Browse files
feat: implement binary encoding for CIDs
1 parent e8eb599 commit b418132

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

src/cid.rs

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,20 +91,34 @@ impl FromStr for Cid {
9191
.decode(without_prefix)
9292
.map_err(|_e| CidParseError::InvalidEncoding)?;
9393

94-
Cid::from_bytes(&bytes)
94+
Cid::from_bytes_raw(&bytes)
9595
}
9696
}
9797

9898
impl Cid {
99+
/// Returns the `Multihash` of this `CID`.
99100
pub fn hash(&self) -> &Multihash {
100101
&self.hash
101102
}
102103

104+
/// Returns the `Codec` of this `CID`.
103105
pub fn codec(&self) -> Codec {
104106
self.codec
105107
}
106108

109+
/// Tries to decode a `CID` from binary encoding.
107110
pub fn from_bytes(bytes: &[u8]) -> Result<Self, CidParseError> {
111+
if bytes.is_empty() {
112+
return Err(CidParseError::TooShort);
113+
}
114+
if bytes[0] != 0x0 {
115+
return Err(CidParseError::InvalidEncoding);
116+
}
117+
Self::from_bytes_raw(&bytes[1..])
118+
}
119+
120+
/// Tries to decode a `CID` from its raw binary components.
121+
pub fn from_bytes_raw(bytes: &[u8]) -> Result<Self, CidParseError> {
108122
const MIN_LEN: usize = 3;
109123

110124
if bytes.len() < MIN_LEN {
@@ -121,7 +135,16 @@ impl Cid {
121135
Ok(Cid { codec, hash })
122136
}
123137

124-
pub fn as_bytes(&self) -> [u8; 36] {
138+
/// Encode the `CID` in binary format.
139+
pub fn as_bytes(&self) -> [u8; 37] {
140+
let mut out = [0u8; 37];
141+
// out[0] = 0 binary prefix
142+
out[1..].copy_from_slice(&self.as_bytes_raw());
143+
out
144+
}
145+
146+
/// Encodes the `CID` in its raw binary components.
147+
pub fn as_bytes_raw(&self) -> [u8; 36] {
125148
let mut out = [0u8; 36];
126149
out[0] = CID_VERSION;
127150
out[1] = self.codec as u8;
@@ -148,7 +171,7 @@ impl Cid {
148171
impl Display for Cid {
149172
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150173
write!(f, "b")?;
151-
let out = self.as_bytes();
174+
let out = self.as_bytes_raw();
152175
BASE32_LOWER.encode_write(&out, f)?;
153176

154177
Ok(())

0 commit comments

Comments
 (0)