This is an automated email from the ASF dual-hosted git repository.

chaokunyang pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/fory.git


The following commit(s) were added to refs/heads/main by this push:
     new 26a67c00d docs(rust): update serialize to deserialize from doc (#2830)
26a67c00d is described below

commit 26a67c00d5417bdfe1fce72fdd330354effca5f3
Author: Shawn Yang <[email protected]>
AuthorDate: Fri Oct 24 14:51:55 2025 +0800

    docs(rust): update serialize to deserialize from doc (#2830)
    
    <!--
    **Thanks for contributing to Apache Fory™.**
    
    **If this is your first time opening a PR on fory, you can refer to
    
[CONTRIBUTING.md](https://github.com/apache/fory/blob/main/CONTRIBUTING.md).**
    
    Contribution Checklist
    
    - The **Apache Fory™** community has requirements on the naming of pr
    titles. You can also find instructions in
    [CONTRIBUTING.md](https://github.com/apache/fory/blob/main/CONTRIBUTING.md).
    
    - Apache Fory™ has a strong focus on performance. If the PR you submit
    will have an impact on performance, please benchmark it first and
    provide the benchmark result here.
    -->
    
    ## Why?
    
    <!-- Describe the purpose of this PR. -->
    
    ## What does this PR do?
    
    <!-- Describe the details of this PR. -->
    
    ## Related issues
    
    <!--
    Is there any related issue? If this PR closes them you say say
    fix/closes:
    
    - #xxxx0
    - #xxxx1
    - Fixes #xxxx2
    -->
    
    ## Does this PR introduce any user-facing change?
    
    <!--
    If any user-facing interface changes, please [open an
    issue](https://github.com/apache/fory/issues/new/choose) describing the
    need to do so and update the document if necessary.
    
    Delete section if not applicable.
    -->
    
    - [ ] Does this PR introduce any public API change?
    - [ ] Does this PR introduce any binary protocol compatibility change?
    
    ## Benchmark
    
    <!--
    When the PR has an impact on performance (if you don't know whether the
    PR will have an impact on performance, you can submit the PR first, and
    if it will have impact on performance, the code reviewer will explain
    it), be sure to attach a benchmark data here.
    
    Delete section if not applicable.
    -->
---
 rust/README.md                | 14 +++++++++----
 rust/fory-core/src/error.rs   |  5 -----
 rust/fory-core/src/fory.rs    | 47 +++++++++++++++++++++++++++++++++++++++++++
 rust/fory/src/lib.rs          | 15 +++++++++++---
 rust/tests/tests/test_fory.rs | 29 +++++++++++++-------------
 5 files changed, 84 insertions(+), 26 deletions(-)

diff --git a/rust/README.md b/rust/README.md
index 264c55cd4..14cbcda34 100644
--- a/rust/README.md
+++ b/rust/README.md
@@ -38,7 +38,7 @@ fory = "0.13"
 ### Basic Example
 
 ```rust
-use fory::{Fory, Error};
+use fory::{Fory, Error, Reader};
 use fory::ForyObject;
 
 #[derive(ForyObject, Debug, PartialEq)]
@@ -50,7 +50,7 @@ struct User {
 
 fn main() -> Result<(), Error> {
     let mut fory = Fory::default();
-    fory.register::<User>(1);
+    fory.register::<User>(1)?;
 
     let user = User {
         name: "Alice".to_string(),
@@ -59,12 +59,18 @@ fn main() -> Result<(), Error> {
     };
 
     // Serialize
-    let bytes = fory.serialize(&user);
-
+    let bytes = fory.serialize(&user)?;
     // Deserialize
     let decoded: User = fory.deserialize(&bytes)?;
     assert_eq!(user, decoded);
 
+    // Serialize to specified buffer
+    let mut buf: Vec<u8> = vec![];
+    fory.serialize_to(&user, &mut buf)?;
+    // Deserialize from specified buffer
+    let mut reader = Reader::new(&buf);
+    let decoded: User = fory.deserialize_from(&mut reader)?;
+    assert_eq!(user, decoded);
     Ok(())
 }
 ```
diff --git a/rust/fory-core/src/error.rs b/rust/fory-core/src/error.rs
index 08cc3d568..7be8e9b56 100644
--- a/rust/fory-core/src/error.rs
+++ b/rust/fory-core/src/error.rs
@@ -16,7 +16,6 @@
 // under the License.
 
 use std::borrow::Cow;
-use std::io;
 use std::sync::OnceLock;
 
 use thiserror::Error;
@@ -110,10 +109,6 @@ pub enum Error {
     #[error("Buffer out of bound: {0} + {1} > {2}")]
     BufferOutOfBound(usize, usize, usize),
 
-    /// IO error from underlying operations.
-    #[error("IO error: {0}")]
-    Io(#[from] io::Error),
-
     /// Error during data encoding.
     ///
     /// Do not construct this variant directly; use [`Error::encode_error`] 
instead.
diff --git a/rust/fory-core/src/fory.rs b/rust/fory-core/src/fory.rs
index 5e6b78daa..9c34195dd 100644
--- a/rust/fory-core/src/fory.rs
+++ b/rust/fory-core/src/fory.rs
@@ -839,6 +839,53 @@ impl Fory {
         })
     }
 
+    /// Deserializes data from a `Reader` into a value of type `T`.
+    ///
+    /// This method is the paired read operation for 
[`serialize_to`](Self::serialize_to).
+    /// It reads serialized data from the current position of the reader and 
automatically
+    /// advances the cursor to the end of the read data, making it suitable 
for reading
+    /// multiple objects sequentially from the same buffer.
+    ///
+    /// # Type Parameters
+    ///
+    /// * `T` - The target type to deserialize into. Must implement 
`Serializer` and `ForyDefault`.
+    ///
+    /// # Arguments
+    ///
+    /// * `reader` - A mutable reference to the `Reader` containing the 
serialized data.
+    ///   The reader's cursor will be advanced to the end of the deserialized 
data.
+    ///
+    /// # Returns
+    ///
+    /// * `Ok(T)` - The deserialized value on success.
+    /// * `Err(Error)` - An error if deserialization fails (e.g., invalid 
format, type mismatch).
+    ///
+    /// # Notes
+    ///
+    /// - The reader's cursor is automatically updated after each successful 
read.
+    /// - This method is ideal for reading multiple objects from the same 
buffer sequentially.
+    /// - See [`serialize_to`](Self::serialize_to) for complete usage examples.
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```rust, ignore
+    /// use fory_core::{Fory, Reader};
+    /// use fory_derive::ForyObject;
+    ///
+    /// #[derive(ForyObject)]
+    /// struct Point { x: i32, y: i32 }
+    ///
+    /// let fory = Fory::default();
+    /// let point = Point { x: 10, y: 20 };
+    ///
+    /// let mut buf = Vec::new();
+    /// fory.serialize_to(&point, &mut buf).unwrap();
+    ///
+    /// let mut reader = Reader::new(&buf);
+    /// let deserialized: Point = fory.deserialize_from(&mut reader).unwrap();
+    /// ```
     pub fn deserialize_from<T: Serializer + ForyDefault>(
         &self,
         reader: &mut Reader,
diff --git a/rust/fory/src/lib.rs b/rust/fory/src/lib.rs
index 778c94bbe..7a7c82dcb 100644
--- a/rust/fory/src/lib.rs
+++ b/rust/fory/src/lib.rs
@@ -56,7 +56,7 @@
 //! ### Basic Example
 //!
 //! ```rust
-//! use fory::{Fory, Error};
+//! use fory::{Fory, Error, Reader};
 //! use fory::ForyObject;
 //!
 //! #[derive(ForyObject, Debug, PartialEq)]
@@ -68,7 +68,7 @@
 //!
 //! # fn main() -> Result<(), Error> {
 //! let mut fory = Fory::default();
-//! fory.register::<User>(1);
+//! fory.register::<User>(1)?;
 //!
 //! let user = User {
 //!     name: "Alice".to_string(),
@@ -76,9 +76,17 @@
 //!     email: "[email protected]".to_string(),
 //! };
 //!
+//! // Serialize and deserialize
 //! let bytes = fory.serialize(&user)?;
 //! let decoded: User = fory.deserialize(&bytes)?;
 //! assert_eq!(user, decoded);
+//!
+//! // Serialize to specified buffer and deserialize from it
+//! let mut buf: Vec<u8> = vec![];
+//! fory.serialize_to(&user, &mut buf)?;
+//! let mut reader = Reader::new(&buf);
+//! let decoded: User = fory.deserialize_from(&mut reader)?;
+//! assert_eq!(user, decoded);
 //! # Ok(())
 //! # }
 //! ```
@@ -1093,6 +1101,7 @@
 
 pub use fory_core::{
     error::Error, fory::Fory, register_trait_type, row::from_row, row::to_row, 
types::TypeId,
-    ArcWeak, ForyDefault, RcWeak, ReadContext, Serializer, TypeResolver, 
WriteContext,
+    ArcWeak, ForyDefault, RcWeak, ReadContext, Reader, Serializer, 
TypeResolver, WriteContext,
+    Writer,
 };
 pub use fory_derive::{ForyObject, ForyRow};
diff --git a/rust/tests/tests/test_fory.rs b/rust/tests/tests/test_fory.rs
index 111156b04..541d36cbc 100644
--- a/rust/tests/tests/test_fory.rs
+++ b/rust/tests/tests/test_fory.rs
@@ -15,6 +15,7 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use fory_core::buffer::Reader;
 use fory_core::fory::Fory;
 use fory_derive::ForyObject;
 
@@ -97,7 +98,7 @@ fn test_serialize_to_detailed() {
     let mut buf = Vec::new();
     let len1 = fory.serialize_to(&p1, &mut buf).unwrap();
     assert_eq!(len1, buf.len());
-    let deserialized1: Point = fory.deserialize(&buf).unwrap();
+    let deserialized1: Point = fory.deserialize_from(&mut 
Reader::new(&buf)).unwrap();
     assert_eq!(p1, deserialized1);
 
     // Test 2: Multiple serializations to the same buffer
@@ -113,9 +114,10 @@ fn test_serialize_to_detailed() {
     assert_eq!(offset1, len2_first);
     assert_eq!(offset2, len2_first + len2_second);
 
-    // Deserialize both objects from the buffer
-    let des2: Point = fory.deserialize(&buf[0..offset1]).unwrap();
-    let des3: Point = fory.deserialize(&buf[offset1..offset2]).unwrap();
+    // Deserialize both objects from the buffer using a single reader
+    let mut reader = Reader::new(&buf);
+    let des2: Point = fory.deserialize_from(&mut reader).unwrap();
+    let des3: Point = fory.deserialize_from(&mut reader).unwrap();
     assert_eq!(p2, des2);
     assert_eq!(p3, des3);
 
@@ -129,7 +131,7 @@ fn test_serialize_to_detailed() {
     buf.clear();
     let len3 = fory.serialize_to(&line, &mut buf).unwrap();
     assert_eq!(len3, buf.len());
-    let deserialized_line: Line = fory.deserialize(&buf).unwrap();
+    let deserialized_line: Line = fory.deserialize_from(&mut 
Reader::new(&buf)).unwrap();
     assert_eq!(line, deserialized_line);
 
     // Test 4: Writing with pre-allocated header space
@@ -150,8 +152,10 @@ fn test_serialize_to_detailed() {
     let stored_len = u64::from_le_bytes(buf[0..8].try_into().unwrap()) as 
usize;
     assert_eq!(stored_len, data_len);
 
-    // Verify we can deserialize the data portion
-    let des4: Point = fory.deserialize(&buf[header_size..]).unwrap();
+    // Verify we can deserialize the data portion by skipping the header
+    let mut reader = Reader::new(&buf);
+    reader.set_cursor(header_size);
+    let des4: Point = fory.deserialize_from(&mut reader).unwrap();
     assert_eq!(p4, des4);
 
     // Test 5: Buffer reuse with resize (capacity preservation)
@@ -180,17 +184,14 @@ fn test_serialize_to_detailed() {
         Point { x: 5, y: 25 },
     ];
 
-    let mut offsets = vec![0];
     for point in &points {
         fory.serialize_to(point, &mut buf).unwrap();
-        offsets.push(buf.len());
     }
 
-    // Deserialize all objects and verify
-    for (i, point) in points.iter().enumerate() {
-        let start = offsets[i];
-        let end = offsets[i + 1];
-        let deserialized: Point = fory.deserialize(&buf[start..end]).unwrap();
+    // Deserialize all objects and verify using a single reader
+    let mut reader = Reader::new(&buf);
+    for point in &points {
+        let deserialized: Point = fory.deserialize_from(&mut reader).unwrap();
         assert_eq!(*point, deserialized);
     }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to