borsh/
schema_helpers.rs

1use crate::__private::maybestd::vec::Vec;
2use crate::from_slice;
3use crate::io::{Error, ErrorKind, Result};
4use crate::schema::{BorshSchemaContainer, SchemaMaxSerializedSizeError};
5use crate::{BorshDeserialize, BorshSchema, BorshSerialize};
6
7/// Deserialize this instance from a slice of bytes, but assume that at the beginning we have
8/// bytes describing the schema of the type. We deserialize this schema and verify that it is
9/// correct.
10pub fn try_from_slice_with_schema<T: BorshDeserialize + BorshSchema>(v: &[u8]) -> Result<T> {
11    let (schema, object) = from_slice::<(BorshSchemaContainer, T)>(v)?;
12    if schema_container_of::<T>() != schema {
13        return Err(Error::new(
14            ErrorKind::InvalidData,
15            "Borsh schema does not match",
16        ));
17    }
18    Ok(object)
19}
20
21/// Serialize object into a vector of bytes and prefix with the schema serialized as vector of
22/// bytes in Borsh format.
23pub fn try_to_vec_with_schema<T: BorshSerialize + BorshSchema + ?Sized>(
24    value: &T,
25) -> Result<Vec<u8>> {
26    let schema = schema_container_of::<T>();
27    let mut res = crate::to_vec(&schema)?;
28    value.serialize(&mut res)?;
29    Ok(res)
30}
31
32/// generate [BorshSchemaContainer] for type `T`
33///
34/// this is an alias of [BorshSchemaContainer::for_type]
35pub fn schema_container_of<T: BorshSchema + ?Sized>() -> BorshSchemaContainer {
36    BorshSchemaContainer::for_type::<T>()
37}
38
39/// Returns the largest possible size of a serialised object based solely on its type `T`.
40///
41/// this is a shortcut for using [BorshSchemaContainer::max_serialized_size]
42/// # Example
43///
44/// ```
45/// use borsh::schema::BorshSchemaContainer;
46///
47/// assert_eq!(Ok(8), borsh::max_serialized_size::<usize>());
48/// ```
49pub fn max_serialized_size<T: BorshSchema + ?Sized>(
50) -> core::result::Result<usize, SchemaMaxSerializedSizeError> {
51    let schema = BorshSchemaContainer::for_type::<T>();
52    schema.max_serialized_size()
53}