Add DecodedValueThunk to allow getting bytes back from dynamic queries (#680)

This commit is contained in:
James Wilson
2022-10-06 09:58:01 +01:00
committed by GitHub
parent 81175b2dd9
commit 98af356644
5 changed files with 91 additions and 11 deletions
+55
View File
@@ -5,6 +5,14 @@
//! This module provides the entry points to create dynamic
//! transactions, storage and constant lookups.
use crate::{
error::Error,
metadata::{
DecodeWithMetadata,
Metadata,
},
};
pub use scale_value::Value;
/// A [`scale_value::Value`] type endowed with contextual information
@@ -24,3 +32,50 @@ pub use crate::storage::{
dynamic as storage,
dynamic_root as storage_root,
};
/// This is the result of making a dynamic request to a node. From this,
/// we can return the raw SCALE bytes that we were handed back, or we can
/// complete the decoding of the bytes into a [`DecodedValue`] type.
pub struct DecodedValueThunk {
type_id: u32,
metadata: Metadata,
scale_bytes: Vec<u8>,
}
impl DecodeWithMetadata for DecodedValueThunk {
type Target = Self;
fn decode_with_metadata(
bytes: &mut &[u8],
type_id: u32,
metadata: &Metadata,
) -> Result<Self::Target, Error> {
let mut v = Vec::with_capacity(bytes.len());
v.extend_from_slice(*bytes);
*bytes = &[];
Ok(DecodedValueThunk {
type_id,
metadata: metadata.clone(),
scale_bytes: v,
})
}
}
impl DecodedValueThunk {
/// Return the SCALE encoded bytes handed back from the node.
pub fn to_encoded(self) -> Vec<u8> {
self.scale_bytes
}
/// Return the SCALE encoded bytes handed back from the node without taking ownership of them.
pub fn encoded(&self) -> &[u8] {
&self.scale_bytes
}
/// Decode the SCALE encoded storage entry into a dynamic [`DecodedValue`] type.
pub fn to_value(&self) -> Result<DecodedValue, Error> {
DecodedValue::decode_with_metadata(
&mut &*self.scale_bytes,
self.type_id,
&self.metadata,
)
}
}