Skip to content

Commit d7998e4

Browse files
expand docs on ToXdr and FromXdr traits
1 parent 3423e93 commit d7998e4

File tree

1 file changed

+54
-4
lines changed

1 file changed

+54
-4
lines changed

soroban-sdk/src/xdr.rs

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,68 @@ use crate::{
2929
// Re-export all the XDR from the environment.
3030
pub use crate::env::xdr::*;
3131

32-
/// Implemented by types that can be serialized to [Bytes].
32+
/// Implemented by types that can be serialized to [Bytes] as XDR.
3333
///
34-
/// All types that are convertible to [Val] are implemented.
34+
/// All types that are convertible to [Val] implement this trait. The value is
35+
/// first converted to a [Val], then serialized to XDR in its [ScVal] form.
36+
///
37+
/// ### Examples
38+
///
39+
/// ```
40+
/// use soroban_sdk::{xdr::ToXdr, Env};
41+
///
42+
/// let env = Env::default();
43+
///
44+
/// let value: u32 = 5;
45+
/// let bytes = value.to_xdr(&env);
46+
/// assert_eq!(bytes.len(), 8);
47+
/// ```
3548
pub trait ToXdr {
49+
/// Serializes the value to XDR as [Bytes].
3650
fn to_xdr(self, env: &Env) -> Bytes;
3751
}
3852

39-
/// Implemented by types that can be deserialized from [Bytes].
53+
/// Implemented by types that can be deserialized from [Bytes] containing XDR.
54+
///
55+
/// All types that are convertible from [Val] implement this trait. The bytes
56+
/// are deserialized from their [ScVal] XDR form into a [Val], then converted
57+
/// to the target type.
58+
///
59+
/// ### Errors
60+
///
61+
/// Returns an error if the [Val] cannot be converted into the target type.
62+
///
63+
/// ### Panics
64+
///
65+
/// Panics if the provided bytes are not valid XDR for an [ScVal].
66+
///
67+
/// ### Examples
68+
///
69+
/// ```
70+
/// use soroban_sdk::{xdr::{ToXdr, FromXdr}, Env};
71+
///
72+
/// let env = Env::default();
73+
///
74+
/// let value: u32 = 5;
75+
/// let bytes = value.to_xdr(&env);
4076
///
41-
/// All types that are convertible from [Val] are implemented.
77+
/// let roundtrip = u32::from_xdr(&env, &bytes);
78+
/// assert_eq!(roundtrip, Ok(5));
79+
/// ```
4280
pub trait FromXdr: Sized {
81+
/// The error type returned if the [Val] cannot be converted into the
82+
/// target type.
4383
type Error;
84+
/// Deserializes the value from XDR [Bytes].
85+
///
86+
/// ### Errors
87+
///
88+
/// Returns an error if the [Val] cannot be converted into the target
89+
/// type.
90+
///
91+
/// ### Panics
92+
///
93+
/// Panics if the provided bytes are not valid XDR for an [ScVal].
4494
fn from_xdr(env: &Env, b: &Bytes) -> Result<Self, Self::Error>;
4595
}
4696

0 commit comments

Comments
 (0)