I'm trying to implement a simple parser for a byte stream.
I'm having troubles when I want to reuse a variable I declared previously,
fn read_data(asn_data: &mut Cursor<&[u8]>) -> Result<(u8, u8, Vec<u8>), Err> {
let total_len = asn_data.get_ref().len();
if total_len < 2 {
return Err(1);
}
let d_type = asn_data.read_u8().unwrap();
let d_len = asn_data.read_u8().unwrap();
if (asn_data.position() + d_len as u64) > total_len as u64 {
return Err(2);
}
let mut buf = vec![0; d_len as usize];
match asn_data.read_exact(&mut buf) {
Err(e) => Err(e),
Ok(()) => Ok((d_type, d_len, buf)),
}
}
fn parse_request(request: &[u8]) -> Option<u8> {
if request.len() == 0 {
return None;
}
let mut rdr = Cursor::new(request);
let data_tuple = read_data(&mut rdr).unwrap();
println!("{:02?}", data_tuple.2);
rdr = Cursor::new(data_tuple.2.as_slice());
let data_tuple = read_data(&mut rdr).unwrap();
println!("{:02x?}", data_tuple.2);
Some(1)
}
In the parse_request function I want to reuse rdr variable, but with the code shown above I get the next error when compiling:
error[E0597]:
data_tuple.2
does not live long enough --> src/main.rs:80:23 | 80 | rdr = Cursor::new(data_tuple.2.as_slice()); | ^^^^^^^^^^^^ borrowed value does not live long enough ... 104 | } | -data_tuple.2
dropped here while still borrowed | = note: values in a scope are dropped in the opposite order they are createderror: aborting due to previous error
However if I write "let mut" when I use the 2nd time rdr variable, the code compiles and works fine...
let mut rdr = Cursor::new(data_tuple.2.as_slice());
I don't understand why... what I want is to reuse the variable instead to declare it again...
I tried with some examples/issues related to variable life time but I didn't get the solution for my case... and the solution I found I don't understand fully...
rdr
makes sure it is declared afterdata_tuple
, so the former can't outlive the latter. If you reuse the variable, the declaration order is the other way around, sordr
is only dropped afterdata_tuple
, hence the error. – Sven MarnachErr
, which is in scope at the same time as the enum variant of the same name? – Sven Marnach