My non-blocking socket receiver implementation uses serde and bincode to deserialize borrowed values from an internal buffer. Here is the condensed version:
struct Receiver {
buf: Vec<u8>,
}
impl Receiver {
fn try_recv<'a, 'de, T>(&'a mut self) -> Option<T>
where 'a: 'de,
T: serde::Deserialize<'de>,
{
// In my actual code, self.buf is filled from a non-blocking socket...
self.buf.push(27);
// ...and the minimum length is determined through other means.
if self.buf.len() >= 10 {
let v: T = bincode::deserialize(&self.buf).unwrap();
Some(v)
} else {
None
}
}
}
fn recv<'a, 'de, T>(receiver: &'a mut Receiver) -> T
where 'a: 'de,
T: serde::Deserialize<'de>
{
// Loop until an entire instance of T has been received
loop {
if let Some(v) = receiver.try_recv() {
return v;
} else {
// Do other stuff, sleep, etc.
}
}
}
fn main() {
let mut receiver = Receiver { buf: vec![] };
let v = recv::<u32>(&mut receiver);
println!("Received v={}", v);
}
But I get the following error:
error[E0499]: cannot borrow `*receiver` as mutable more than once at a time
--> src/main.rs:25:26
|
20 | fn recv<'a, 'de, T>(receiver: &'a mut Receiver) -> T
| --- lifetime `'de` defined here
...
25 | if let Some(v) = receiver.try_recv() {
| ^^^^^^^^-----------
| |
| mutable borrow starts here in previous iteration of loop
| argument requires that `*receiver` is borrowed for `'de`
I think it should be possible to compile this with the proper lifetime annotations, because the mut reference to receiver
, which is returned by the try_recv()
call, is not carried to the next loop iteration.
Any help would be greatly appreciated.