Search code examples
rusthyper

What is the best way to send a specific number of bytes in a hyper response?


I'm looking to send a specific number of bytes (e.g. 1GB) as a non-chunked response in a hyper server I'm making. I'm new to Rust and figured I could just the Rust equivalent of byte slice but that hasn't been working. Wondering what is the best way to accomplish this.

let mut bytes = BytesMut::with_capacity(64).freeze();
Ok(Response::new(Body::from(bytes)))

This returns a response with 0 content length but I want it to return 64 bytes.


Solution

  • BytesMut::with_capacity does not fill the buffer with anything. It only preallocates a buffer of 64 bytes, but leaves the length at zero. The documentation indicates this, together with a code example that shows that buffer is still empty, unless you push something to it.

    If you'd like to send 64 bytes and do not care what they are, try a zero-filled Vec:

    Ok(Response::new(Body::from(vec![0; 64])))