docs

#1.3. MaybeUninit<T>:未初始化内存

本页内容

bare::mem 模块定义用于安全处理未初始化内存的包装类型及相关操作。普通的 T 总是保证已初始化,而 MaybeUninit<T> 在类型层面显式表达初始化状态。

#1.3.1. 动机:读取未初始化内存是未定义行为

读取未初始化内存是未定义行为,即使对整数类型也是如此。问题不只是读出一个“垃圾值”;编译器可以对这个值做任何假设,并据此变换代码。

c
// C
int x;            // uninit
if (x == 0) { ... }   // the compiler may assume any value for x; either branch may become dead code

因此 T 本身无法表示未初始化状态,需要一个单独的包装类型。

#1.3.2. MaybeUninit<T>

nabi
struct MaybeUninit<T> { /* same size + align as T, but possibly uninitialized */ }

impl<T> MaybeUninit<T> {
    fn uninit() -> MaybeUninit<T>;          // uninitialized slot
    fn zeroed() -> MaybeUninit<T>;          // filled with 0
    fn new(value: T) -> MaybeUninit<T>;     // initialized slot

    fn write(ref self, value: T);           // write value

    fn as_ptr(self) -> ConstPtr<T>;
    fn as_mut_ptr(ref self) -> Ptr<T>;

    unsafe fn assume_init(self) -> T;
    // SAFETY: only when initialization is guaranteed by write / an external mechanism

}

as_ptr / as_mut_ptr 要求接收者是一个位置:指针指向该变量,而不是它的副本。uninit() 可以实现为 zeroed()。

#示例:分离初始化步骤

典型模式:等 FFI 填满缓冲区,再取出值。

nabi
let buf: MaybeUninit<[u8; 1024]> = MaybeUninit::uninit();
let p: Ptr<u8> = buf.as_mut_ptr().cast::<u8>();

unsafe {
    read_from_kernel(p, 1024);              // FFI fills buf
    let initialized: [u8; 1024] = buf.assume_init();
}

#在 write 之后使用

write 只存储值,不返回引用(Nabi 没有 ref 返回)。写入之后,用 assume_init 取出值。

nabi
let slot: MaybeUninit<Big> = MaybeUninit::uninit();
slot.write(big_value());
let v: Big = unsafe { slot.assume_init() };
process(v);

#1.3.3. Pod trait

nabi
unsafe trait Pod { /* marker */ }

Plain Old Data 的缩写:每一种位模式都有效的类型。1.2.5 的 reinterpret 要求这个标记。它是 unsafe trait(4.15.4):#[derive(Pod)] 生成实现,手写的实现是 unsafe impl Pod for T {}。无论哪种方式,结构体的布局、字段和 Drop 都按下面的规则检查。

自动实现不适用
所有整数(i*、u*)Ptr<T>(来源)
所有浮点数(f*)用户结构体(显式 #[derive(Pod)])
[T; N](T:Pod)enum(变体标签、niche)
最多 4 个元素且全部为 Pod 的元组
c_charbool、char(大多数位模式都不是值)

#Pod 的保证

Pod 同时保证三件事。

  1. 读取任何位模式都是安全的:不会暴露未初始化数据。
  2. 确定的布局:必须是 #[repr(C)] 或 #[repr(transparent)]。
  3. 没有 Drop:如果实现了 Drop,Pod 会被自动拒绝。
nabi
#[derive(Pod)]
#[repr(C)]
struct Vec3 { x: f32; y: f32; z: f32; }
// → reinterpret OK, ffi safe, etc.

#1.3.4. 裸内存操作:read / write

用于底层内存操作的自由函数如下:

nabi
unsafe fn read<T>(src: ConstPtr<T>) -> T;
unsafe fn write<T>(dst: Ptr<T>, value: T);

unsafe fn copy<T>(src: ConstPtr<T>, dst: Ptr<T>, count: usize);
                                               // memmove (overlap OK)
unsafe fn copy_nonoverlapping<T>(src: ConstPtr<T>, dst: Ptr<T>, count: usize);
                                               // memcpy (overlap UB, faster)

unsafe fn write_bytes<T>(dst: Ptr<T>, value: u8, count: usize);
                                               // memset (every byte = value)

unsafe fn swap<T>(a: Ptr<T>, b: Ptr<T>);
unsafe fn replace<T>(dst: Ptr<T>, value: T) -> T;     // read existing + write
unsafe fn drop_in_place<T>(p: Ptr<T>);               // runs the drop glue (does not free memory)

其中大多数也作为 Ptr<T> 的方法暴露(1.1.2);本模块的自由函数是一种更顺手的替代写法。volatile 访问是 bare::volatile::read / write(1.5),这是它唯一的路径。

drop_in_place 运行 drop glue:先运行类型自己的 drop,再按声明的逆序运行各字段的 drop(2.13.4)。

#1.3.5. transmute_unchecked:逃生口

它就是 1.2.6 中描述的函数。它定义在本模块中;bare::transmute_unchecked 是它在层级根上的重新导出。

nabi
unsafe fn transmute_unchecked<A, B>(a: A) -> B;        // no size check

#1.3.6. 对齐 / 大小工具

nabi
fn align_of<T>() -> usize;                  // T::align()
fn size_of<T>() -> usize;                   // T::size()

它们不是 unsafe。它们是 Reflect trait(2.12 reflect)中 T::size() / T::align() 的 bare 层级形式:bare 代码没有 Reflect。它们只在这里定义。没有值形式:一个值在运行时所持有内容的大小(和类型的成员、any 的内容)是 x.size_of_val()(2.12.2);bare 代码只有静态类型。

#1.3.7. 内建函数映射

各项与编译器内建函数(intrinsic)的对应关系如下:

项内建函数
MaybeUninit::as_ptr / as_mut_ptrnabi.addr_of(assume_init 是普通的字段读取)
ptr::addr_of / many_addr_ofnabi.addr_of
Pod(标记,自动派生)
read / writenabi.ptr.read / nabi.ptr.write(经由 Ptr / ConstPtr 的方法)
copy / copy_nonoverlapping无:逐元素 read / write 的循环(dst 高于 src 时 copy 反向进行)
write_bytes无:逐字节写入的循环
drop_in_placenabi.drop_in_place
size_of / align_ofnabi.size_of / nabi.align_of
buf_new / buf_get / buf_set / buf_samenabi.buf_new / nabi.buf_get / nabi.buf_set / nabi.buf_same

#1.3.8. 与其他语言的比较

方面CRustZigNabi
未初始化的表示T x;(静默)MaybeUninit<T>undefinedMaybeUninit<T>
Pod / 安全 transmute无bytemuck::Pod(库)@bitCastPod + reinterpret
未初始化读取允许UBUBUB
memcpy / memmovememcpyptr::copy*@memcpybare::mem::copy*

#1.3.9. GcBuf<T> 与 buf_* 原语

GcBuf<T> 是编译器已知的 GC 缓冲区,集合类型建立在它之上,它定义在本模块中。它的语义见 2.9.12,core::collections::raw 在那里重新导出它。

nabi
struct GcBuf<T> { /* one GC reference to a run of Ts */ }

impl<T> GcBuf<T> {
    unsafe fn new(len: usize) -> GcBuf<T>;     // = buf_new(len)
    unsafe fn get(self, i: usize) -> T;        // = buf_get(self, i)
    unsafe fn set(self, i: usize, v: T);       // = buf_set(self, i, v)
}
impl<T> Clone for GcBuf<T>;                    // the same handle: the clone shares the buffer

unsafe fn buf_new<T>(len: usize) -> GcBuf<T>;      // zeroed
unsafe fn buf_get<T>(buf: GcBuf<T>, i: usize) -> T;        // no bounds check
unsafe fn buf_set<T>(buf: GcBuf<T>, i: usize, v: T);       // no bounds check
fn buf_same<T>(a: GcBuf<T>, b: GcBuf<T>) -> bool;  // identity, not contents; pins nothing

发现错误? 在 GitHub 上编辑此页 最后更新: