ipld_nostd/ipld/codec.rs
1//! This module contains traits to have a unified API across codecs.
2//!
3//! There are two traits defined, [`Codec`] and [`Links`]. Those are separate
4//! traits as the `Links` trait is not generic over a certain type.
5
6use {
7 crate::cid::Cid,
8 alloc::vec::Vec,
9 core2::io::{BufRead, Write},
10};
11
12/// Each IPLD codec implementation should implement this Codec trait. This way
13/// codecs can be more easily exchanged or combined.
14pub trait Codec<T>: Links {
15 /// The multicodec code of the IPLD codec.
16 const CODE: u64;
17 /// The error that is returned if encoding or decoding fails.
18 type Error;
19
20 /// Decode a reader into the desired type.
21 fn decode<R: BufRead>(reader: R) -> Result<T, Self::Error>;
22 /// Encode a type into a writer.
23 fn encode<W: Write>(writer: W, data: &T) -> Result<(), Self::Error>;
24
25 /// Decode a slice into the desired type.
26 fn decode_from_slice(bytes: &[u8]) -> Result<T, Self::Error> {
27 Self::decode(bytes)
28 }
29
30 /// Encode a type into bytes.
31 fn encode_to_vec(data: &T) -> Result<Vec<u8>, Self::Error> {
32 let mut output = Vec::new();
33 Self::encode(&mut output, data)?;
34 Ok(output)
35 }
36}
37
38/// Trait for returning the links of a serialized IPLD data.
39pub trait Links {
40 /// The error that is returned if the link extraction fails.
41 type LinksError;
42
43 /// Return all links (CIDs) that the given encoded data contains.
44 fn links(bytes: &[u8])
45 -> Result<impl Iterator<Item = Cid>, Self::LinksError>;
46}