tiny_cid/
version.rs

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