-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
124 lines (98 loc) · 2.56 KB
/
main.rs
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/// The trait I want to implement, but cannot change.
pub trait GetFluid {
type Item<'a>
where
Self: 'a;
fn get_fluid<'a>(&'a mut self) -> Self::Item<'a>;
}
/// A library I want to use, but it has a bit different api:
/// the difference is that Car does not yield Fuel directly, but via Engine.
mod car {
pub struct Car {
pub engines: Vec<f64>,
}
pub struct Engine<'car> {
pub id: usize,
pub car: &'car mut Car,
// + some internal fields
}
pub struct Fuel<'car, 'engine> {
pub engine: &'engine mut Engine<'car>,
// + some internal fields
}
impl Car {
pub fn get_engine(&mut self) -> Engine<'_> {
println!("create engine");
Engine { id: 0, car: self }
}
}
impl<'car> Engine<'car> {
pub fn get_fuel(&mut self) -> Fuel<'car, '_> {
println!("create fuel");
Fuel { engine: self }
}
}
impl<'car, 'engine> Fuel<'car, 'engine> {
pub fn update(&mut self, val: f64) {
self.engine.car.engines[self.engine.id] = val;
}
}
impl<'a> Drop for Engine<'a> {
fn drop(&mut self) {
println!("drop engine");
}
}
impl<'a, 'b> Drop for Fuel<'a, 'b> {
fn drop(&mut self) {
println!("drop fuel");
}
}
}
use pac_cell::PacCell;
impl GetFluid for car::Car {
type Item<'a> = PacCell<car::Engine<'a>, car::Fuel<'a, 'a>> where Self: 'a;
fn get_fluid<'a>(&'a mut self) -> Self::Item<'a> {
// create engine by borrowing self
let engine: car::Engine<'a> = self.get_engine();
PacCell::new(engine, |e| e.get_fuel())
}
}
#[test]
fn test_01() {
let mut car = car::Car {
engines: vec![3.2, 1.5],
};
{
let mut fuel = car.get_fluid();
fuel.with_mut(|f| f.update(4.2));
}
assert_eq!(car.engines, vec![4.2, 1.5]);
}
#[test]
fn test_02() {
let mut car = car::Car {
engines: vec![3.2, 1.5],
};
{
let mut fuel = car.get_fluid();
fuel.with_mut(|f| f.update(4.2));
let _engine = fuel.unwrap();
}
assert_eq!(car.engines, vec![4.2, 1.5]);
}
#[test]
fn test_03() {
struct Hello {
world: i64,
}
let hello = Hello { world: 10 };
let mut pac = PacCell::new(hello, |h| &mut h.world);
let initial = pac.with_mut(|world| {
let i = **world;
**world = 12;
i
});
assert_eq!(initial, 10);
let hello_again = pac.unwrap();
assert_eq!(hello_again.world, 12);
}