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
//! IPLD Codecs.
#[cfg(feature = "dag-cbor")]
use crate::cbor::DagCborCodec;
use crate::cid::Cid;
use crate::codec::{Codec, Decode, Encode, References};
use crate::error::{Result, UnsupportedCodec};
use crate::ipld::Ipld;
#[cfg(feature = "dag-json")]
use crate::json::DagJsonCodec;
#[cfg(feature = "dag-pb")]
use crate::pb::DagPbCodec;
use crate::raw::RawCodec;
use core::convert::TryFrom;
use std::io::{Read, Seek, Write};

/// Default codecs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IpldCodec {
    /// Raw codec.
    Raw,
    /// Cbor codec.
    #[cfg(feature = "dag-cbor")]
    DagCbor,
    /// Json codec.
    #[cfg(feature = "dag-json")]
    DagJson,
    /// Protobuf codec.
    #[cfg(feature = "dag-pb")]
    DagPb,
}

impl TryFrom<u64> for IpldCodec {
    type Error = UnsupportedCodec;

    fn try_from(ccode: u64) -> core::result::Result<Self, Self::Error> {
        Ok(match ccode {
            0x55 => Self::Raw,
            #[cfg(feature = "dag-cbor")]
            0x71 => Self::DagCbor,
            #[cfg(feature = "dag-json")]
            0x0129 => Self::DagJson,
            #[cfg(feature = "dag-pb")]
            0x70 => Self::DagPb,
            _ => return Err(UnsupportedCodec(ccode)),
        })
    }
}

impl From<IpldCodec> for u64 {
    fn from(mc: IpldCodec) -> Self {
        match mc {
            IpldCodec::Raw => 0x55,
            #[cfg(feature = "dag-cbor")]
            IpldCodec::DagCbor => 0x71,
            #[cfg(feature = "dag-json")]
            IpldCodec::DagJson => 0x0129,
            #[cfg(feature = "dag-pb")]
            IpldCodec::DagPb => 0x70,
        }
    }
}

impl From<RawCodec> for IpldCodec {
    fn from(_: RawCodec) -> Self {
        Self::Raw
    }
}

#[cfg(feature = "dag-cbor")]
impl From<DagCborCodec> for IpldCodec {
    fn from(_: DagCborCodec) -> Self {
        Self::DagCbor
    }
}

#[cfg(feature = "dag-cbor")]
impl From<IpldCodec> for DagCborCodec {
    fn from(_: IpldCodec) -> Self {
        Self
    }
}

#[cfg(feature = "dag-json")]
impl From<DagJsonCodec> for IpldCodec {
    fn from(_: DagJsonCodec) -> Self {
        Self::DagJson
    }
}

#[cfg(feature = "dag-json")]
impl From<IpldCodec> for DagJsonCodec {
    fn from(_: IpldCodec) -> Self {
        Self
    }
}

#[cfg(feature = "dag-pb")]
impl From<DagPbCodec> for IpldCodec {
    fn from(_: DagPbCodec) -> Self {
        Self::DagPb
    }
}

#[cfg(feature = "dag-pb")]
impl From<IpldCodec> for DagPbCodec {
    fn from(_: IpldCodec) -> Self {
        Self
    }
}

impl Codec for IpldCodec {}

impl Encode<IpldCodec> for Ipld {
    fn encode<W: Write>(&self, c: IpldCodec, w: &mut W) -> Result<()> {
        match c {
            IpldCodec::Raw => self.encode(RawCodec, w)?,
            #[cfg(feature = "dag-cbor")]
            IpldCodec::DagCbor => self.encode(DagCborCodec, w)?,
            #[cfg(feature = "dag-json")]
            IpldCodec::DagJson => self.encode(DagJsonCodec, w)?,
            #[cfg(feature = "dag-pb")]
            IpldCodec::DagPb => self.encode(DagPbCodec, w)?,
        };
        Ok(())
    }
}

impl Decode<IpldCodec> for Ipld {
    fn decode<R: Read + Seek>(c: IpldCodec, r: &mut R) -> Result<Self> {
        Ok(match c {
            IpldCodec::Raw => Self::decode(RawCodec, r)?,
            #[cfg(feature = "dag-cbor")]
            IpldCodec::DagCbor => Self::decode(DagCborCodec, r)?,
            #[cfg(feature = "dag-json")]
            IpldCodec::DagJson => Self::decode(DagJsonCodec, r)?,
            #[cfg(feature = "dag-pb")]
            IpldCodec::DagPb => Self::decode(DagPbCodec, r)?,
        })
    }
}

impl References<IpldCodec> for Ipld {
    fn references<R: Read + Seek, E: Extend<Cid>>(
        c: IpldCodec,
        r: &mut R,
        set: &mut E,
    ) -> Result<()> {
        match c {
            IpldCodec::Raw => <Self as References<RawCodec>>::references(RawCodec, r, set)?,
            #[cfg(feature = "dag-cbor")]
            IpldCodec::DagCbor => {
                <Self as References<DagCborCodec>>::references(DagCborCodec, r, set)?
            }
            #[cfg(feature = "dag-json")]
            IpldCodec::DagJson => {
                <Self as References<DagJsonCodec>>::references(DagJsonCodec, r, set)?
            }
            #[cfg(feature = "dag-pb")]
            IpldCodec::DagPb => <Self as References<DagPbCodec>>::references(DagPbCodec, r, set)?,
        };
        Ok(())
    }
}

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

    #[test]
    fn raw_encode() {
        let data = Ipld::Bytes([0x22, 0x33, 0x44].to_vec());
        let result = IpldCodec::Raw.encode(&data).unwrap();
        assert_eq!(result, vec![0x22, 0x33, 0x44]);
    }

    #[test]
    fn raw_decode() {
        let data = [0x22, 0x33, 0x44];
        let result: Ipld = IpldCodec::Raw.decode(&data).unwrap();
        assert_eq!(result, Ipld::Bytes(data.to_vec()));
    }

    #[cfg(feature = "dag-cbor")]
    #[test]
    fn dag_cbor_encode() {
        let data = Ipld::Bytes([0x22, 0x33, 0x44].to_vec());
        let result = IpldCodec::DagCbor.encode(&data).unwrap();
        assert_eq!(result, vec![0x43, 0x22, 0x33, 0x44]);
    }

    #[cfg(feature = "dag-cbor")]
    #[test]
    fn dag_cbor_decode() {
        let data = [0x43, 0x22, 0x33, 0x44];
        let result: Ipld = IpldCodec::DagCbor.decode(&data).unwrap();
        assert_eq!(result, Ipld::Bytes(vec![0x22, 0x33, 0x44]));
    }

    #[cfg(feature = "dag-json")]
    #[test]
    fn dag_json_encode() {
        let data = Ipld::Bool(true);
        let result = String::from_utf8(IpldCodec::DagJson.encode(&data).unwrap().to_vec()).unwrap();
        assert_eq!(result, "true");
    }

    #[cfg(feature = "dag-json")]
    #[test]
    fn dag_json_decode() {
        let data = b"true";
        let result: Ipld = IpldCodec::DagJson.decode(data).unwrap();
        assert_eq!(result, Ipld::Bool(true));
    }

    #[cfg(feature = "dag-pb")]
    #[test]
    fn dag_pb_encode() {
        let mut data_map = std::collections::BTreeMap::<String, Ipld>::new();
        data_map.insert("Data".to_string(), Ipld::Bytes(b"data".to_vec()));
        data_map.insert("Links".to_string(), Ipld::List(vec![]));

        let data = Ipld::Map(data_map);
        let result = IpldCodec::DagPb.encode(&data).unwrap();
        assert_eq!(result, vec![0x0a, 0x04, 0x64, 0x61, 0x74, 0x61]);
    }

    #[cfg(feature = "dag-pb")]
    #[test]
    fn dag_pb_decode() {
        let mut data_map = std::collections::BTreeMap::<String, Ipld>::new();
        data_map.insert("Data".to_string(), Ipld::Bytes(b"data".to_vec()));
        data_map.insert("Links".to_string(), Ipld::List(vec![]));
        let expected = Ipld::Map(data_map);

        let data = [0x0a, 0x04, 0x64, 0x61, 0x74, 0x61];
        let result: Ipld = IpldCodec::DagPb.decode(&data).unwrap();
        assert_eq!(result, expected);
    }
}