referrerpolicy=no-referrer-when-downgrade

staging_xcm/
double_encoded.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17use crate::MAX_XCM_DECODE_DEPTH;
18use alloc::vec::Vec;
19use codec::{Decode, DecodeLimit, DecodeWithMemTracking, Encode};
20
21/// Wrapper around the encoded and decoded versions of a value.
22/// Caches the decoded value once computed.
23#[derive(Encode, Decode, DecodeWithMemTracking, scale_info::TypeInfo)]
24#[codec(encode_bound())]
25#[codec(decode_bound())]
26#[scale_info(bounds(), skip_type_params(T))]
27#[scale_info(replace_segment("staging_xcm", "xcm"))]
28#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
29pub struct DoubleEncoded<T> {
30	encoded: Vec<u8>,
31	#[codec(skip)]
32	decoded: Option<T>,
33}
34
35impl<T> Clone for DoubleEncoded<T> {
36	fn clone(&self) -> Self {
37		Self { encoded: self.encoded.clone(), decoded: None }
38	}
39}
40
41impl<T> PartialEq for DoubleEncoded<T> {
42	fn eq(&self, other: &Self) -> bool {
43		self.encoded.eq(&other.encoded)
44	}
45}
46impl<T> Eq for DoubleEncoded<T> {}
47
48impl<T> core::fmt::Debug for DoubleEncoded<T> {
49	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
50		array_bytes::bytes2hex("0x", &self.encoded).fmt(f)
51	}
52}
53
54impl<T> From<Vec<u8>> for DoubleEncoded<T> {
55	fn from(encoded: Vec<u8>) -> Self {
56		Self { encoded, decoded: None }
57	}
58}
59
60impl<T> DoubleEncoded<T> {
61	pub fn into<S>(self) -> DoubleEncoded<S> {
62		DoubleEncoded::from(self)
63	}
64
65	pub fn from<S>(e: DoubleEncoded<S>) -> Self {
66		Self { encoded: e.encoded, decoded: None }
67	}
68
69	/// Provides an API similar to `AsRef` that provides access to the inner value.
70	/// `AsRef` implementation would expect an `&Option<T>` return type.
71	pub fn as_ref(&self) -> Option<&T> {
72		self.decoded.as_ref()
73	}
74
75	/// Access the encoded data.
76	pub fn into_encoded(self) -> Vec<u8> {
77		self.encoded
78	}
79}
80
81impl<T: Decode> DoubleEncoded<T> {
82	/// Decode the inner encoded value and store it.
83	/// Returns a reference to the value in case of success and `Err(())` in case the decoding
84	/// fails.
85	pub fn ensure_decoded(&mut self) -> Result<&T, ()> {
86		if self.decoded.is_none() {
87			self.decoded =
88				T::decode_all_with_depth_limit(MAX_XCM_DECODE_DEPTH, &mut &self.encoded[..]).ok();
89		}
90		self.decoded.as_ref().ok_or(())
91	}
92
93	/// Move the decoded value out or (if not present) decode `encoded`.
94	pub fn take_decoded(&mut self) -> Result<T, ()> {
95		self.decoded
96			.take()
97			.or_else(|| {
98				T::decode_all_with_depth_limit(MAX_XCM_DECODE_DEPTH, &mut &self.encoded[..]).ok()
99			})
100			.ok_or(())
101	}
102
103	/// Provides an API similar to `TryInto` that allows fallible conversion to the inner value
104	/// type. `TryInto` implementation would collide with std blanket implementation based on
105	/// `TryFrom`.
106	pub fn try_into(mut self) -> Result<T, ()> {
107		self.ensure_decoded()?;
108		self.decoded.ok_or(())
109	}
110}
111
112#[cfg(test)]
113mod tests {
114	use super::*;
115
116	#[test]
117	fn ensure_decoded_works() {
118		let val: u64 = 42;
119		let mut encoded: DoubleEncoded<_> = Encode::encode(&val).into();
120		assert_eq!(encoded.ensure_decoded(), Ok(&val));
121	}
122
123	#[test]
124	fn take_decoded_works() {
125		let val: u64 = 42;
126		let mut encoded: DoubleEncoded<_> = Encode::encode(&val).into();
127		assert_eq!(encoded.take_decoded(), Ok(val));
128	}
129
130	#[test]
131	fn try_into_works() {
132		let val: u64 = 42;
133		let encoded: DoubleEncoded<_> = Encode::encode(&val).into();
134		assert_eq!(encoded.try_into(), Ok(val));
135	}
136}