Resize And Fill Reusable Buffers

Grow, truncate, and reset byte buffers in place with resize and fill: growing needs Clone for new slots, truncation drops the tail, fill wipes stale bytes.

RustData Integrity

Code

rustsnippet
22 lines
fn main() {
    // resize grows: new slots are filled with clones of the fill value (growth requires T: Clone)
    let mut header = vec![0u8; 4];
    header.resize(8, 0xA5);
    println!("grown:     {header:02X?}");

    // resize truncates: extra elements are dropped outright, with no error
    let mut payload: Vec<u8> = (0..10).collect();
    payload.resize(6, 0);
    println!("truncated: {payload:02X?}");

    // fill resets the reusable buffer: clear the previous run's dirty data before reuse
    let mut scratch = vec![0xFFu8; 6];
    scratch.fill(0);
    println!("reset:     {scratch:02X?}");

    // fill can also target a range: the header is kept while the payload section resets uniformly
    let mut frame = vec![0u8; 10];
    frame[..2].copy_from_slice(&[0x1F, 0x2F]);
    frame[2..].fill(0xEE);
    println!("frame:     {frame:02X?}");
}

What the code does

Resize And Fill Reusable Buffers reduces to the function main.

Applying it

The demo output is labeled (grown:, truncated:, reset:), so every printed line maps back to its originating operation.

Statements that matter

let mut payload: Vec<u8> = (0..10).collect();

Interactive Tools for This Topic

FAQ

What does Resize And Fill Reusable Buffers print when run?
No setup needed: run the file and look for labeled lines like `grown:`, `truncated:`, `reset:` in the output.