gear_subxt/metadata/
decode_encode_traits.rs

1// Copyright 2019-2023 Parity Technologies (UK) Ltd.
2// This file is dual-licensed as Apache-2.0 or GPL-3.0.
3// see LICENSE for license details.
4
5use super::Metadata;
6use crate::error::Error;
7
8/// This trait is implemented for all types that also implement [`scale_decode::DecodeAsType`].
9pub trait DecodeWithMetadata: Sized {
10    /// Given some metadata and a type ID, attempt to SCALE decode the provided bytes into `Self`.
11    fn decode_with_metadata(
12        bytes: &mut &[u8],
13        type_id: u32,
14        metadata: &Metadata,
15    ) -> Result<Self, Error>;
16}
17
18impl<T: scale_decode::DecodeAsType> DecodeWithMetadata for T {
19    fn decode_with_metadata(
20        bytes: &mut &[u8],
21        type_id: u32,
22        metadata: &Metadata,
23    ) -> Result<T, Error> {
24        let val = T::decode_as_type(bytes, type_id, metadata.types())?;
25        Ok(val)
26    }
27}
28
29/// This trait is implemented for all types that also implement [`scale_encode::EncodeAsType`].
30pub trait EncodeWithMetadata {
31    /// SCALE encode this type to bytes, possibly with the help of metadata.
32    fn encode_with_metadata(
33        &self,
34        type_id: u32,
35        metadata: &Metadata,
36        bytes: &mut Vec<u8>,
37    ) -> Result<(), Error>;
38}
39
40impl<T: scale_encode::EncodeAsType> EncodeWithMetadata for T {
41    /// SCALE encode this type to bytes, possibly with the help of metadata.
42    fn encode_with_metadata(
43        &self,
44        type_id: u32,
45        metadata: &Metadata,
46        bytes: &mut Vec<u8>,
47    ) -> Result<(), Error> {
48        self.encode_as_type_to(type_id, metadata.types(), bytes)?;
49        Ok(())
50    }
51}