How is the UDP server example safe?

Viewed 1920

I have a UDP server example, which is working:

let mut socket = UdpSocket::bind("127.0.0.1:12345")?;
let mut buf = [0; 4096];
loop {
    let sock = socket.try_clone()?;
    match socket.recv_from(&mut buf) {
        Ok((amt, src)) => {
            thread::spawn(move || {
                println!("Handling connection from {}", &src);
                let buf = &mut buf[..amt];
                buf.reverse();
                sock.send_to(&buf, &src).expect("error sending");
            });
        },
        Err(err) => {
            eprintln!("Err: {}", err);
        }
    }
}

It looks like all incoming UDP packets are sharing the same buffer.

If two UDP packets arrive at the same time, won't the second packet overwrite the first in buf, leading to the second packet's (reversed) content being sent back to both senders?

How does Rust prevent this?

1 Answers

No, the buffer is not shared among threads but implicitly copied before starting a new one. From the array doc:

Arrays of any size are Copy if the element type is Copy

Therefore a move keyword forces a buffer movement, which leads to a copy since the same buffer can be used at the next iteration of the loop.

Related