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 6a6174613 chore(Rust): Streamline code (#2828)
6a6174613 is described below

commit 6a6174613b8492924ea8920283637655fd91933d
Author: weipeng <[email protected]>
AuthorDate: Fri Oct 24 14:10:54 2025 +0800

    chore(Rust): Streamline code (#2828)
    
    <!--
    **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?
    
    - Add API `borrow_mut` for `Pool` and make `get` `put` private to avoid
    forgeting call put after get
    - Make `EMPTY_STRING` const which was supposed to be
    
    <!-- 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/fory-core/src/fory.rs                   | 93 ++++++++++++++--------------
 rust/fory-core/src/resolver/context.rs       | 12 +++-
 rust/fory-core/src/resolver/type_resolver.rs |  2 +-
 3 files changed, 57 insertions(+), 50 deletions(-)

diff --git a/rust/fory-core/src/fory.rs b/rust/fory-core/src/fory.rs
index f9da31b9e..5e6b78daa 100644
--- a/rust/fory-core/src/fory.rs
+++ b/rust/fory-core/src/fory.rs
@@ -369,20 +369,19 @@ impl Fory {
     /// ```
     pub fn serialize<T: Serializer>(&self, record: &T) -> Result<Vec<u8>, 
Error> {
         let pool = self.get_writer_pool()?;
-        let mut context = pool.get();
-        match self.serialize_with_context(record, &mut context) {
-            Ok(_) => {
-                let result = context.writer.dump();
-                context.writer.reset();
-                pool.put(context);
-                Ok(result)
-            }
-            Err(err) => {
-                context.writer.reset();
-                pool.put(context);
-                Err(err)
-            }
-        }
+        pool.borrow_mut(
+            |context| match self.serialize_with_context(record, context) {
+                Ok(_) => {
+                    let result = context.writer.dump();
+                    context.writer.reset();
+                    Ok(result)
+                }
+                Err(err) => {
+                    context.writer.reset();
+                    Err(err)
+                }
+            },
+        )
     }
 
     /// Serializes a value of type `T` into the provided byte buffer.
@@ -507,20 +506,20 @@ impl Fory {
     ) -> Result<usize, Error> {
         let pool = self.get_writer_pool()?;
         let start = buf.len();
-        let mut context = pool.get();
-        // Context go from pool would be 'static. but context hold the buffer 
through `writer` field, so we should make buffer live longer.
-        // After serializing, `detach_writer` will be called, the writer in 
context will be set to dangling pointer.
-        // So it's safe to make buf live to the end of this method.
-        let outlive_buffer = unsafe { mem::transmute::<&mut Vec<u8>, &mut 
Vec<u8>>(buf) };
-        context.attach_writer(Writer::from_buffer(outlive_buffer));
-        let result = self.serialize_with_context(record, &mut context);
-        let written_size = context.writer.len() - start;
-        context.detach_writer();
-        pool.put(context);
-        match result {
-            Ok(_) => Ok(written_size),
-            Err(err) => Err(err),
-        }
+        pool.borrow_mut(|context| {
+            // Context go from pool would be 'static. but context hold the 
buffer through `writer` field, so we should make buffer live longer.
+            // After serializing, `detach_writer` will be called, the writer 
in context will be set to dangling pointer.
+            // So it's safe to make buf live to the end of this method.
+            let outlive_buffer = unsafe { mem::transmute::<&mut Vec<u8>, &mut 
Vec<u8>>(buf) };
+            context.attach_writer(Writer::from_buffer(outlive_buffer));
+            let result = self.serialize_with_context(record, context);
+            let written_size = context.writer.len() - start;
+            context.detach_writer();
+            match result {
+                Ok(_) => Ok(written_size),
+                Err(err) => Err(err),
+            }
+        })
     }
 
     #[inline(always)]
@@ -830,14 +829,14 @@ impl Fory {
     /// ```
     pub fn deserialize<T: Serializer + ForyDefault>(&self, bf: &[u8]) -> 
Result<T, Error> {
         let pool = self.get_read_pool()?;
-        let mut context = pool.get();
-        context.init(self.max_dyn_depth);
-        let outlive_buffer = unsafe { mem::transmute::<&[u8], &[u8]>(bf) };
-        context.attach_reader(Reader::new(outlive_buffer));
-        let result = self.deserialize_with_context(&mut context);
-        context.detach_reader();
-        pool.put(context);
-        result
+        pool.borrow_mut(|context| {
+            context.init(self.max_dyn_depth);
+            let outlive_buffer = unsafe { mem::transmute::<&[u8], &[u8]>(bf) };
+            context.attach_reader(Reader::new(outlive_buffer));
+            let result = self.deserialize_with_context(context);
+            context.detach_reader();
+            result
+        })
     }
 
     pub fn deserialize_from<T: Serializer + ForyDefault>(
@@ -845,17 +844,17 @@ impl Fory {
         reader: &mut Reader,
     ) -> Result<T, Error> {
         let pool = self.get_read_pool()?;
-        let mut context = pool.get();
-        context.init(self.max_dyn_depth);
-        let outlive_buffer = unsafe { mem::transmute::<&[u8], 
&[u8]>(reader.bf) };
-        let mut new_reader = Reader::new(outlive_buffer);
-        new_reader.set_cursor(reader.cursor);
-        context.attach_reader(new_reader);
-        let result = self.deserialize_with_context(&mut context);
-        let end = context.detach_reader().get_cursor();
-        reader.set_cursor(end);
-        pool.put(context);
-        result
+        pool.borrow_mut(|context| {
+            context.init(self.max_dyn_depth);
+            let outlive_buffer = unsafe { mem::transmute::<&[u8], 
&[u8]>(reader.bf) };
+            let mut new_reader = Reader::new(outlive_buffer);
+            new_reader.set_cursor(reader.cursor);
+            context.attach_reader(new_reader);
+            let result = self.deserialize_with_context(context);
+            let end = context.detach_reader().get_cursor();
+            reader.set_cursor(end);
+            result
+        })
     }
 
     #[inline(always)]
diff --git a/rust/fory-core/src/resolver/context.rs 
b/rust/fory-core/src/resolver/context.rs
index b8b96b4a5..b69a05616 100644
--- a/rust/fory-core/src/resolver/context.rs
+++ b/rust/fory-core/src/resolver/context.rs
@@ -466,13 +466,21 @@ impl<T> Pool<T> {
     }
 
     #[inline(always)]
-    pub fn get(&self) -> T {
+    pub fn borrow_mut<Result>(&self, handler: impl FnOnce(&mut T) -> Result) 
-> Result {
+        let mut obj = self.get();
+        let result = handler(&mut obj);
+        self.put(obj);
+        result
+    }
+
+    #[inline(always)]
+    fn get(&self) -> T {
         self.items.lock().pop().unwrap_or_else(|| (self.factory)())
     }
 
     // put back manually
     #[inline(always)]
-    pub fn put(&self, item: T) {
+    fn put(&self, item: T) {
         self.items.lock().push(item);
     }
 }
diff --git a/rust/fory-core/src/resolver/type_resolver.rs 
b/rust/fory-core/src/resolver/type_resolver.rs
index 4a6a97ce0..35bd9b53a 100644
--- a/rust/fory-core/src/resolver/type_resolver.rs
+++ b/rust/fory-core/src/resolver/type_resolver.rs
@@ -43,7 +43,7 @@ type WriteDataFn = fn(&dyn Any, &mut WriteContext, 
has_generics: bool) -> Result
 type ReadDataFn = fn(&mut ReadContext) -> Result<Box<dyn Any>, Error>;
 type ToSerializerFn = fn(Box<dyn Any>) -> Result<Box<dyn Serializer>, Error>;
 type GetSortedFieldInfosFn = fn(&TypeResolver) -> Result<Vec<FieldInfo>, 
Error>;
-static EMPTY_STRING: String = String::new();
+const EMPTY_STRING: String = String::new();
 
 #[derive(Clone, Debug)]
 pub struct Harness {


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

Reply via email to