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 collections 中定義的安全檢視;本模組只定義從指標到 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>:嚴格來源 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 接受位置運算式:區域變數或 static(包括 extern "C" 的 static),或其欄位或元素。指向區域變數的指標在該變數位於作用域內時有效;指向靜態變數的指標在整個執行期間有效(靜態變數位於資料區段;惰性初始化的靜態變數會在取址之前初始化;靜態變數持有的 GC 參考是根)。透過指向非 mut 靜態變數的指標寫入是未定義行為。被取址的變數在該作用域內保持為 GC 根,而根會固定物件,因此被參考物不會移動。在協程主體中,指標只在下一個暫停點之前有效。在暫停點之後使用這種指標是編譯錯誤。

#嚴格來源:分開的逃生門

usize → Ptr<T> 的轉換預設會被拒絕,因為對失去來源的指標解參考是 UB。因此一般路徑與逃生門明確分開。

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*(陣列);由於沒有長度資訊,避免越界存取是呼叫端的責任。在 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 模型)
嚴格來源無✓(1.84+)無✓(Rust 模型)
拒絕 as 強制轉型允許允許(僅警告)明確的 @ptrCast完全拒絕

如表所示,Nabi 最重要的三項決定是:第一,採用 Zig 風格的數量區分,把五種指標清楚劃分;第二,採用 Rust 2024 的嚴格來源模型;第三,強制明確的強制轉型,使指標完全不能使用 as。這三項決定合起來,避開了 C 和 Rust 大部分的指標陷阱。

發現錯誤? 在 GitHub 上編輯此頁 最後更新: