2018-11-08 01:58:03 -06:00
|
|
|
use std::cell::{Cell, RefCell};
|
2016-09-27 10:02:04 -05:00
|
|
|
use std::rc::Rc;
|
2018-11-08 01:58:03 -06:00
|
|
|
use std::sync::Arc;
|
2016-09-27 10:02:04 -05:00
|
|
|
|
2017-08-29 09:51:26 -05:00
|
|
|
fn rc_refcell() {
|
2016-09-27 10:02:04 -05:00
|
|
|
let r = Rc::new(RefCell::new(42));
|
2018-11-08 01:58:03 -06:00
|
|
|
let r2 = r.clone();
|
2016-09-27 10:02:04 -05:00
|
|
|
*r.borrow_mut() += 10;
|
2018-11-08 01:58:03 -06:00
|
|
|
let x = *r2.borrow();
|
2017-08-29 09:51:26 -05:00
|
|
|
assert_eq!(x, 52);
|
2016-09-27 10:02:04 -05:00
|
|
|
}
|
|
|
|
|
2018-11-08 01:58:03 -06:00
|
|
|
fn rc_cell() {
|
|
|
|
let r = Rc::new(Cell::new(42));
|
|
|
|
let r2 = r.clone();
|
|
|
|
let x = r.get();
|
|
|
|
r2.set(x + x);
|
|
|
|
assert_eq!(r.get(), 84);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn rc_refcell2() {
|
|
|
|
let r = Rc::new(RefCell::new(42));
|
|
|
|
let r2 = r.clone();
|
|
|
|
*r.borrow_mut() += 10;
|
|
|
|
let x = r2.borrow();
|
|
|
|
let r3 = r.clone();
|
|
|
|
let y = r3.borrow();
|
|
|
|
assert_eq!((*x + *y)/2, 52);
|
|
|
|
}
|
|
|
|
|
2017-06-12 17:22:58 -05:00
|
|
|
fn rc_raw() {
|
|
|
|
let r = Rc::new(0);
|
|
|
|
let r2 = Rc::into_raw(r.clone());
|
|
|
|
let r2 = unsafe { Rc::from_raw(r2) };
|
|
|
|
assert!(Rc::ptr_eq(&r, &r2));
|
|
|
|
drop(r);
|
|
|
|
assert!(Rc::try_unwrap(r2).is_ok());
|
|
|
|
}
|
|
|
|
|
2018-11-08 01:58:03 -06:00
|
|
|
fn arc() {
|
|
|
|
fn test() -> Arc<i32> {
|
|
|
|
let a = Arc::new(42);
|
|
|
|
a
|
|
|
|
}
|
|
|
|
assert_eq!(*test(), 42);
|
|
|
|
}
|
|
|
|
|
2017-08-29 09:51:26 -05:00
|
|
|
// Make sure this Rc doesn't fall apart when touched
|
|
|
|
fn check_unique_rc<T: ?Sized>(mut r: Rc<T>) {
|
|
|
|
let r2 = r.clone();
|
|
|
|
assert!(Rc::get_mut(&mut r).is_none());
|
|
|
|
drop(r2);
|
|
|
|
assert!(Rc::get_mut(&mut r).is_some());
|
|
|
|
}
|
|
|
|
|
|
|
|
fn rc_from() {
|
|
|
|
check_unique_rc::<[_]>(Rc::from(&[1,2,3] as &[_]));
|
|
|
|
check_unique_rc::<[_]>(Rc::from(vec![1,2,3]));
|
|
|
|
check_unique_rc::<[_]>(Rc::from(Box::new([1,2,3]) as Box<[_]>));
|
|
|
|
check_unique_rc::<str>(Rc::from("Hello, World!"));
|
|
|
|
}
|
|
|
|
|
2016-09-27 10:02:04 -05:00
|
|
|
fn main() {
|
|
|
|
rc_refcell();
|
2018-11-08 01:58:03 -06:00
|
|
|
rc_refcell2();
|
|
|
|
rc_cell();
|
2017-06-12 17:22:58 -05:00
|
|
|
rc_raw();
|
2017-08-29 09:51:26 -05:00
|
|
|
rc_from();
|
2018-11-08 01:58:03 -06:00
|
|
|
arc();
|
2016-09-27 10:02:04 -05:00
|
|
|
}
|