1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 /*! Task-local garbage-collected boxes
13 The `Gc` type provides shared ownership of an immutable value. Destruction is not deterministic, and
14 will occur some time between every `Gc` handle being gone and the end of the task. The garbage
15 collector is task-local so `Gc<T>` is not sendable.
20 use clone::{Clone, DeepClone};
22 /// Immutable garbage-collected pointer type
29 impl<T: 'static> Gc<T> {
30 /// Construct a new garbage-collected box
32 pub fn new(value: T) -> Gc<T> {
37 impl<T: 'static> Gc<T> {
38 /// Borrow the value contained in the garbage-collected box
40 pub fn borrow<'r>(&'r self) -> &'r T {
45 /// The `Send` bound restricts this to acyclic graphs where it is well-defined.
47 /// A `Freeze` bound would also work, but `Send` *or* `Freeze` cannot be expressed.
48 impl<T: DeepClone + Send + 'static> DeepClone for Gc<T> {
50 fn deep_clone(&self) -> Gc<T> {
51 Gc::new(self.borrow().deep_clone())
62 let x = Gc::new(RefCell::new(5));
64 x.borrow().with_mut(|inner| {
67 assert_eq!(y.borrow().with(|x| *x), 20);
71 fn test_deep_clone() {
72 let x = Gc::new(RefCell::new(5));
73 let y = x.deep_clone();
74 x.borrow().with_mut(|inner| {
77 assert_eq!(y.borrow().with(|x| *x), 5);
83 assert_eq!(*x.borrow(), 5);
87 fn test_simple_clone() {
90 assert_eq!(*x.borrow(), 5);
91 assert_eq!(*y.borrow(), 5);
95 fn test_destructor() {
97 assert_eq!(**x.borrow(), 5);