sp_cid/
version.rs

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