seanmonstar / httparse

A push parser for the HTTP 1.x protocol in Rust.
https://docs.rs/httparse
Apache License 2.0
585 stars 114 forks source link

How return a Request properly #35

Closed steverob closed 7 years ago

steverob commented 7 years ago

Beginner here. Have not understood lifetimes completely. I am trying to return a parsed Request from a function like this -

fn read_and_parse(mut stream: TcpStream) -> Option<Request> {
  ..
  return req;
}

I get this error -

error[E0107]: wrong number of lifetime parameters: expected 2, found 0
  --> src/main.rs:64:61
   |
64 | fn read_and_parse(mut stream: TcpStream) -> Option<&'static Request> {
   |                                                             ^^^^^^^ expected 2 lifetime parameters

error: aborting due to previous error

How do I solve this?

seanmonstar commented 7 years ago

Hello! httparse works by not copying any data, but instead finding indices to the different parts of request. Therefore, the Request has a lifetime related to the data buffer it parsed from. Meaning, it cannot outlive the data (probably some Vec<u8>). You could probably take a look at the Lifetimes chapter of the Rust Book.

Regarding the function you pasted, the problem is that you need to the read some data of the the TcpStream. You would probably do with a Vec<u8> or similar. Then you call request.parse(&data), and that returned Request cannot live longer than the Vec it is borrowing from. So you wouldn't be able to return a Request just from that function.

I'm going to close this, since it's a usage question, and not a bug in httparse.