I am writing a lexer and want to advance/backup a cursor using RAII helpers. I have a string that is indexed by the CharStreamGuard
type that acts as the cursor. It is created at the top-level with new
or extended from a parent guard using extend
. I believe the following code models the lifetimes correctly: 'c
is a sub-lifetime of 'b
, but the compiler still gives
error[E0597]: `csg` does not live long enough
--> src/lib.rs:78:48
|
76 | let mut csg = CharStreamGuard::new(&s);
| ------- binding `csg` declared here
77 | {
78 | let mut csg2 = CharStreamGuard::extend(&mut csg);
| ^^^^^^^^ borrowed value does not live long enough
...
82 | }
| -
| |
| `csg` dropped here while still borrowed
| borrow might be used here, when `csg` is dropped and runs the `Drop` code for type `CharStreamGuard`
error[E0499]: cannot borrow `csg` as mutable more than once at a time
--> src/lib.rs:81:5
|
78 | let mut csg2 = CharStreamGuard::extend(&mut csg);
| -------- first mutable borrow occurs here
...
81 | csg.accept();
| ^^^
| |
| second mutable borrow occurs here
| first borrow later used here
For the code:
#[derive(PartialEq)]
enum GuardStatus {
Unset,
Accepted,
Rejected,
}
pub struct CharStreamGuard<'a, 'b> {
src: &'a String,
parent: Option<&'b mut CharStreamGuard<'a, 'b>>,
index: usize,
status: GuardStatus
}
impl<'a,'b> CharStreamGuard<'a,'b> {
fn new(src: &'a String) -> CharStreamGuard<'a,'b> {
return CharStreamGuard {
src: src,
parent: None,
index: 0,
status: GuardStatus::Unset
};
}
fn extend<'c>(parent: &'c mut CharStreamGuard<'a,'b>) -> CharStreamGuard<'a,'c>
where 'c : 'b
{
let index = parent.index;
return CharStreamGuard {
src: parent.src,
parent: Some(parent),
index: index,
status: GuardStatus::Unset
};
}
fn accept(&mut self) {
self.status = GuardStatus::Accepted;
if let Some(parent) = self.parent.as_mut() {
parent.index = self.index;
}
}
fn reject(&mut self) {
self.status = GuardStatus::Rejected;
}
}
impl Drop for CharStreamGuard<'_,'_> {
fn drop(&mut self) -> () {
if self.status == GuardStatus::Unset {
panic!("guard was neither accpeted nor rejected!");
}
}
}
fn test_it() {
let s = String::new();
let mut csg = CharStreamGuard::new(&s);
{
let mut csg2 = CharStreamGuard::extend(&mut csg);
csg2.accept();
}
csg.accept();
}