Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: into_v1 #121

Merged
merged 2 commits into from
Aug 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -162,3 +162,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);
}