soroban_sdk/xdr.rs
1//! Convert values to and from [Bytes].
2//!
3//! All types that are convertible to and from [Val] implement the
4//! [ToXdr] and [FromXdr] traits, and serialize to the ScVal XDR form.
5//!
6//! ### Examples
7//!
8//! ```
9//! use soroban_sdk::{
10//! xdr::{FromXdr, ToXdr},
11//! Env, Bytes, IntoVal, TryFromVal,
12//! };
13//!
14//! let env = Env::default();
15//!
16//! let value: u32 = 5;
17//!
18//! let bytes = value.to_xdr(&env);
19//! assert_eq!(bytes.len(), 8);
20//!
21//! let roundtrip = u32::from_xdr(&env, &bytes);
22//! assert_eq!(roundtrip, Ok(value));
23//! ```
24
25use crate::{
26 env::internal::Env as _, unwrap::UnwrapInfallible, Bytes, Env, IntoVal, TryFromVal, Val,
27};
28
29// Re-export all the XDR from the environment.
30pub use crate::env::xdr::*;
31
32/// Implemented by types that can be serialized to [Bytes].
33///
34/// All types that are convertible to [Val] are implemented.
35pub trait ToXdr {
36 fn to_xdr(self, env: &Env) -> Bytes;
37}
38
39/// Implemented by types that can be deserialized from [Bytes].
40///
41/// All types that are convertible from [Val] are implemented.
42pub trait FromXdr: Sized {
43 type Error;
44 fn from_xdr(env: &Env, b: &Bytes) -> Result<Self, Self::Error>;
45}
46
47impl<T> ToXdr for T
48where
49 T: IntoVal<Env, Val>,
50{
51 fn to_xdr(self, env: &Env) -> Bytes {
52 let val: Val = self.into_val(env);
53 let bin = env.serialize_to_bytes(val).unwrap_infallible();
54 unsafe { Bytes::unchecked_new(env.clone(), bin) }
55 }
56}
57
58impl<T> FromXdr for T
59where
60 T: TryFromVal<Env, Val>,
61{
62 type Error = T::Error;
63
64 fn from_xdr(env: &Env, b: &Bytes) -> Result<Self, Self::Error> {
65 let t = env.deserialize_from_bytes(b.into()).unwrap_infallible();
66 T::try_from_val(env, &t)
67 }
68}