Skip to content

Commit 9dfbebd

Browse files
authored
Merge pull request #751 from RalfJung/rc
test weak_into_raw
2 parents a5224b0 + 0dfc1c9 commit 9dfbebd

File tree

3 files changed

+57
-2
lines changed

3 files changed

+57
-2
lines changed

rust-version

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
4b9d80325a65b0375eea526409a0f3aaf1cbc23c
1+
81970852e172c04322cbf8ba23effabeb491c83c

tests/compile-fail/rc_as_raw.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#![feature(weak_into_raw)]
2+
3+
use std::rc::{Rc, Weak};
4+
use std::ptr;
5+
6+
/// Taken from the `Weak::as_raw` doctest.
7+
fn main() {
8+
let strong = Rc::new(Box::new(42));
9+
let weak = Rc::downgrade(&strong);
10+
// Both point to the same object
11+
assert!(ptr::eq(&*strong, Weak::as_raw(&weak)));
12+
// The strong here keeps it alive, so we can still access the object.
13+
assert_eq!(42, **unsafe { &*Weak::as_raw(&weak) });
14+
15+
drop(strong);
16+
// But not any more. We can do Weak::as_raw(&weak), but accessing the pointer would lead to
17+
// undefined behaviour.
18+
assert_eq!(42, **unsafe { &*Weak::as_raw(&weak) }); //~ ERROR dangling pointer
19+
}

tests/run-pass/rc.rs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
#![feature(weak_into_raw)]
2+
13
use std::cell::{Cell, RefCell};
2-
use std::rc::Rc;
4+
use std::rc::{Rc, Weak};
35
use std::sync::Arc;
46
use std::fmt::Debug;
57

@@ -69,12 +71,46 @@ fn rc_fat_ptr_eq() {
6971
drop(unsafe { Rc::from_raw(r) });
7072
}
7173

74+
/// Taken from the `Weak::into_raw` doctest.
75+
fn weak_into_raw() {
76+
let strong = Rc::new(42);
77+
let weak = Rc::downgrade(&strong);
78+
let raw = Weak::into_raw(weak);
79+
80+
assert_eq!(1, Rc::weak_count(&strong));
81+
assert_eq!(42, unsafe { *raw });
82+
83+
drop(unsafe { Weak::from_raw(raw) });
84+
assert_eq!(0, Rc::weak_count(&strong));
85+
}
86+
87+
/// Taken from the `Weak::from_raw` doctest.
88+
fn weak_from_raw() {
89+
let strong = Rc::new(42);
90+
91+
let raw_1 = Weak::into_raw(Rc::downgrade(&strong));
92+
let raw_2 = Weak::into_raw(Rc::downgrade(&strong));
93+
94+
assert_eq!(2, Rc::weak_count(&strong));
95+
96+
assert_eq!(42, *Weak::upgrade(&unsafe { Weak::from_raw(raw_1) }).unwrap());
97+
assert_eq!(1, Rc::weak_count(&strong));
98+
99+
drop(strong);
100+
101+
// Decrement the last weak count.
102+
assert!(Weak::upgrade(&unsafe { Weak::from_raw(raw_2) }).is_none());
103+
}
104+
72105
fn main() {
73106
rc_fat_ptr_eq();
74107
rc_refcell();
75108
rc_refcell2();
76109
rc_cell();
77110
rc_raw();
78111
rc_from();
112+
weak_into_raw();
113+
weak_from_raw();
114+
79115
arc();
80116
}

0 commit comments

Comments
 (0)