Hi everyone, I'm not sure how to describe the issue I'm encountering, so I'll just show a simplified example to hopefully make it more clear (playground link):
This is my code:
trait Visit<'a> {
fn visit(slice: &'a [u8]) -> Self;
fn min_size() -> usize;
fn consumed(&self) -> usize;
}
struct Num<'a>(&'a [u8]);
impl<'a> Visit<'a> for Num<'a> {
fn visit(slice: &'a [u8]) -> Self {
Num(&slice[..4])
}
fn min_size() -> usize {
4
}
fn consumed(&self) -> usize {
4
}
}
struct Visitor {
buffer: Vec<u8>,
cursor: usize,
}
impl Visitor {
fn advance<'a, 's: 'a, V: Visit<'a>>(&'s mut self) -> bool {
if self.buffer.len() - self.cursor < V::min_size() {
false
} else {
let value = V::visit(&self.buffer[self.cursor..]);
self.cursor += value.consumed();
true
}
}
fn consume_all<'a, V: Visit<'a>>(&mut self) {
while self.advance::<V>() {}
}
}
And this is the error I'm getting:
error: lifetime may not live long enough
--> src/main.rs:39:15
|
38 | fn consume_all<'a, V: Visit<'a>>(&mut self) {
| -- - let's call the lifetime of this reference `'1`
| |
| lifetime `'a` defined here
39 | while self.advance::<V>() {}
| ^^^^^^^^^^^^^^^^^^^ argument requires that `'1` must outlive `'a`
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:39:15
|
38 | fn consume_all<'a, V: Visit<'a>>(&mut self) {
| -- lifetime `'a` defined here
39 | while self.advance::<V>() {}
| ^^^^^^^^^^^^^^^^^^^
| |
| `*self` was mutably borrowed here in the previous iteration of the loop
| argument requires that `*self` is borrowed for `'a`
I think understand why this error happens, but my problem is that I can't figure out a way to remove/simplify the lifetimes. Since the value
variable clearly doesn't outlive the advance
function I thought about specifying an anonymous lifetime to the Visit
trait bound, but the compiler doesn't allow me to do it. And since I can't do that I have to explicitly name that lifetime, but this is where it all spirals out of control.
I tried defining a separate lifetime 's
to make it more clear that 'a
doesn't live all that long, but that also didn't work. And as I understand it there's no way to define a lifetime which lives "shorter" than the function (which is what I'm interested into here I think).
From what I'm reading online I'm guessing HRTB might be helpful in this case, but again I can't figure out a way to use them here.
Sorry for the very vague question, I can't really explain this any better. If you have any tips or ideas I'd really appreciate them!
Thanks!
Alekos