cardano_sdk/
cbor.rs

1//  This Source Code Form is subject to the terms of the Mozilla Public
2//  License, v. 2.0. If a copy of the MPL was not distributed with this
3//  file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5pub use minicbor::{decode::Decode, encode::Encode};
6pub use pallas_codec::minicbor::*;
7use std::convert::Infallible;
8
9/// A trait mostly for convenience, as we often end up writing bytes to CBOR. The original
10/// [`minicbor::Encode::encode`] makes room for encoding into any Writer type, and thus provides
11/// the ability to fail.
12///
13/// When writing bytes to a vector, the operation is however Infaillible.
14pub trait ToCbor {
15    fn to_cbor(&self) -> Vec<u8>;
16}
17
18impl<T: Encode<()>> ToCbor for T {
19    fn to_cbor(&self) -> Vec<u8> {
20        let mut bytes = Vec::new();
21        let _: Result<(), encode::Error<Infallible>> = encode(self, &mut bytes);
22        bytes
23    }
24}
25
26/// A trait mostly for convenience, as we often end up writing bytes to CBOR.
27pub trait FromCbor<'d> {
28    fn from_cbor(bytes: &'d [u8]) -> Result<Self, decode::Error>
29    where
30        Self: Sized;
31}
32
33impl<'d, T: Decode<'d, ()>> FromCbor<'d> for T {
34    fn from_cbor(bytes: &'d [u8]) -> Result<Self, decode::Error> {
35        decode(bytes)
36    }
37}