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