I have the following code:
pub fn read_packet<'a>(buf: &'a mut [u8]) -> &'a [u8] {
loop {
read_exact(buf);
if let Some(packet) = to_packet(buf) {
return packet;
}
}
}
fn read_exact(_: &mut [u8]) {
todo!()
}
fn to_packet<'a>(_: &'a [u8]) -> Option<&'a [u8]> {
todo!()
}
I get the following error:
error[E0502]: cannot borrow `*buf` as mutable because it is also borrowed as immutable
--> src/lib.rs:3:9
|
1 | pub fn read_packet<'a>(buf: &'a mut [u8]) -> &'a [u8] {
| -- lifetime `'a` defined here
2 | loop {
3 | read_exact(buf);
| ^^^^^^^^^^^^^^^ mutable borrow occurs here
4 |
5 | if let Some(packet) = to_packet(buf) {
| --- immutable borrow occurs here
6 | return packet;
| ------ returning this value requires that `*buf` is borrowed for `'a`
I think it should work because:
- The mutable borrow in
read_exact
completes on line 3. - If
to_packet
returnsSome
then the value is returned to the caller. - If not, the immutable borrow of
to_packet
is over at the end of the loop. So it is free to be taken mutable borrow of in the next iteration.
Can somebody please let me know why this doesn't work?
EDIT:
It seems like a current borrow checker limitation. I tried using Polonius in the nightly and it works fine with
RUSTFLAGS=-Zpolonius cargo +nightly check