copy_from_slice Fills Fixed Byte Buffers

Fill fixed-size buffers with copy_from_slice, which enforces equal lengths with a panic, and see how runtime-sized copies get an explicit bounds check first.

RustData Integrity

Code

rustsnippet
28 lines
fn main() {
    // 定长帧缓冲:MTU 风格固定大小,接收不足一整块的数据
    let mut frame = [0u8; 8];
    let payload = [0xAA, 0xBB, 0xCC];

    // copy_from_slice 要求两侧长度严格相等,否则 panic
    frame[..payload.len()].copy_from_slice(&payload);
    println!("frame: {frame:02X?}");

    // 运行期长度:先显式截断到缓冲区容量,再整块拷贝
    let incoming = vec![1u8, 2, 3, 4, 5];
    let mut buffer: Vec<u8> = vec![0; 8];
    let n = incoming.len().min(buffer.len());
    buffer[..n].copy_from_slice(&incoming[..n]);
    println!("buffer: {buffer:?} copied {n} of {}", incoming.len());

    // 长度不等是显式契约:直接 panic,而不是静默截断。
    // 闭包按可变借用捕获 target,而标准库对 &mut T 是显式否定实现
    // impl<T> !UnwindSafe for &mut T(unwind 中途放弃 &mut 可能破坏
    // 借用不变量),catch_unwind 要求 F: UnwindSafe,直接传闭包
    // 编译失败(E0277)。target 是不外逃的局部数组,该断言成立:
    let mut target = [0u8; 2];
    let mismatch =
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            target.copy_from_slice(&[1, 2, 3])
        }));
    println!("mismatch panicked: {}", mismatch.is_err());
}

How it works

Count the function main as the entire surface area of copy_from_slice Fills Fixed Byte Buffers.

Putting it to use

Running the file prints labeled results such as frame:, buffer:, mismatch panicked: — each operation’s effect is visible in the output.

Core lines

frame[..payload.len()].copy_from_slice(&payload);

Interactive Tools for This Topic

FAQ

What does copy_from_slice Fills Fixed Byte Buffers print when run?
No setup needed: run the file and look for labeled lines like `frame:`, `buffer:`, `mismatch panicked:` in the output.