Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test weak_into_raw #751

Merged
merged 1 commit into from
May 29, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}