linera_sdk/
extensions.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Extension traits with some common functionality.
5
6use serde::{de::DeserializeOwned, Serialize};
7
8/// Extension trait to deserialize a type from a vector of bytes using [`bcs`].
9pub trait FromBcsBytes: Sized {
10    /// Deserializes itself from a vector of bytes using [`bcs`].
11    fn from_bcs_bytes(bytes: &[u8]) -> Result<Self, bcs::Error>;
12}
13
14impl<T> FromBcsBytes for T
15where
16    T: DeserializeOwned,
17{
18    fn from_bcs_bytes(bytes: &[u8]) -> Result<Self, bcs::Error> {
19        bcs::from_bytes(bytes)
20    }
21}
22
23/// Extension trait to serialize a type into a vector of bytes using [`bcs`].
24pub trait ToBcsBytes {
25    /// Serializes itself into a vector of bytes using [`bcs`].
26    fn to_bcs_bytes(&self) -> Result<Vec<u8>, bcs::Error>;
27}
28
29impl<T> ToBcsBytes for T
30where
31    T: Serialize,
32{
33    fn to_bcs_bytes(&self) -> Result<Vec<u8>, bcs::Error> {
34        bcs::to_bytes(self)
35    }
36}