fvm_ipld_encoding/
cbor.rs

1// Copyright 2021-2023 Protocol Labs
2// Copyright 2019-2022 ChainSafe Systems
3// SPDX-License-Identifier: Apache-2.0, MIT
4
5use std::fmt::{Debug, Formatter};
6use std::ops::Deref;
7use std::rc::Rc;
8
9use serde::{Deserialize, Serialize};
10
11use super::errors::Error;
12use crate::{de, from_slice, ser, strict_bytes, to_vec};
13
14/// Cbor utility functions for serializable objects
15#[deprecated(note = "use to_vec or from_slice directly")]
16pub trait Cbor: ser::Serialize + de::DeserializeOwned {
17    /// Marshalls cbor encodable object into cbor bytes
18    fn marshal_cbor(&self) -> Result<Vec<u8>, Error> {
19        to_vec(&self)
20    }
21
22    /// Unmarshals cbor encoded bytes to object
23    fn unmarshal_cbor(bz: &[u8]) -> Result<Self, Error> {
24        from_slice(bz)
25    }
26}
27
28#[allow(deprecated)]
29impl<T> Cbor for Vec<T> where T: Cbor {}
30#[allow(deprecated)]
31impl<T> Cbor for Option<T> where T: Cbor {}
32
33/// Raw serialized cbor bytes.
34/// This data is (de)serialized as a byte string.
35#[derive(Clone, PartialEq, Serialize, Deserialize, Hash, Eq, Default)]
36#[serde(transparent)]
37pub struct RawBytes {
38    #[serde(with = "strict_bytes")]
39    bytes: Vec<u8>,
40}
41
42impl From<RawBytes> for Vec<u8> {
43    fn from(b: RawBytes) -> Vec<u8> {
44        b.bytes
45    }
46}
47
48impl From<Vec<u8>> for RawBytes {
49    fn from(v: Vec<u8>) -> RawBytes {
50        RawBytes::new(v)
51    }
52}
53
54impl From<RawBytes> for Rc<[u8]> {
55    fn from(b: RawBytes) -> Rc<[u8]> {
56        b.bytes.into()
57    }
58}
59
60#[allow(deprecated)]
61impl Cbor for RawBytes {}
62
63impl Deref for RawBytes {
64    type Target = Vec<u8>;
65    fn deref(&self) -> &Self::Target {
66        &self.bytes
67    }
68}
69
70impl RawBytes {
71    /// Constructor if data is encoded already
72    pub fn new(bytes: Vec<u8>) -> Self {
73        Self { bytes }
74    }
75
76    /// Contructor for encoding Cbor encodable structure.
77    pub fn serialize<O: Serialize>(obj: O) -> Result<Self, Error> {
78        Ok(Self {
79            bytes: to_vec(&obj)?,
80        })
81    }
82
83    /// Returns serialized bytes.
84    pub fn bytes(&self) -> &[u8] {
85        &self.bytes
86    }
87
88    /// Deserializes the serialized bytes into a defined type.
89    pub fn deserialize<O: de::DeserializeOwned>(&self) -> Result<O, Error> {
90        from_slice(&self.bytes)
91    }
92}
93
94impl Debug for RawBytes {
95    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
96        write!(f, "RawBytes {{ ")?;
97        for byte in &self.bytes {
98            write!(f, "{:02x}", byte)?;
99        }
100        write!(f, " }}")
101    }
102}
103
104#[cfg(test)]
105mod test {
106    use crate::RawBytes;
107
108    #[test]
109    fn debug_hex() {
110        assert_eq!("RawBytes {  }", format!("{:?}", RawBytes::from(vec![])));
111        assert_eq!("RawBytes { 00 }", format!("{:?}", RawBytes::from(vec![0])));
112        assert_eq!("RawBytes { 0f }", format!("{:?}", RawBytes::from(vec![15])));
113        assert_eq!(
114            "RawBytes { 00010a10ff }",
115            format!("{:?}", RawBytes::from(vec![0, 1, 10, 16, 255]))
116        );
117    }
118}