]> git.lizzy.rs Git - rust.git/blob - src/test/ui/impl-trait/hidden-lifetimes.rs
Merge commit '953f024793dab92745fee9cd2c4dee6a60451771' into clippyup
[rust.git] / src / test / ui / impl-trait / hidden-lifetimes.rs
1 // Test to show what happens if we were not careful and allowed invariant
2 // lifetimes to escape though an impl trait.
3 //
4 // Specifically we swap a long lived and short lived reference, giving us a
5 // dangling pointer.
6
7 use std::cell::RefCell;
8 use std::rc::Rc;
9
10 trait Swap: Sized {
11     fn swap(self, other: Self);
12 }
13
14 impl<T> Swap for &mut T {
15     fn swap(self, other: Self) {
16         std::mem::swap(self, other);
17     }
18 }
19
20 impl<T> Swap for Rc<RefCell<T>> {
21     fn swap(self, other: Self) {
22         <RefCell<T>>::swap(&self, &other);
23     }
24 }
25
26 // Here we are hiding `'b` making the caller believe that `&'a mut &'s T` and
27 // `&'a mut &'l T` are the same type.
28 fn hide_ref<'a, 'b, T: 'static>(x: &'a mut &'b T) -> impl Swap + 'a {
29     //~^ ERROR hidden type
30     x
31 }
32
33 fn dangle_ref() -> &'static [i32; 3] {
34     let mut res = &[4, 5, 6];
35     let x = [1, 2, 3];
36     hide_ref(&mut res).swap(hide_ref(&mut &x));
37     res
38 }
39
40 // Here we are hiding `'b` making the caller believe that `Rc<RefCell<&'s T>>`
41 // and `Rc<RefCell<&'l T>>` are the same type.
42 //
43 // This is different to the previous example because the concrete return type
44 // only has a single lifetime.
45 fn hide_rc_refcell<'a, 'b: 'a, T: 'static>(x: Rc<RefCell<&'b T>>) -> impl Swap + 'a {
46     //~^ ERROR hidden type
47     x
48 }
49
50 fn dangle_rc_refcell() -> &'static [i32; 3] {
51     let long = Rc::new(RefCell::new(&[4, 5, 6]));
52     let x = [1, 2, 3];
53     let short = Rc::new(RefCell::new(&x));
54     hide_rc_refcell(long.clone()).swap(hide_rc_refcell(short));
55     let res: &'static [i32; 3] = *long.borrow();
56     res
57 }
58
59 fn main() {
60     // both will print nonsense values.
61     println!("{:?}", dangle_ref());
62     println!("{:?}", dangle_rc_refcell())
63 }