Archive for the ‘Rust’ Category

Creating uninitialized socket-recv-buffer with Rust

October 4, 2017

Programming Rust: Assuming one wants to recv data from socket,  storing the data into an byte buffer. Either you create a byte-array, initializing each element with well defined value, such as the following  code zero-ing the memory chunk completely.

fn recv_handler() 
{
  let mut recvbuf : [u8; 2048] = [0; 2048];
  ...
}

Or, as zero-ing of large byte-buffers may be time-consuming and as the net-socket recv-function does not read from supplied buffer anyway, creating an uninitialized byte-buffer to recv the data from socket.

use std::mem;

fn recv_handler() 
{
  let mut recvbuf : [u8; 2048] = unsafe { mem::uninitialized() };
  ...
}

The memory of recvbuf will be located on stack, no dynamic memory allocation will be involved, and the corresponding memory section is not zero-ed out.