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
#![deny(missing_docs)]
#![deny(warnings)]
use core::convert::TryFrom;
use libipld_core::cid::Cid;
use libipld_core::codec::{Codec, Decode, Encode, References};
use libipld_core::error::{Result, UnsupportedCodec};
use libipld_core::ipld::Ipld;
pub use serde_json::Error;
use std::io::{Read, Write};
mod codec;
#[derive(Clone, Copy, Debug)]
pub struct DagJsonCodec;
impl Codec for DagJsonCodec {}
impl From<DagJsonCodec> for u64 {
fn from(_: DagJsonCodec) -> Self {
0x0129
}
}
impl TryFrom<u64> for DagJsonCodec {
type Error = UnsupportedCodec;
fn try_from(_: u64) -> core::result::Result<Self, Self::Error> {
Ok(Self)
}
}
impl Encode<DagJsonCodec> for Ipld {
fn encode<W: Write>(&self, _: DagJsonCodec, w: &mut W) -> Result<()> {
Ok(codec::encode(self, w)?)
}
}
impl Decode<DagJsonCodec> for Ipld {
fn decode<R: Read>(_: DagJsonCodec, r: &mut R) -> Result<Self> {
Ok(codec::decode(r)?)
}
}
impl References<DagJsonCodec> for Ipld {
fn references<R: Read, E: Extend<Cid>>(c: DagJsonCodec, r: &mut R, set: &mut E) -> Result<()> {
Ipld::decode(c, r)?.references(set);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use libipld_core::cid::Cid;
use libipld_core::multihash::{Code, MultihashDigest};
use std::collections::BTreeMap;
#[test]
fn encode_struct() {
let digest = Code::Blake3_256.digest(&b"block"[..]);
let cid = Cid::new_v1(0x55, digest);
let mut map = BTreeMap::new();
map.insert("name".to_string(), Ipld::String("Hello World!".to_string()));
map.insert("details".to_string(), Ipld::Link(cid));
let contact = Ipld::Map(map);
let contact_encoded = DagJsonCodec.encode(&contact).unwrap();
println!("encoded: {:02x?}", contact_encoded);
println!(
"encoded string {}",
std::str::from_utf8(&contact_encoded).unwrap()
);
assert_eq!(
std::str::from_utf8(&contact_encoded).unwrap(),
format!(
r#"{{"details":{{"/":"{}"}},"name":"Hello World!"}}"#,
base64::encode(cid.to_bytes()),
)
);
let contact_decoded: Ipld = DagJsonCodec.decode(&contact_encoded).unwrap();
assert_eq!(contact_decoded, contact);
}
}