summaryrefslogtreecommitdiffstats
path: root/third_party/rust/rental/tests/simple_mut.rs
blob: c7af358998d01d399df5465efbccb35faf0c1518 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#[macro_use]
extern crate rental;


pub struct Foo {
	i: i32,
}

impl Foo {
	fn try_borrow_mut(&mut self) -> Result<&mut i32, ()> { Ok(&mut self.i) }
	fn fail_borrow_mut(&mut self) -> Result<&mut i32, ()> { Err(()) }
}


rental! {
	mod rentals {
		use super::*;

		#[rental_mut]
		pub struct SimpleMut {
			foo: Box<Foo>,
			iref: &'foo mut i32,
		}
	}
}


#[test]
fn new() {
	let foo = Foo { i: 5 };
	let _ = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i);

	let foo = Foo { i: 5 };
	let sm = rentals::SimpleMut::try_new(Box::new(foo), |foo| foo.try_borrow_mut());
	assert!(sm.is_ok());

	let foo = Foo { i: 5 };
	let sm = rentals::SimpleMut::try_new(Box::new(foo), |foo| foo.fail_borrow_mut());
	assert!(sm.is_err());
}


#[test]
fn read() {
	let foo = Foo { i: 5 };

	let sm = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i);
	let i: i32 = sm.rent(|iref| **iref);
	assert_eq!(i, 5);

	let iref: &i32 = sm.ref_rent(|iref| *iref);
	assert_eq!(*iref, 5);
}


#[test]
fn write() {
	let foo = Foo { i: 5 };

	let mut sm = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i);

	{
		let iref: &mut i32 = sm.ref_rent_mut(|iref| *iref);
		*iref = 12;
		assert_eq!(*iref, 12);
	}
}