forest_encoding/
errors.rs

1// Copyright 2019-2022 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use cid::Error as CidError;
5use serde_cbor::error::Error as CborError;
6use std::fmt;
7use std::io;
8use thiserror::Error;
9
10/// Error type for encoding and decoding data through any Forest supported protocol.
11///
12/// This error will provide any details about the data which was attempted to be
13/// encoded or decoded.
14#[derive(Debug, PartialEq, Error)]
15#[error("Serialization error for {protocol} protocol: {description}")]
16pub struct Error {
17    pub description: String,
18    pub protocol: CodecProtocol,
19}
20
21impl From<CborError> for Error {
22    fn from(err: CborError) -> Error {
23        Self {
24            description: err.to_string(),
25            protocol: CodecProtocol::Cbor,
26        }
27    }
28}
29
30impl From<CidError> for Error {
31    fn from(err: CidError) -> Self {
32        Self {
33            description: err.to_string(),
34            protocol: CodecProtocol::Cbor,
35        }
36    }
37}
38
39impl From<Error> for io::Error {
40    fn from(err: Error) -> Self {
41        Self::new(io::ErrorKind::Other, err)
42    }
43}
44
45/// CodecProtocol defines the protocol in which the data is encoded or decoded
46///
47/// This is used with the encoding errors, to detail the encoding protocol or any other
48/// information about how the data was encoded or decoded
49#[derive(Debug, PartialEq)]
50pub enum CodecProtocol {
51    Cbor,
52}
53
54impl fmt::Display for CodecProtocol {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        match *self {
57            CodecProtocol::Cbor => write!(f, "Cbor"),
58        }
59    }
60}