Skip to content

Commit

Permalink
Merge pull request #121 from Arqu/arqu/into_v1
Browse files Browse the repository at this point in the history
feat: into_v1
  • Loading branch information
Stebalien authored Aug 8, 2022
2 parents 6947c15 + a683d67 commit 17e37cb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/cid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,19 @@ impl<const S: usize> Cid<S> {
}
}

/// Convert a CIDv0 to a CIDv1. Returns unchanged if already a CIDv1.
pub fn into_v1(self) -> Result<Self> {
match self.version {
Version::V0 => {
if self.codec != DAG_PB {
return Err(Error::InvalidCidV0Codec);
}
Ok(Self::new_v1(self.codec, self.hash))
}
Version::V1 => Ok(self),
}
}

/// Returns the cid version.
pub const fn version(&self) -> Version {
self.version
Expand Down
16 changes: 16 additions & 0 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,19 @@ fn method_can_take_differently_sized_cids() {
a_function_that_takes_a_generic_cid(&cid_128)
);
}

#[test]
fn test_into_v1() {
let cid = Cid::from_str("QmTPcW343HGMdoxarwvHHoPhkbo5GfNYjnZkyW5DBtpvLe").unwrap();
let cid_v1 = cid.into_v1().unwrap();
assert_eq!(cid_v1.version(), Version::V1);
assert_eq!(
cid_v1.to_string(),
"bafybeiclbsxcvqpfliqcejqz5ghpvw4r7vktjkyk3ruvjvdmam5azct2v4"
);

let cid = Cid::from_str("bafyreibjo4xmgaevkgud7mbifn3dzp4v4lyaui4yvqp3f2bqwtxcjrdqg4").unwrap();
let cid_v1 = cid.into_v1().unwrap();
assert_eq!(cid_v1.version(), Version::V1);
assert_eq!(cid_v1, cid);
}

0 comments on commit 17e37cb

Please sign in to comment.