aoc-toolkit 0.1.0-alpha.4

A toolkit for solving Advent of Code problems
Documentation
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

pub(super) fn serve_once(
    status: &'static str,
    headers: &'static str,
    body: &'static [u8],
) -> (String, JoinHandle<String>) {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();

    let address = listener.local_addr().unwrap();

    listener.set_nonblocking(true).unwrap();

    let handle = thread::spawn(move || {
        let deadline = Instant::now() + Duration::from_secs(10);

        let mut stream = loop {
            match listener.accept() {
                Ok((stream, _)) => break stream,

                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                    assert!(Instant::now() < deadline, "Expected an HTTP request");

                    thread::sleep(Duration::from_millis(10));
                }

                Err(error) => {
                    panic!("Cannot accept request: {error}");
                }
            }
        };

        stream.set_nonblocking(false).unwrap();

        stream
            .set_read_timeout(Some(Duration::from_secs(5)))
            .unwrap();

        stream
            .set_write_timeout(Some(Duration::from_secs(5)))
            .unwrap();

        let mut request = String::new();

        {
            let mut reader = BufReader::new(&mut stream);

            loop {
                let mut line = String::new();

                let read = reader.read_line(&mut line).unwrap();

                assert_ne!(read, 0, "Incomplete HTTP request");

                request.push_str(&line);

                if line == "\r\n" {
                    break;
                }
            }
        }

        write!(
            stream,
            "HTTP/1.1 {status}\r\n\
             Content-Length: {}\r\n\
             Connection: close\r\n\
             {headers}\r\n",
            body.len(),
        )
        .unwrap();

        stream.write_all(body).unwrap();
        stream.flush().unwrap();

        request
    });

    (format!("http://{address}"), handle)
}