jeudi 24 décembre 2020

Why Rust reset some variables after a loop?

I finished reading The Rust Programming Languange some time ago and I'm creating a simple http-server for the sake of teaching myself Rust.

In a function meant to parse a &[u8] and create a HttpRequest object, I noticed that a loop that should be parsing the headers is actually not updating some variables used to track the state of parsing:

pub fn parse_request(buffer: &[u8]) -> Result<HttpRequest, &'static str> {
    let (mut line, mut curr_req_reader_pos) = next_req_line(buffer, 0);

    let (method, path, version) = parse_method_path_and_version(&line)?;

    let (line, curr_req_reader_pos) = next_req_line(buffer, curr_req_reader_pos);
    //eprintln!("--- got next line: {}, {} ---", curr_req_reader_pos, String::from_utf8_lossy(line));
    let mut headers = vec![];
    let mut lel = 0;
    while line.len() > 0 {
        //eprintln!("LOOP");
        let header = parse_header(&line);
        eprintln!("--- parsed header: {} ---", String::from_utf8_lossy(line));
        headers.push(header);
        let (line, curr_req_reader_pos) = next_req_line(buffer, curr_req_reader_pos);
        //eprintln!("--- got next line: {}, {} ---", curr_req_reader_pos, String::from_utf8_lossy(line));
        let (line, curr_req_reader_pos) = next_req_line(buffer, curr_req_reader_pos);
        //eprintln!("--- got next line: {}, {} ---", curr_req_reader_pos, String::from_utf8_lossy(line));
        //eprintln!("LOOP");
        lel += 10;
        //break;
    }

    let (line, curr_req_reader_pos) = next_req_line(buffer, curr_req_reader_pos);
    //eprintln!("--- got next line: {}, {} ---", curr_req_reader_pos, String::from_utf8_lossy(line));
    //eprintln!("{}", lel);

    let has_body;
    match method.as_ref() {
        "POST" | "PUT" | "PATCH" => has_body = true,
        _ => has_body = true
    };

    let body;
    if has_body {
        let (line, curr_req_reader_pos) = next_req_line(buffer, curr_req_reader_pos);
        body = String::from_utf8_lossy(line).to_string();
    } else  {
        body = String::new();
    }

    Ok(HttpRequest {
        method,
        path,
        version,
        headers,
        has_body,
        body
    })
}

There's also tests for each method:

#[test]
fn test_next_req_line() {
    let req = "GET / HTTP/1.1\r\nContent-Length: 3\r\n\r\n\r\n\r\nlel".as_bytes();

    let (mut lel, mut pos) = next_req_line(req, 0);
    assert_eq!("GET / HTTP/1.1", String::from_utf8_lossy(lel));
    assert!(lel.len() > 0);
    assert_eq!(16, pos);

    let (lel, pos) = next_req_line(req, pos);
    assert_eq!("Content-Length: 3", String::from_utf8_lossy(lel));
    assert!(lel.len() > 0);
    assert_eq!(35, pos);

    let (lel, pos) = next_req_line(req, pos);
    assert_eq!("", String::from_utf8_lossy(lel));
    assert!(lel.len() == 0);
    assert_eq!(37, pos);

    let (lel, pos) = next_req_line(req, pos);
    assert_eq!("", String::from_utf8_lossy(lel));
    assert!(lel.len() == 0);

    let (lel, pos) = next_req_line(req, pos);
    assert_eq!("", String::from_utf8_lossy(lel));
    assert!(lel.len() == 0);

    let (lel, pos) = next_req_line(req, pos);
    assert_eq!("lel", String::from_utf8_lossy(lel));
    assert!(lel.len() == 3);
}

    #[test]
    fn test_parse_request() {
        let mut request = String::from("GET / HTTP/1.1\r\n");
        request.push_str("Content-Length: 3\r\n");
        request.push_str("\r\n");
        request.push_str("lel");
        let request = request.as_bytes();

        match parse_request(&request) {
            Ok(http_request) => {
                assert_eq!(http_request.method, "GET");
                assert_eq!(http_request.path, "/");
                assert_eq!(http_request.version, "HTTP/1.1");
            },
            Err(_) => {
                println!("Failed");
            }
        }
    }

The commented lines are just to show what's happening, and that's where I saw this output:


    Finished test [unoptimized + debuginfo] target(s) in 0.53s
     Running target/debug/deps/rweb-6bbc2a3130f7e3d9

running 4 tests
test http::testing::test_next_req_line ... ok
test http::testing::test_parse_header ... ok
test http::testing::test_parse_method_path_and_version ... ok
--- parsed method path version  ---
--- got next line: 35, Content-Length: 3 ---
LOOP
--- parsed header: Content-Length: 3 ---
--- got next line: 37,  ---
--- got next line: 39, lel ---
LOOP
--- got next line: 37,  ---
10
test http::testing::test_parse_request ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

It seems that the while loop is not re-assigning the line and curr_req_reader_pos variables, but for me it made perfect sense to expect that the loop would update these variables and parse every header. However, it works perfecly outside a loop, as anyone can see in the tests.

I can't figure out why this happens with my current undertanding of Rust, why does it happen?

Aucun commentaire:

Enregistrer un commentaire