Skip to content

Commit 26a67c0

Browse files
authored
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. -->
1 parent 4313a5d commit 26a67c0

File tree

5 files changed

+84
-26
lines changed

5 files changed

+84
-26
lines changed

rust/README.md

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ fory = "0.13"
3838
### Basic Example
3939

4040
```rust
41-
use fory::{Fory, Error};
41+
use fory::{Fory, Error, Reader};
4242
use fory::ForyObject;
4343

4444
#[derive(ForyObject, Debug, PartialEq)]
@@ -50,7 +50,7 @@ struct User {
5050

5151
fn main() -> Result<(), Error> {
5252
let mut fory = Fory::default();
53-
fory.register::<User>(1);
53+
fory.register::<User>(1)?;
5454

5555
let user = User {
5656
name: "Alice".to_string(),
@@ -59,12 +59,18 @@ fn main() -> Result<(), Error> {
5959
};
6060

6161
// Serialize
62-
let bytes = fory.serialize(&user);
63-
62+
let bytes = fory.serialize(&user)?;
6463
// Deserialize
6564
let decoded: User = fory.deserialize(&bytes)?;
6665
assert_eq!(user, decoded);
6766

67+
// Serialize to specified buffer
68+
let mut buf: Vec<u8> = vec![];
69+
fory.serialize_to(&user, &mut buf)?;
70+
// Deserialize from specified buffer
71+
let mut reader = Reader::new(&buf);
72+
let decoded: User = fory.deserialize_from(&mut reader)?;
73+
assert_eq!(user, decoded);
6874
Ok(())
6975
}
7076
```

rust/fory-core/src/error.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
// under the License.
1717

1818
use std::borrow::Cow;
19-
use std::io;
2019
use std::sync::OnceLock;
2120

2221
use thiserror::Error;
@@ -110,10 +109,6 @@ pub enum Error {
110109
#[error("Buffer out of bound: {0} + {1} > {2}")]
111110
BufferOutOfBound(usize, usize, usize),
112111

113-
/// IO error from underlying operations.
114-
#[error("IO error: {0}")]
115-
Io(#[from] io::Error),
116-
117112
/// Error during data encoding.
118113
///
119114
/// Do not construct this variant directly; use [`Error::encode_error`] instead.

rust/fory-core/src/fory.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -839,6 +839,53 @@ impl Fory {
839839
})
840840
}
841841

842+
/// Deserializes data from a `Reader` into a value of type `T`.
843+
///
844+
/// This method is the paired read operation for [`serialize_to`](Self::serialize_to).
845+
/// It reads serialized data from the current position of the reader and automatically
846+
/// advances the cursor to the end of the read data, making it suitable for reading
847+
/// multiple objects sequentially from the same buffer.
848+
///
849+
/// # Type Parameters
850+
///
851+
/// * `T` - The target type to deserialize into. Must implement `Serializer` and `ForyDefault`.
852+
///
853+
/// # Arguments
854+
///
855+
/// * `reader` - A mutable reference to the `Reader` containing the serialized data.
856+
/// The reader's cursor will be advanced to the end of the deserialized data.
857+
///
858+
/// # Returns
859+
///
860+
/// * `Ok(T)` - The deserialized value on success.
861+
/// * `Err(Error)` - An error if deserialization fails (e.g., invalid format, type mismatch).
862+
///
863+
/// # Notes
864+
///
865+
/// - The reader's cursor is automatically updated after each successful read.
866+
/// - This method is ideal for reading multiple objects from the same buffer sequentially.
867+
/// - See [`serialize_to`](Self::serialize_to) for complete usage examples.
868+
///
869+
/// # Examples
870+
///
871+
/// Basic usage:
872+
///
873+
/// ```rust, ignore
874+
/// use fory_core::{Fory, Reader};
875+
/// use fory_derive::ForyObject;
876+
///
877+
/// #[derive(ForyObject)]
878+
/// struct Point { x: i32, y: i32 }
879+
///
880+
/// let fory = Fory::default();
881+
/// let point = Point { x: 10, y: 20 };
882+
///
883+
/// let mut buf = Vec::new();
884+
/// fory.serialize_to(&point, &mut buf).unwrap();
885+
///
886+
/// let mut reader = Reader::new(&buf);
887+
/// let deserialized: Point = fory.deserialize_from(&mut reader).unwrap();
888+
/// ```
842889
pub fn deserialize_from<T: Serializer + ForyDefault>(
843890
&self,
844891
reader: &mut Reader,

rust/fory/src/lib.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
//! ### Basic Example
5757
//!
5858
//! ```rust
59-
//! use fory::{Fory, Error};
59+
//! use fory::{Fory, Error, Reader};
6060
//! use fory::ForyObject;
6161
//!
6262
//! #[derive(ForyObject, Debug, PartialEq)]
@@ -68,17 +68,25 @@
6868
//!
6969
//! # fn main() -> Result<(), Error> {
7070
//! let mut fory = Fory::default();
71-
//! fory.register::<User>(1);
71+
//! fory.register::<User>(1)?;
7272
//!
7373
//! let user = User {
7474
//! name: "Alice".to_string(),
7575
//! age: 30,
7676
//! email: "[email protected]".to_string(),
7777
//! };
7878
//!
79+
//! // Serialize and deserialize
7980
//! let bytes = fory.serialize(&user)?;
8081
//! let decoded: User = fory.deserialize(&bytes)?;
8182
//! assert_eq!(user, decoded);
83+
//!
84+
//! // Serialize to specified buffer and deserialize from it
85+
//! let mut buf: Vec<u8> = vec![];
86+
//! fory.serialize_to(&user, &mut buf)?;
87+
//! let mut reader = Reader::new(&buf);
88+
//! let decoded: User = fory.deserialize_from(&mut reader)?;
89+
//! assert_eq!(user, decoded);
8290
//! # Ok(())
8391
//! # }
8492
//! ```
@@ -1093,6 +1101,7 @@
10931101
10941102
pub use fory_core::{
10951103
error::Error, fory::Fory, register_trait_type, row::from_row, row::to_row, types::TypeId,
1096-
ArcWeak, ForyDefault, RcWeak, ReadContext, Serializer, TypeResolver, WriteContext,
1104+
ArcWeak, ForyDefault, RcWeak, ReadContext, Reader, Serializer, TypeResolver, WriteContext,
1105+
Writer,
10971106
};
10981107
pub use fory_derive::{ForyObject, ForyRow};

rust/tests/tests/test_fory.rs

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
// specific language governing permissions and limitations
1616
// under the License.
1717

18+
use fory_core::buffer::Reader;
1819
use fory_core::fory::Fory;
1920
use fory_derive::ForyObject;
2021

@@ -97,7 +98,7 @@ fn test_serialize_to_detailed() {
9798
let mut buf = Vec::new();
9899
let len1 = fory.serialize_to(&p1, &mut buf).unwrap();
99100
assert_eq!(len1, buf.len());
100-
let deserialized1: Point = fory.deserialize(&buf).unwrap();
101+
let deserialized1: Point = fory.deserialize_from(&mut Reader::new(&buf)).unwrap();
101102
assert_eq!(p1, deserialized1);
102103

103104
// Test 2: Multiple serializations to the same buffer
@@ -113,9 +114,10 @@ fn test_serialize_to_detailed() {
113114
assert_eq!(offset1, len2_first);
114115
assert_eq!(offset2, len2_first + len2_second);
115116

116-
// Deserialize both objects from the buffer
117-
let des2: Point = fory.deserialize(&buf[0..offset1]).unwrap();
118-
let des3: Point = fory.deserialize(&buf[offset1..offset2]).unwrap();
117+
// Deserialize both objects from the buffer using a single reader
118+
let mut reader = Reader::new(&buf);
119+
let des2: Point = fory.deserialize_from(&mut reader).unwrap();
120+
let des3: Point = fory.deserialize_from(&mut reader).unwrap();
119121
assert_eq!(p2, des2);
120122
assert_eq!(p3, des3);
121123

@@ -129,7 +131,7 @@ fn test_serialize_to_detailed() {
129131
buf.clear();
130132
let len3 = fory.serialize_to(&line, &mut buf).unwrap();
131133
assert_eq!(len3, buf.len());
132-
let deserialized_line: Line = fory.deserialize(&buf).unwrap();
134+
let deserialized_line: Line = fory.deserialize_from(&mut Reader::new(&buf)).unwrap();
133135
assert_eq!(line, deserialized_line);
134136

135137
// Test 4: Writing with pre-allocated header space
@@ -150,8 +152,10 @@ fn test_serialize_to_detailed() {
150152
let stored_len = u64::from_le_bytes(buf[0..8].try_into().unwrap()) as usize;
151153
assert_eq!(stored_len, data_len);
152154

153-
// Verify we can deserialize the data portion
154-
let des4: Point = fory.deserialize(&buf[header_size..]).unwrap();
155+
// Verify we can deserialize the data portion by skipping the header
156+
let mut reader = Reader::new(&buf);
157+
reader.set_cursor(header_size);
158+
let des4: Point = fory.deserialize_from(&mut reader).unwrap();
155159
assert_eq!(p4, des4);
156160

157161
// Test 5: Buffer reuse with resize (capacity preservation)
@@ -180,17 +184,14 @@ fn test_serialize_to_detailed() {
180184
Point { x: 5, y: 25 },
181185
];
182186

183-
let mut offsets = vec![0];
184187
for point in &points {
185188
fory.serialize_to(point, &mut buf).unwrap();
186-
offsets.push(buf.len());
187189
}
188190

189-
// Deserialize all objects and verify
190-
for (i, point) in points.iter().enumerate() {
191-
let start = offsets[i];
192-
let end = offsets[i + 1];
193-
let deserialized: Point = fory.deserialize(&buf[start..end]).unwrap();
191+
// Deserialize all objects and verify using a single reader
192+
let mut reader = Reader::new(&buf);
193+
for point in &points {
194+
let deserialized: Point = fory.deserialize_from(&mut reader).unwrap();
194195
assert_eq!(*point, deserialized);
195196
}
196197
}

0 commit comments

Comments
 (0)