ipld_nostd/cid/
version.rs

1use {
2	super::error::{Error, Result},
3	core::convert::TryFrom,
4	scale::{Decode, Encode},
5};
6
7/// The version of the CID.
8#[derive(
9	PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Hash, Decode, Encode,
10)]
11pub enum Version {
12	/// CID version 0.
13	V0,
14	/// CID version 1.
15	V1,
16}
17
18impl Version {
19	/// Check if the version of `data` string is CIDv0.
20	pub fn is_v0_str(data: &str) -> bool {
21		// v0 is a Base58Btc encoded sha hash, so it has
22		// fixed length and always begins with "Qm"
23		data.len() == 46 && data.starts_with("Qm")
24	}
25
26	/// Check if the version of `data` bytes is CIDv0.
27	pub fn is_v0_binary(data: &[u8]) -> bool {
28		data.len() == 34 && data.starts_with(&[0x12, 0x20])
29	}
30}
31
32/// Convert a number to the matching version, or `Error` if no valid version is
33/// matching.
34impl TryFrom<u64> for Version {
35	type Error = Error;
36
37	fn try_from(raw: u64) -> Result<Self> {
38		match raw {
39			0 => Ok(Self::V0),
40			1 => Ok(Self::V1),
41			_ => Err(Error::InvalidCidVersion),
42		}
43	}
44}
45
46impl From<Version> for u64 {
47	fn from(ver: Version) -> u64 {
48		match ver {
49			Version::V0 => 0,
50			Version::V1 => 1,
51		}
52	}
53}