Hello, I'm new to Rust. I'm trying to fix the following 'second mutable borrow occurs here' error.
Basically I wanted to write a function that uses httparse
to parse a buffer as a Response and if it fails to parse it as Request. Also, I wanted to have a single httparse::Header
array. Any suggestions?
Playground link: Rust Playground
The error:
Compiling tmp v0.1.0 (file:///home/oblique/scratchpad/rust/tmp)
error[E0499]: cannot borrow `*headers` as mutable more than once at a time
--> src/main.rs:17:46
|
10 | let mut res = httparse::Response::new(headers);
| ------- first mutable borrow occurs here
...
17 | let mut req = httparse::Request::new(headers);
| ^^^^^^^ second mutable borrow occurs here
...
24 | }
| - first borrow ends here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0499`.
error: Could not compile `tmp`.
To learn more, run the command again with --verbose.
My code:
extern crate httparse;
enum Http<'headers, 'buf: 'headers> {
Res(httparse::Response<'headers, 'buf>),
Req(httparse::Request<'headers, 'buf>),
}
fn parse_http<'b, 'h>(http: &'b [u8], headers: &'h mut [httparse::Header<'b>]) -> Result<Http<'h, 'b>, String> {
{
let mut res = httparse::Response::new(headers);
if let Ok(_) = res.parse(&http) {
return Ok(Http::Res(res));
}
}
{
let mut req = httparse::Request::new(headers);
if let Ok(_) = req.parse(&http) {
return Ok(Http::Req(req));
}
}
Err("Failed to parse HTTP headers".into())
}
fn main() {
let buf = b"GET /index.html HTTP/1.1\r\nHost: example.domain\r\n\r\n";
let mut headers = [httparse::EMPTY_HEADER; 16];
match parse_http(buf, &mut headers) {
Ok(http) => {
match http {
Http::Res(_) => println!("response"),
Http::Req(_) => println!("request"),
}
}
Err(e) => eprintln!("{}", e),
}
}