当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust write_bytes用法及代码示例


本文简要介绍rust语言中 Function std::intrinsics::write_bytes 的用法。

用法

pub unsafe fn write_bytes<T>(dst: *mut T, val: u8, count: usize)

将从 dst 开始的 count * size_of::<T>() 字节内存设置为 val

write_bytes 类似于 C 的 memset ,但将 count * size_of::<T>() 字节设置为 val

安全性

如果违反以下任何条件,则行为未定义:

  • 对于 count * size_of::<T>() 字节的写入,dst 必须是 valid

  • dst 必须正确对齐。

此外,调用者必须确保将 count * size_of::<T>() 字节写入给定的内存区域会产生 T 的有效值。使用类型为 T 且包含无效值 T 的内存区域是未定义的行为。

请注意,即使有效复制的大小 ( count * size_of::<T>() ) 是 0 ,指针也必须非空且正确对齐。

例子

基本用法:

use std::ptr;

let mut vec = vec![0u32; 4];
unsafe {
    let vec_ptr = vec.as_mut_ptr();
    ptr::write_bytes(vec_ptr, 0xfe, 2);
}
assert_eq!(vec, [0xfefefefe, 0xfefefefe, 0, 0]);

创建无效值:

use std::ptr;

let mut v = Box::new(0i32);

unsafe {
    // Leaks the previously held value by overwriting the `Box<T>` with
    // a null pointer.
    ptr::write_bytes(&mut v as *mut Box<i32>, 0, 1);
}

// At this point, using or dropping `v` results in undefined behavior.
// drop(v); // ERROR

// Even leaking `v` "uses" it, and hence is undefined behavior.
// mem::forget(v); // ERROR

// In fact, `v` is invalid according to basic type layout invariants, so *any*
// operation touching it is undefined behavior.
// let v2 = v; // ERROR

unsafe {
    // Let us instead put in a valid value
    ptr::write(&mut v as *mut Box<i32>, Box::new(42i32));
}

// Now the box is fine
assert_eq!(*v, 42);

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Function std::intrinsics::write_bytes。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。