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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use anyhow::{anyhow, Result};
use libipld_cbor::DagCborCodec;
use libipld_core::{
    codec::{Codec, Decode, Encode},
    raw::RawCodec,
};
use std::{
    fmt::{Display, Formatter},
    io::{Read, Seek, Write},
};
use std::{hash::Hash, marker::PhantomData, ops::Deref};

use cid::Cid;
use noosphere_storage::BlockStore;
use serde::{de::DeserializeOwned, Deserialize, Serialize};

use noosphere_collections::hamt::Hash as HamtHash;

#[cfg(not(target_arch = "wasm32"))]
pub trait LinkSend: Send {}

#[cfg(not(target_arch = "wasm32"))]
impl<T> LinkSend for T where T: Send {}

#[cfg(target_arch = "wasm32")]
pub trait LinkSend {}

#[cfg(target_arch = "wasm32")]
impl<T> LinkSend for T {}

/// A [Link] is a [Cid] with a type attached. The type represents the data that
/// the [Cid] refers to. This is a helpful construct to use to ensure that data
/// structures whose fields or elements may be [Cid]s can still retain strong
/// typing. A [Link] transparently represents its inner [Cid], so a data
/// structure that uses [Link]s can safely be interpretted in terms of [Cid]s,
/// and vice-versa.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Clone)]
// NOTE: Required because libipld special-cases unit structs and errors
// SEE: https://github.com/ipld/libipld/blob/65e0b38520f62cfb2b67ebe658846d86dac2f73e/core/src/serde/ser.rs#L192
#[serde(from = "Cid", into = "Cid")]
#[repr(transparent)]
pub struct Link<T>
where
    T: Clone,
{
    pub cid: Cid,
    linked_type: PhantomData<T>,
}

impl<T> Deref for Link<T>
where
    T: Clone,
{
    type Target = Cid;

    fn deref(&self) -> &Self::Target {
        &self.cid
    }
}

impl<T> Hash for Link<T>
where
    T: Clone,
{
    fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
        Hash::hash(&self.cid, hasher)
    }
}

impl<T> HamtHash for Link<T>
where
    T: Clone,
{
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.cid.hash().hash(state);
    }
}

impl<T> Link<T>
where
    T: Clone,
{
    pub fn new(cid: Cid) -> Self {
        Link {
            cid,
            linked_type: PhantomData,
        }
    }
}

impl<T> Display for Link<T>
where
    T: Clone,
{
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        self.cid.fmt(f)
    }
}

impl<C: Codec, T> Encode<C> for Link<T>
where
    Cid: Encode<C>,
    T: Clone,
{
    fn encode<W: Write>(&self, c: C, w: &mut W) -> Result<()> {
        self.cid.encode(c, w)
    }
}

impl<C: Codec, T> Decode<C> for Link<T>
where
    Cid: Decode<C>,
    T: Clone,
{
    fn decode<R: Read + Seek>(c: C, r: &mut R) -> Result<Self> {
        Ok(Self::new(Cid::decode(c, r)?))
    }
}

impl<T> AsRef<Cid> for Link<T>
where
    T: Clone,
{
    fn as_ref(&self) -> &Cid {
        &self.cid
    }
}

impl<T> From<Cid> for Link<T>
where
    T: Clone,
{
    fn from(cid: Cid) -> Self {
        Self::new(cid)
    }
}

impl<T> From<Link<T>> for Cid
where
    T: Clone,
{
    fn from(link: Link<T>) -> Self {
        link.cid
    }
}

impl<T> Link<T>
where
    T: Serialize + DeserializeOwned + Clone + LinkSend,
{
    /// Given a [BlockStore], attempt to load a value for the [Cid] of this
    /// [Link]. The loaded block will be interpretted as the type that is
    /// attached to the [Cid] by this [Link], and then returned.
    pub async fn load_from<S: BlockStore>(&self, store: &S) -> Result<T> {
        match self.codec() {
            codec_id if codec_id == u64::from(DagCborCodec) => {
                store.load::<DagCborCodec, _>(self).await
            }
            codec_id if codec_id == u64::from(RawCodec) => store.load::<RawCodec, _>(self).await,
            codec_id => Err(anyhow!("Unsupported codec {}", codec_id)),
        }
    }
}

#[cfg(test)]
mod tests {
    use cid::Cid;
    use libipld_cbor::DagCborCodec;
    use noosphere_storage::{BlockStore, MemoryStore};
    use serde::{Deserialize, Serialize};
    #[cfg(target_arch = "wasm32")]
    use wasm_bindgen_test::wasm_bindgen_test;

    use crate::data::MemoIpld;

    use super::Link;

    #[cfg(target_arch = "wasm32")]
    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    #[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
    async fn it_can_interpret_referenced_block_as_attached_type() {
        let mut store = MemoryStore::default();
        let cid = store
            .save::<DagCborCodec, _>(&MemoIpld {
                parent: None,
                headers: vec![("Foo".into(), "Bar".into())],
                body: Cid::default(),
            })
            .await
            .unwrap();

        let link = Link::<MemoIpld>::new(cid);

        let memo = link.load_from(&store).await.unwrap();

        assert_eq!(memo.get_first_header("Foo"), Some(String::from("Bar")))
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    #[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
    async fn it_transparently_serializes_and_deserializes_as_a_cid() {
        #[derive(Serialize, Deserialize)]
        struct UsesLink {
            pub link: Link<MemoIpld>,
        }

        #[derive(Serialize, Deserialize)]
        struct UsesCid {
            pub link: Cid,
        }

        let mut store = MemoryStore::default();

        let memo_cid = store
            .save::<DagCborCodec, _>(&MemoIpld {
                parent: None,
                headers: vec![("Foo".into(), "Bar".into())],
                body: Cid::default(),
            })
            .await
            .unwrap();

        let uses_link_cid = store
            .save::<DagCborCodec, _>(&UsesLink {
                link: Link::new(memo_cid),
            })
            .await
            .unwrap();

        let loaded_uses_cid = store
            .load::<DagCborCodec, UsesCid>(&uses_link_cid)
            .await
            .unwrap();

        assert_eq!(loaded_uses_cid.link, memo_cid);

        let loaded_uses_link = store
            .load::<DagCborCodec, UsesLink>(&uses_link_cid)
            .await
            .unwrap();

        assert_eq!(loaded_uses_link.link, Link::<MemoIpld>::new(memo_cid));
    }
}