docs

#1.1. 指针家族:Ptr / ConstPtr / ManyPtr / CPtr

本页内容

bare::ptr 模块定义五种裸指针。设计沿用 Zig 的数量编码模型:所指对象的数量(arity)和可变性都编码在类型本身中,从而完全排除静默的类型转换。

#1.1.1. 5 种指针

下表展示这五种指针的划分方式。

类型含义C 对应可为 null
Ptr<T>可变,恰好 1 个 TT*✗(用 Ptr<T> | none)
ConstPtr<T>const,恰好 1 个 Tconst T*✗
ManyPtr<T>可变,N 个连续的 T(长度未知)T*(数组)✗
Slice<T>只读,N 个连续的 T(包含长度)(const T*, len)✗(另有 niche)
CPtr<T>兼容 C,可为 null + 1T*(可为 null)✓(自动)

Ptr、ConstPtr、ManyPtr 和 CPtr 都是 #[repr(transparent)]:跨越 extern "C" 时它们就是 C 指针。

其中 Slice<T> 是 2.9 集合类型中定义的安全视图;本模块只定义从指针到 Slice 的途径(ManyPtr::slice)。指向列表元素的指针来自固定(1.6)。

#Send / Sync

裸指针 Ptr<T>、ConstPtr<T>、ManyPtr<T> 和 CPtr<T> 都是 !Send 和 !Sync(2.13.9)。要在线程之间传递包含指针的类型,其作者必须用 unsafe impl Send 为它担保。

#Trait

地址是值(0.5.12):Ptr<T>、ConstPtr<T>、ManyPtr<T> 和 CPtr<T> 实现 Clone、Copy、PartialEq、Eq、Hash、PartialOrd 和 Ord,全部按地址进行,还实现打印地址的 Debug。p == q 比较的是地址,从不比较所指对象。

#自动 niche

Ptr<T>、ConstPtr<T> 和 ManyPtr<T> 可以把 null 指针值用作 niche,所以加上 none 不需要额外的标签。这是一种优化,而不是保证:实现可以把 Ptr<T> | none 表示为普通的带标签和类型。

nabi
size_of::<Ptr<i32>>()         //→ 8 (64-bit target)
size_of::<Ptr<i32> | none>()  //→ 8 (implementation using the niche; not guaranteed)

而 CPtr<T> 本身就可为 null,所以不需要单独的哨兵值;它的 none 表示就是 CPtr::null()。

niche 机制见 2.2 non-zero。

#1.1.2. Ptr<T>:strict provenance API

最基本的类型 Ptr<T> 的公开 API 如下:

nabi
// module functions of bare::ptr (size_of / align_of: bare::mem, 1.3.6)
fn addr_of<T>(place: T) -> Ptr<T>;
fn many_addr_of<T>(place: T) -> ManyPtr<T>;
fn expose_provenance<T>(p: Ptr<T>) -> usize;
unsafe fn from_exposed_provenance<T>(addr: usize) -> Ptr<T>;

addr_of / many_addr_of 接受位置表达式(place expression):局部变量或 static(包括 extern "C" 的 static),或者它们的字段或元素。指向局部变量的指针在该变量处于作用域内时有效;指向静态变量的指针在整个运行期间有效(静态变量位于数据段中;延迟初始化的静态变量在取地址之前完成初始化;静态变量持有的 GC 引用是根)。通过指向非 mut 静态变量的指针写入是未定义行为。被取地址的变量在该作用域内一直是 GC 根,而根会被固定,所以所引用的对象不会移动。在协程体中,指针只在下一个挂起点之前有效。在挂起点之后使用这样的指针是编译错误。

#Strict provenance:分离的逃生口

usize → Ptr<T> 的转换默认被拒绝,因为解引用丢失了来源(provenance)的指针是未定义行为。因此正常路径和逃生口被明确分开。

nabi
use bare::ptr::{expose_provenance, from_exposed_provenance};

// recommended: provenance preserved
let p: Ptr<i32> = ...;
let q = p.with_addr(p.addr() + 4);     // 4 bytes further, provenance unchanged

// discouraged: fresh provenance (only for FFI / hardware registers)
let exposed: usize = expose_provenance(p);   // "exposes" p's provenance
let r: Ptr<i32> = unsafe { from_exposed_provenance(exposed) };
                                              // _assumes_ the new ptr has one of
                                              // the exposed provenances

这一设计的权威出发点是 Ralf Jung 的 “Pointers Are Complicated”,它与 2024 年 12 月在 Rust 1.84 中稳定的 Rust core::ptr::with_exposed_provenance 同构。

#示例:指针运算

下面的简短示例展示运算的用法。

nabi
let arr: [i32; 5] = [10, 20, 30, 40, 50];
let p: Ptr<i32> = bare::ptr::addr_of(arr[0]);

let p3 = p.add(3);                    // ptr to arr[3]
unsafe {
    let v = p3.read();                //→ 40
}

// byte arithmetic (struct field offset)
struct Header { magic: u32; size: u64; }
let h: Ptr<Header> = ...;
let size_ptr: Ptr<u64> = h.byte_offset(4).cast::<u64>();
                                      // location of Header.size
                                      // (alignment check needed; see 1.2 cast)

#1.1.3. ConstPtr<T>:只读

只读变体没有写入系列的方法。

nabi
struct ConstPtr<T> { /* opaque */ }

impl<T> ConstPtr<T> {
    fn dangling() -> ConstPtr<T>;

    fn addr(self) -> usize;
    fn with_addr(self, addr: usize) -> ConstPtr<T>;
    fn offset(self, count: isize) -> ConstPtr<T>;
    fn add(self, count: usize) -> ConstPtr<T>;
    fn sub(self, count: usize) -> ConstPtr<T>;

    fn cast<U>(self) -> ConstPtr<U>;
    fn as_many(self) -> ManyPtr<T>;

    unsafe fn read(self) -> T;
    unsafe fn read_volatile(self) -> T;
    // no write methods: read-only
}

与 Ptr<T> 互相转换是否安全取决于方向。加上 const 没有代价;去掉 const 必须通过命名的强制转换 bare::const_cast(调用本身是安全的;通过结果写入是 unsafe)。

nabi
let m: Ptr<i32> = ...;
let c: ConstPtr<i32> = m.as_const();        // Ptr → ConstPtr (safe)

let c: ConstPtr<i32> = ...;
let m: Ptr<i32> = bare::const_cast(c);    // ConstPtr → Ptr (safe call; writes through m are unsafe; see 1.2 cast)

因此去掉 const 只能通过显式路径进行;不接受静默转换。

#1.1.4. ManyPtr<T>:N 个连续元素,长度未知

接下来是指向多个元素但没有长度信息的类型。

nabi
struct ManyPtr<T> { /* opaque */ }

impl<T> ManyPtr<T> {
    fn addr(self) -> usize;
    fn with_addr(self, addr: usize) -> ManyPtr<T>;

    fn offset(self, count: isize) -> ManyPtr<T>;
    fn add(self, count: usize) -> ManyPtr<T>;

    fn cast<U>(self) -> ManyPtr<U>;
    fn as_one(self) -> Ptr<T>;                  // the first element
    fn as_const(self) -> ConstPtr<T>;

    unsafe fn read(self, idx: usize) -> T;
    unsafe fn write(self, idx: usize, value: T);

    // no length information; the caller guarantees the index
    unsafe fn slice(self, len: usize) -> Slice<T>;        // attaches a length to make a Slice
}

它用于接收 C 的 T*(数组);由于没有长度信息,避免越界(OOB)是调用者的责任。在 GC 堆之外的内存上调用 slice 时,元素不得包含 GC 引用;否则是未定义行为。

nabi
extern "C" {
    fn read_buffer(out: ManyPtr<u8>, len: usize) -> usize;
}

let buf: [u8; 1024] = [0; 1024];
let read_count = unsafe {
    read_buffer(bare::ptr::many_addr_of(buf[0]), 1024)
};

#1.1.5. CPtr<T>:兼容 C 的可为 null 指针

与 C ABI 直接对应的可为 null 变体如下:

nabi
struct CPtr<T> { /* opaque, nullable */ }

impl<T> CPtr<T> {
    fn null() -> CPtr<T>;
    fn from_ptr(p: Ptr<T>) -> CPtr<T>;       // non-null
    fn from_const(p: ConstPtr<T>) -> CPtr<T>;
    fn from_addr(addr: usize) -> CPtr<T>;    // 0 = null

    fn is_null(self) -> bool;
    fn as_ptr(self) -> Ptr<T> | none;        // null → none
    fn as_const(self) -> ConstPtr<T> | none;

    fn addr(self) -> usize;                  // null = 0
}

它适用于 C 函数交换可为 null 的 T* 的边界。典型用法:

nabi
extern "C" {
    fn malloc(size: usize) -> CPtr<u8>;       // null on failure
    fn free(ptr: CPtr<u8>);
}

let buf: CPtr<u8> = unsafe { malloc(1024) };
match buf.as_ptr() {
    p: Ptr<u8> => process(p),
    none       => panic("malloc failed"),
}
unsafe { free(buf) };

得益于自动 niche,Ptr<T> | none 与 ABI 兼容,但在需要 -1 这样的显式哨兵值时,仅有 CPtr 是不够的。这时的标准做法是在新类型(newtype)上用 #[niche(-1)] 单独建模。

#1.1.6. 转换矩阵

这五种类型之间的转换途径汇总在一个矩阵中。

从 \ 到Ptr<T>ConstPtr<T>ManyPtr<T>CPtr<T>Slice<T>usize
Ptr<T>-.as_const() 安全.as_many() 安全CPtr::from_ptr(p).as_many().slice(len) unsafe.addr() 丢失来源
ConstPtr<T>bare::const_cast(c)-.as_many()CPtr::from_const(c).as_many().slice(len) unsafe.addr()
ManyPtr<T>.as_one() 安全.as_const()-CPtr::from_ptr(m.as_one()).slice(len) unsafe.addr()
CPtr<T>.as_ptr()?.as_const()?.as_ptr()?.as_many()-.as_ptr()?.as_many().slice(len) unsafe.addr()
Slice<T>pin.as_data_ptr()pin.as_data_ptr().as_const()pin.as_data_many_ptr()CPtr::from_ptr(pin.as_data_ptr())-pin.as_data_ptr().addr()
usizefrom_exposed_provenance(a) ⚠from_exposed_provenance(a).as_const() ⚠from_exposed_provenance(a).as_many() ⚠CPtr::from_addr(a)经由指针-

⚠ 标记创建新来源的逃生口。Slice<T> 本身没有指针访问器:在它那一行中,pin 是对该切片所查看的 List<T> 调用的 gc::pin(xs),指针指向列表的第一个元素,并在持有该固定期间有效(1.6)。

#1.1.7. 与其他语言的比较

与解决过同一问题的其他语言相比,Nabi 的定位就清楚了。

方面CRustZigNabi
单个指针T**const T / *mut T*T / *const TPtr<T> / ConstPtr<T>
多个指针T*(含糊)*const T(含糊)[*]TManyPtr<T>
带长度无&[T][]TSlice<T>
可为 null(所有指针)Option<*const T>?*TCPtr<T> 或 Ptr<T> | none
数量分离无部分(切片分开)✓(*T / [*]T 分开)✓(Zig 模型)
strict provenance无✓(1.84+)无✓(Rust 模型)
拒绝 as 强制转换允许允许(仅警告)显式 @ptrCast完全拒绝

如表所示,Nabi 最重要的三项决定是:第一,采用 Zig 式的数量分离,把五种指针清楚地分开;第二,采用 Rust 2024 的 strict provenance 模型;第三,强制使用显式强制转换,使 as 完全不能用于指针。这三项决定合在一起,避开了 C 和 Rust 的大部分指针陷阱。

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