summaryrefslogtreecommitdiffstats
path: root/src/cid.rs
blob: 5aef970e9eb9a393b00f3cfea78e94696b84776c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use anyhow::Result;

/// Our own CID type
///
/// Right now the ipfs_api crate does not use a CID type in its interface... hence we would need to
/// convert back-and-forth between String and cid::Cid,... but that's tedious.
///
/// Hence we just create our own "Cid type" and use that as long as the crate API is stringly
/// typed.
#[derive(Clone, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct Cid(String);

impl AsRef<str> for Cid {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

pub trait TryToCid {
    fn try_to_cid(self) -> Result<Cid>;
}

impl TryToCid for ipfs_api_backend_hyper::response::AddResponse {
    fn try_to_cid(self) -> Result<Cid> {
        log::debug!("Transforming to CID => {:?}", self);
        string_to_cid(self.hash)
    }
}

impl TryToCid for ipfs_api_backend_hyper::response::DagPutResponse {
    fn try_to_cid(self) -> Result<Cid> {
        log::debug!("Transforming to CID => {:?}", self);
        string_to_cid(self.cid.cid_string)
    }
}

impl daglib::NodeId for Cid {
}

/// Helper function that can be tested
///
/// Converts a String to a Cid
#[cfg(not(test))]
fn string_to_cid(s: String) -> Result<Cid> {
    string_to_cid_impl(s)
}

#[cfg(test)]
pub fn string_to_cid(s: String) -> Result<Cid> {
    string_to_cid_impl(s)
}

fn string_to_cid_impl(s: String) -> Result<Cid> {
    Ok(Cid(s))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_string_to_cid() {
        let s = String::from("QmY2T5EfgLn8qWCt8eus6VX1gJuAp1nmUSdmoehgMxznAf");
        let r = string_to_cid(s);
        assert!(r.is_ok(), "Not OK = {:?}", r);
    }
}