Skip to content

[Rust] Support Rc/Arc/Weak serialization for object graph support #2621

@chaokunyang

Description

@chaokunyang

Feature Request

When to use Rc/Arc/Weak:

  1. Rc (Reference Counted)
  • Use when: You need multiple parts of your single-threaded program to share ownership of a value, and you want the value to be deallocated only when the last owner is gone.
  • Example: A tree structure where different nodes might need to refer to the same parent node.
  1. Arc (Atomic Reference Counted)- Use when: You need multiple threads to share ownership of data. It's the thread-safe version of Rc.
  • Example: Multiple threads need to access and read the same immutable configuration data.
  1. Weak (Weak Reference):
  • Use when: You have a reference cycle between Rc or Arc pointers that would cause a memory leak. A Weak pointer doesn't count towards the strong reference count, allowing the data to be deallocated even if Weak pointers still exist.
  • How it works: To access the data, a Weak reference must be "upgraded" to a strong Rc or Arc reference. If the data has already been deallocated, the upgrade will fail, returning a null pointer, which is how you check for validity.
  • Example: In a doubly linked list, where each node has a next pointer (strong) and a prev pointer (weak) to avoid a circular dependency that would prevent the nodes from being deallocated

Object graph is common in languages like java/python/go, by using Rc/Arc/Weak, we can implement similiar functionalities in rust. Fory needs to support Rc/Arc/Weak serialization.

Is your feature request related to a problem? Please describe

No response

Describe the solution you'd like

Like we did in java/python, we can implement a RefResolver in rust, which track reference for Rc/Arc/Weak by using a Map. At deserialization, we can use a Vec<Ref> to hold those reference to rebuild the reference relationship.

Ref can be defined as:

enum Ref {
  RcRef(Box<dyn Any>),
  ArcRef(Box<dyn Any>)
}

https://github.com/apache/fory/blob/main/java/fory-core/src/main/java/org/apache/fory/resolver/MapRefResolver.java can be used an example for implementation in rust.

Describe alternatives you've considered

No response

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions