subxt_core/metadata/
decode_encode_traits.rs

1// Copyright 2019-2024 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;
6
7use alloc::vec::Vec;
8
9/// This trait is implemented for all types that also implement [`scale_decode::DecodeAsType`].
10pub trait DecodeWithMetadata: Sized {
11    /// Given some metadata and a type ID, attempt to SCALE decode the provided bytes into `Self`.
12    fn decode_with_metadata(
13        bytes: &mut &[u8],
14        type_id: u32,
15        metadata: &Metadata,
16    ) -> Result<Self, scale_decode::Error>;
17}
18
19impl<T: scale_decode::DecodeAsType> DecodeWithMetadata for T {
20    fn decode_with_metadata(
21        bytes: &mut &[u8],
22        type_id: u32,
23        metadata: &Metadata,
24    ) -> Result<T, scale_decode::Error> {
25        let val = T::decode_as_type(bytes, type_id, metadata.types())?;
26        Ok(val)
27    }
28}
29
30/// This trait is implemented for all types that also implement [`scale_encode::EncodeAsType`].
31pub trait EncodeWithMetadata {
32    /// SCALE encode this type to bytes, possibly with the help of metadata.
33    fn encode_with_metadata(
34        &self,
35        type_id: u32,
36        metadata: &Metadata,
37        bytes: &mut Vec<u8>,
38    ) -> Result<(), scale_encode::Error>;
39}
40
41impl<T: scale_encode::EncodeAsType> EncodeWithMetadata for T {
42    /// SCALE encode this type to bytes, possibly with the help of metadata.
43    fn encode_with_metadata(
44        &self,
45        type_id: u32,
46        metadata: &Metadata,
47        bytes: &mut Vec<u8>,
48    ) -> Result<(), scale_encode::Error> {
49        self.encode_as_type_to(type_id, metadata.types(), bytes)?;
50        Ok(())
51    }
52}