Skip to content

Commit

Permalink
test weak_into_raw
Browse files Browse the repository at this point in the history
  • Loading branch information
RalfJung committed May 29, 2019
1 parent a5224b0 commit 0dfc1c9
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 2 deletions.
2 changes: 1 addition & 1 deletion rust-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4b9d80325a65b0375eea526409a0f3aaf1cbc23c
81970852e172c04322cbf8ba23effabeb491c83c
19 changes: 19 additions & 0 deletions tests/compile-fail/rc_as_raw.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#![feature(weak_into_raw)]

use std::rc::{Rc, Weak};
use std::ptr;

/// Taken from the `Weak::as_raw` doctest.
fn main() {
let strong = Rc::new(Box::new(42));
let weak = Rc::downgrade(&strong);
// Both point to the same object
assert!(ptr::eq(&*strong, Weak::as_raw(&weak)));
// The strong here keeps it alive, so we can still access the object.
assert_eq!(42, **unsafe { &*Weak::as_raw(&weak) });

drop(strong);
// But not any more. We can do Weak::as_raw(&weak), but accessing the pointer would lead to
// undefined behaviour.
assert_eq!(42, **unsafe { &*Weak::as_raw(&weak) }); //~ ERROR dangling pointer
}
38 changes: 37 additions & 1 deletion tests/run-pass/rc.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#![feature(weak_into_raw)]

use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::fmt::Debug;

Expand Down Expand Up @@ -69,12 +71,46 @@ fn rc_fat_ptr_eq() {
drop(unsafe { Rc::from_raw(r) });
}

/// Taken from the `Weak::into_raw` doctest.
fn weak_into_raw() {
let strong = Rc::new(42);
let weak = Rc::downgrade(&strong);
let raw = Weak::into_raw(weak);

assert_eq!(1, Rc::weak_count(&strong));
assert_eq!(42, unsafe { *raw });

drop(unsafe { Weak::from_raw(raw) });
assert_eq!(0, Rc::weak_count(&strong));
}

/// Taken from the `Weak::from_raw` doctest.
fn weak_from_raw() {
let strong = Rc::new(42);

let raw_1 = Weak::into_raw(Rc::downgrade(&strong));
let raw_2 = Weak::into_raw(Rc::downgrade(&strong));

assert_eq!(2, Rc::weak_count(&strong));

assert_eq!(42, *Weak::upgrade(&unsafe { Weak::from_raw(raw_1) }).unwrap());
assert_eq!(1, Rc::weak_count(&strong));

drop(strong);

// Decrement the last weak count.
assert!(Weak::upgrade(&unsafe { Weak::from_raw(raw_2) }).is_none());
}

fn main() {
rc_fat_ptr_eq();
rc_refcell();
rc_refcell2();
rc_cell();
rc_raw();
rc_from();
weak_into_raw();
weak_from_raw();

arc();
}

0 comments on commit 0dfc1c9

Please sign in to comment.