cid/
version.rs

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