Commit 7b7cac7
committed
core: Relax lifetime constraint on
This change enables users of `i2cdev` to create generic functions on `T:
I2CTransfer` that have output buffers constructed separately from the
`I2CMessage` array, like the following:
```rust
fn smbus_read_post_box<T>(i2c: &mut T, offset: u16, out: &mut [u8])
where for<'a> T: I2CTransfer<'a>,
{
let addr = offset.to_be_bytes();
let mut messages = [
T::Message::write(addr),
T::Message::read(out),
];
i2c.transfer(&mut messages).expect("uh oh");
}
```
Before this, `messages` would not satisfy the constraints of `.transfer()`,
because `messages` does not live as long as one of the output buffers `out`:
```
error[E0597]: `messages` does not live long enough
--> src/smbpbisensor.rs:69:19
|
63 | let mut messages = [
| ------------ binding `messages` declared here
...
69 | .transfer(&mut messages)
| ^^^^^^^^^^^^^ borrowed value does not live long enough
...
78 | }
| -
| |
| `messages` dropped here while still borrowed
| borrow might be used here, when `messages` is dropped and runs the destructor for type `[<T as I2CTransfer<'_>>::Message; 2]`
```
The error message is a little confusing, but basically `&'a mut [Self::Message]`
is forcing the array of `I2CMessage`s to match the lifetime of the buffers in
the messages, which is not strictly necessary: the array of messages can have a
different lifetime than the buffers. After this change, the above example
compiles successfully.msgs in I2CTransfer::transfer()
1 parent 499e902 commit 7b7cac7
3 files changed
+4
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
137 | 137 | | |
138 | 138 | | |
139 | 139 | | |
140 | | - | |
| 140 | + | |
141 | 141 | | |
142 | 142 | | |
143 | 143 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
299 | 299 | | |
300 | 300 | | |
301 | 301 | | |
302 | | - | |
| 302 | + | |
303 | 303 | | |
304 | 304 | | |
305 | 305 | | |
| |||
335 | 335 | | |
336 | 336 | | |
337 | 337 | | |
338 | | - | |
| 338 | + | |
339 | 339 | | |
340 | 340 | | |
341 | 341 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
152 | 152 | | |
153 | 153 | | |
154 | 154 | | |
155 | | - | |
| 155 | + | |
156 | 156 | | |
157 | 157 | | |
158 | 158 | | |
| |||
0 commit comments