From be296f23b95213c0e2c4a3889b3146dd53bb904f Mon Sep 17 00:00:00 2001 From: Jonathan LEI Date: Tue, 22 Oct 2024 22:46:46 +0800 Subject: [PATCH] docs: better docs for `Encode` and `Decode` --- starknet-core/src/codec.rs | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/starknet-core/src/codec.rs b/starknet-core/src/codec.rs index b5ab08fb..443a5718 100644 --- a/starknet-core/src/codec.rs +++ b/starknet-core/src/codec.rs @@ -20,6 +20,33 @@ pub trait FeltWriter { /// Any type that can be serialized into a series of [Felt]s. This trait corresponds to the /// `serialize` function of the Cairo `Serde` trait. +/// +/// This trait can be derived as long as all the fields in type implement [`Encode`]. +/// +/// # Example +/// +/// This example demonstrates deriving the trait and then using it to serialize an instance into +/// [`Vec`]. +/// +/// ```rust +/// use starknet_core::codec::Encode; +/// # use starknet_core::types::Felt; +/// +/// #[derive(Encode)] +/// struct CairoType { +/// a: u32, +/// b: Option, +/// } +/// +/// let instance = CairoType { +/// a: 3, +/// b: Some(true), +/// }; +/// let mut serialized = vec![]; +/// instance.encode(&mut serialized); +/// +/// assert_eq!(vec![Felt::THREE, Felt::ZERO, Felt::ONE], serialized); +/// ``` pub trait Encode { /// Converts the type into a list of [`Felt`] and append them into the writer. fn encode(&self, writer: &mut W) -> Result<(), Error>; @@ -27,6 +54,32 @@ pub trait Encode { /// Any type that can be deserialized from a series of [Felt]s. This trait corresponds to the /// `deserialize` function of the Cairo `Serde` trait. +/// +/// This trait can be derived as long as all the fields in type implement [`Encode`]. +/// +/// # Example +/// +/// This example demonstrates deriving the trait and then using it to deserialize an instance from +/// [`Vec`]. +/// +/// ```rust +/// use starknet_core::codec::Decode; +/// # use starknet_core::types::Felt; +/// +/// #[derive(Debug, PartialEq, Eq, Decode)] +/// struct CairoType { +/// a: u32, +/// b: Option, +/// } +/// +/// assert_eq!( +/// CairoType { +/// a: 3, +/// b: Some(true) +/// }, +/// CairoType::decode(&[Felt::THREE, Felt::ZERO, Felt::ONE]).unwrap() +/// ); +/// ``` pub trait Decode<'a>: Sized { /// Converts into the type from a list of [`Felt`]. fn decode(reader: T) -> Result