Skip to content

Commit df57d65

Browse files
committed
Make UniqueRc invariant for soundness
1 parent fb65a3e commit df57d65

File tree

3 files changed

+48
-2
lines changed

3 files changed

+48
-2
lines changed

library/alloc/src/rc.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -3708,7 +3708,11 @@ pub struct UniqueRc<
37083708
#[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
37093709
> {
37103710
ptr: NonNull<RcInner<T>>,
3711-
phantom: PhantomData<RcInner<T>>,
3711+
// Define the ownership of `RcInner<T>` for drop-check
3712+
_marker: PhantomData<RcInner<T>>,
3713+
// Invariance is necessary for soundness: once other `Weak`
3714+
// references exist, we already have a form of shared mutability!
3715+
_marker2: PhantomData<*mut T>,
37123716
alloc: A,
37133717
}
37143718

@@ -3994,7 +3998,7 @@ impl<T, A: Allocator> UniqueRc<T, A> {
39943998
},
39953999
alloc,
39964000
));
3997-
Self { ptr: ptr.into(), phantom: PhantomData, alloc }
4001+
Self { ptr: ptr.into(), _marker: PhantomData, _marker2: PhantomData, alloc }
39984002
}
39994003
}
40004004

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// regression test of https://github.com/rust-lang/rust/pull/133572#issuecomment-2543007164
2+
// we should also test UniqueArc once implemented
3+
//
4+
// inline comments explain how this code *would* compile if UniqueRc was still covariant
5+
6+
#![feature(unique_rc_arc)]
7+
8+
use std::rc::UniqueRc;
9+
10+
fn extend_lifetime<'a, 'b>(x: &'a str) -> &'b str {
11+
let r = UniqueRc::new(""); // UniqueRc<&'static str>
12+
let w = UniqueRc::downgrade(&r); // Weak<&'static str>
13+
let mut r = r; // [IF COVARIANT]: ==>> UniqueRc<&'a str>
14+
*r = x; // assign the &'a str
15+
let _r = UniqueRc::into_rc(r); // Rc<&'a str>, but we only care to activate the weak
16+
let r = w.upgrade().unwrap(); // Rc<&'static str>
17+
*r // &'static str, coerces to &'b str
18+
//~^ ERROR lifetime may not live long enough
19+
}
20+
21+
fn main() {
22+
let s = String::from("Hello World!");
23+
let r = extend_lifetime(&s);
24+
println!("{r}");
25+
drop(s);
26+
println!("{r}");
27+
}
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error: lifetime may not live long enough
2+
--> $DIR/variance-uniquerc.rs:17:5
3+
|
4+
LL | fn extend_lifetime<'a, 'b>(x: &'a str) -> &'b str {
5+
| -- -- lifetime `'b` defined here
6+
| |
7+
| lifetime `'a` defined here
8+
...
9+
LL | *r // &'static str, coerces to &'b str
10+
| ^^ function was supposed to return data with lifetime `'b` but it is returning data with lifetime `'a`
11+
|
12+
= help: consider adding the following bound: `'a: 'b`
13+
14+
error: aborting due to 1 previous error
15+

0 commit comments

Comments
 (0)