Skip to main content

GcWeak

Struct GcWeak 

Source
pub struct GcWeak<T: GcNode> { /* private fields */ }
Expand description

Weak reference

Implementations§

Source§

impl<T: GcNode> GcWeak<T>

Source

pub fn index(&self) -> u16

get weakref index

Source

pub fn version(&self) -> u16

Source

pub fn upgrade(&self, heap: &GcHeap) -> Option<GcRef<T>>

Upgrade weak reference to strong reference

Examples found in repository?
examples/advanced_features.rs (line 94)
78fn demonstrate_weak_references(
79    heap: &mut GcHeap,
80    partition: gc_lite::GcPartitionId,
81) -> GcResult<()> {
82    println!("1. Create strong and weak references...");
83
84    let strong_ref =
85        unsafe { heap.alloc_root_raw(partition, MyString(String::from("Strong Reference Data"))) }
86            .map_err(|(err, _)| err)?;
87
88    let weak_ref = heap.downgrade(&strong_ref);
89    println!("  Created strong reference: {:?}", strong_ref);
90    println!("  Created weak reference: {:?}", weak_ref);
91
92    // Upgrade weak reference
93    println!("\n2. Upgrade weak reference...");
94    match weak_ref.upgrade(heap) {
95        Some(upgraded) => {
96            let data = upgraded.deref();
97            println!("  Weak reference upgrade successful: '{}'", data);
98            assert_eq!(data, "Strong Reference Data");
99        }
100        None => println!("  Weak reference upgrade failed"),
101    }
102
103    // Try upgrading after releasing strong reference
104    println!("\n3. Upgrade weak reference after releasing strong reference...");
105    heap.garbage_collect(partition, GcHeap::DUMMY_DISPOSE_CALLBACK);
106
107    match weak_ref.upgrade(heap) {
108        Some(_) => {
109            println!("  Weak reference can still be upgraded (object may still be in memory)")
110        }
111        None => println!("  Weak reference upgrade failed (object has been collected)"),
112    }
113
114    Ok(())
115}
More examples
Hide additional examples
examples/basic_usage.rs (line 171)
49fn main() -> GcResult<()> {
50    println!("=== Basic usage example of partitioned garbage collection system ===");
51
52    // Create garbage collection context
53    let mut heap = GcHeap::new(&GC_TYPE_REGISTRY);
54
55    println!("Initial state:");
56    println!("  Number of partitions: {}", heap.partition_ids().len());
57
58    // Create two partitions
59    println!("\nCreate partitions:");
60    let partition1 = heap.create_partition();
61    let partition2 = heap.create_partition();
62    println!("  Created partition1: {:?}", partition1);
63    println!("  Created partition2: {:?}", partition2);
64    println!("  Number of partitions: {}", heap.partition_ids().len());
65
66    // Allocate objects in partition1
67    println!("\nAllocate objects in partition1:");
68    let obj1 = unsafe { heap.alloc_raw(partition1, MyString(String::from("Hello"))) }
69        .map_err(|(err, _)| err)?;
70    let obj2 = unsafe { heap.alloc_raw(partition1, MyI32(42)) }.map_err(|(err, _)| err)?;
71    let obj3 = unsafe { heap.alloc_raw(partition1, MyString(String::from("VectorData"))) }
72        .map_err(|(err, _)| err)?;
73
74    println!("  Created string: '{}'", obj1.deref());
75    println!("  Created number: {}", obj2.deref());
76    println!("  Created string: '{}'", obj3.deref());
77
78    // Allocate objects in partition2
79    println!("\nAllocate objects in partition2:");
80    let obj4 = unsafe { heap.alloc_raw(partition2, MyString(String::from("World"))) }
81        .map_err(|(err, _)| err)?;
82    let obj5 = unsafe { heap.alloc_raw(partition2, MyI32(99)) }.map_err(|(err, _)| err)?;
83
84    println!("  Created string: '{}'", obj4.deref());
85    println!("  Created number: {}", obj5.deref());
86
87    // Display partition status
88    println!("\nPartition status:");
89    for partition_id in heap.partition_ids() {
90        if let Some(partition) = heap.partition(partition_id) {
91            let limit = heap.memory_limit();
92            let usage = if limit > 0 {
93                format!(
94                    "{}/{} bytes ({:.1}%)",
95                    partition.memory_used(),
96                    limit,
97                    (partition.memory_used() as f64 / limit as f64) * 100.0
98                )
99            } else {
100                format!("{}/∞ bytes", partition.memory_used())
101            };
102            println!(
103                "  {:?}: {} [自动GC: {}]",
104                partition_id,
105                usage,
106                if heap.gc_threshold() > 0 {
107                    "Enabled"
108                } else {
109                    "Disabled"
110                }
111            );
112        }
113    }
114
115    // Root objects are now implicitly managed by stack variables (e.g., obj1, obj2).
116    // No explicit `set_root` calls are needed for them.
117    println!("\nRoot objects are held by variables:");
118    println!("  Roots: obj1, obj2, obj3, obj4, obj5");
119
120    // Manually trigger garbage collection for partition1
121    println!("\nManually trigger garbage collection for partition1...");
122    let freed = heap.garbage_collect(partition1, GcHeap::DUMMY_DISPOSE_CALLBACK);
123    println!("  Collected {} bytes", freed);
124
125    // Verify root objects are still valid
126    println!("\nVerify partition1 root objects are still valid:");
127    println!("  Object1: '{}'", obj1.deref());
128    println!("  Object2: {}", obj2.deref());
129
130    // Manually trigger garbage collection for partition2
131    println!("\nManually trigger garbage collection for partition2...");
132    let freed = heap.garbage_collect(partition2, GcHeap::DUMMY_DISPOSE_CALLBACK);
133    println!("  Collected {} bytes", freed);
134
135    // Verify partition2 root objects are still valid
136    println!("\nVerify partition2 root objects are still valid:");
137    println!("  Object4: '{}'", obj4.deref());
138
139    // Trigger garbage collection for partition1 again to collect unreferenced objects
140    println!("\nTrigger garbage collection for partition1 again...");
141    // obj2 is no longer explicitly un-rooted, but we can simulate it going out of scope
142    // to test collection. For this example, we'll just collect other garbage.
143    let freed = heap.garbage_collect(partition1, GcHeap::DUMMY_DISPOSE_CALLBACK);
144    println!("  Collected {} bytes", freed);
145
146    // Verify remaining root objects are still valid
147    println!("\nVerify remaining root objects are still valid:");
148    println!("  Object1: '{}'", obj1.deref());
149    println!("  Object2: {} (still a root)", obj2.deref());
150
151    // Demonstrate automatic garbage collection
152    println!("\nDemonstrate automatic garbage collection...");
153
154    // Create a small partition to demonstrate automatic GC
155    let small_partition = heap.create_partition();
156
157    // Allocate multiple objects to fill partition
158    for i in 0..5 {
159        let _obj = unsafe { heap.alloc_raw(small_partition, MyString(format!("Object {}", i))) }
160            .map_err(|(err, _)| err)?;
161    }
162
163    println!("  Allocated 5 objects in small partition");
164
165    // Demonstrate weak references
166    println!("\nDemonstrate weak references:");
167    let weak_ref = heap.downgrade(&obj1);
168    println!("  Created weak reference: {:?}", weak_ref);
169
170    // Upgrade weak reference
171    match weak_ref.upgrade(&heap) {
172        Some(strong_ref) => {
173            println!(
174                "  Weak reference upgrade successful: '{}'",
175                strong_ref.deref()
176            );
177        }
178        None => {
179            println!("  Weak reference upgrade failed");
180        }
181    }
182
183    // Demonstrate complex types with GC references
184    println!("\nDemonstrate complex types with GC references:");
185    let mut node1 =
186        unsafe { heap.alloc_raw(partition1, TestNode::new("Node 1")) }.map_err(|(err, _)| err)?;
187    let mut node2 =
188        unsafe { heap.alloc_raw(partition1, TestNode::new("Node 2")) }.map_err(|(err, _)| err)?;
189
190    // Establish references between nodes
191    {
192        node1.with_mut(&mut heap, |n| n.add_child(node2));
193        node2.with_mut(&mut heap, |n| n.add_child(node1));
194    }
195
196    println!("  Created node1: {}", node1.deref());
197    println!("  Created node2: {}", node2.deref());
198
199    // Trigger garbage collection, verify circular references are handled correctly
200    println!("\nGarbage collection for handling circular references...");
201    let freed = heap.garbage_collect(partition1, GcHeap::DUMMY_DISPOSE_CALLBACK);
202    println!("  回收了 {} 字节内存", freed);
203
204    // Demonstrate partition deletion
205    println!("\nDemonstrate partition deletion:");
206
207    // Create an empty partition
208    let empty_partition = heap.create_partition();
209    println!("  Created empty partition: {:?}", empty_partition);
210
211    // Delete empty partition
212    heap.remove_partition(empty_partition, GcHeap::DUMMY_DISPOSE_CALLBACK);
213    println!("  Deleted empty partition successfully");
214
215    // Delete non-empty partition
216    heap.remove_partition(partition1, GcHeap::DUMMY_DISPOSE_CALLBACK);
217    println!("  Deleted non-empty partition successfully");
218
219    println!("\nExample completed!");
220    Ok(())
221}

Trait Implementations§

Source§

impl<T: GcNode> Clone for GcWeak<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: GcNode> Debug for GcWeak<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: GcNode> Default for GcWeak<T>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<T: PartialEq + GcNode> PartialEq for GcWeak<T>

Source§

fn eq(&self, other: &GcWeak<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: GcNode> Copy for GcWeak<T>

Source§

impl<T: GcNode> StructuralPartialEq for GcWeak<T>

Auto Trait Implementations§

§

impl<T> Freeze for GcWeak<T>

§

impl<T> RefUnwindSafe for GcWeak<T>
where T: RefUnwindSafe,

§

impl<T> Send for GcWeak<T>
where T: Send,

§

impl<T> Sync for GcWeak<T>
where T: Sync,

§

impl<T> Unpin for GcWeak<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for GcWeak<T>

§

impl<T> UnwindSafe for GcWeak<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.