# std::ptr

原始指標（raw pointer）`*const T`／`*mut T` 的工具函式，以及保證非空的指標 `NonNull<T>`。

## 這個模組做什麼

參考 `&T`／`&mut T` 由借用檢查器保證永遠有效。原始指標 `*const T`（唯讀）與 `*mut T`（可寫）則不受這些檢查：可以是空的（null）、可以指向已釋放的記憶體、可以同時有多個可寫指標。安全責任全部交給寫程式的人。

新手通常不需要原始指標；它們主要出現在：

| 情境 | 說明 |
| --- | --- |
| 和 C 程式互動（FFI） | C 的指標對應到 `*const T`／`*mut T`，見 [std::ffi](/pkg-ffi) |
| 實作底層資料結構 | 例如自己寫鏈結串列、記憶體配置器 |
| 比較兩個參考是不是同一個位置 | `ptr::eq`，這個是安全的 |

| 動作 | 需要 `unsafe` 嗎 |
| --- | --- |
| 建立原始指標（`&x as *const T`、`&raw const x`） | 不需要 |
| 比較、印出、轉型原始指標 | 不需要 |
| 解參考 `*p`、`ptr::read`、`ptr::write` | 需要 |

## 匯入

```rust
use std::ptr::{self, NonNull};
```

`*const T` 與 `*mut T` 是語言內建型別，不需要匯入；`ptr::null`、`ptr::eq`、`NonNull` 等需要寫路徑或 `use`。

## 常用 API

### 建立原始指標與 unsafe 解參考

用 `&raw const x`／`&raw mut x`（Rust 1.82 起）或 `&x as *const T` 從變數取得原始指標，這一步是安全的。解參考 `*p`（或用 `&*p` 轉回參考）則必須寫在 `unsafe` 區塊中，代表你向編譯器保證：指標非空、對齊正確、指向有效且已初始化的值，而且沒有違反別名規則。

注意：解參考無效指標（空指標、已釋放、未對齊）是未定義行為（undefined behavior），程式可能當掉、也可能悄悄產生錯誤結果。

簽名：
```rust
*const T
*mut T
```

範例：
```rust
fn main() {
    let mut score = 60;
    let write: *mut i32 = &raw mut score;
    let read: *const i32 = write as *const i32;

    unsafe {
        *write += 25;
        println!("透過 *const 讀到：{}", *read);
    }

    let text = String::from("hi");
    let p = &text as *const String;
    let r: &String = unsafe { &*p };
    println!("長度 {}", r.len());
    println!("score = {}", score);
}
```

輸出：
```text
透過 *const 讀到：85
長度 2
score = 85
```

### ptr::null 與 is_null

`ptr::null()` 與 `ptr::null_mut()` 產生空指標，對應 C 的 `NULL`。拿到外部傳入的指標時，先用 `is_null` 檢查再使用。`as_ref` 則把原始指標轉成 `Option<&T>`：空指標得到 `None`。

注意：`as_ref` 是 `unsafe`，因為非空的指標仍可能無效，函式只幫你檢查空值。

簽名：
```rust
pub const fn null<T>() -> *const T
pub const fn null_mut<T>() -> *mut T
pub const fn is_null(self) -> bool
pub unsafe fn as_ref<'a>(self) -> Option<&'a T>
```

範例：
```rust
use std::ptr;

fn describe(p: *const i32) -> String {
    match unsafe { p.as_ref() } {
        Some(v) => format!("值是 {}", v),
        None => String::from("空指標"),
    }
}

fn main() {
    let n = 42;
    let good: *const i32 = &n;
    let empty: *const i32 = ptr::null();
    let empty_mut: *mut u8 = ptr::null_mut();

    println!("good.is_null() = {}", good.is_null());
    println!("empty.is_null() = {}", empty.is_null());
    println!("empty_mut.is_null() = {}", empty_mut.is_null());
    println!("{} / {}", describe(good), describe(empty));
}
```

輸出：
```text
good.is_null() = false
empty.is_null() = true
empty_mut.is_null() = true
值是 42 / 空指標
```

### ptr::eq：比較是不是同一個位置

`==` 比較的是內容；`ptr::eq(a, b)` 比較兩個參考（或指標）是否指向同一個記憶體位置。這是安全函式，不需要 `unsafe`。

簽名：
```rust
pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool
```

範例：
```rust
use std::ptr;

fn main() {
    let a = String::from("相同內容");
    let b = String::from("相同內容");
    let a2 = &a;

    println!("a == b：{}", a == b);
    println!("ptr::eq(&a, &b)：{}", ptr::eq(&a, &b));
    println!("ptr::eq(&a, a2)：{}", ptr::eq(&a, a2));

    let arr = [10, 20, 30];
    let first = &arr[0];
    println!("first 是 arr[0]：{}", ptr::eq(first, &arr[0]));
    println!("first 是 arr[1]：{}", ptr::eq(first, &arr[1]));
}
```

輸出：
```text
a == b：true
ptr::eq(&a, &b)：false
ptr::eq(&a, a2)：true
first 是 arr[0]：true
first 是 arr[1]：false
```

### add 與 offset：指標運算

`p.add(n)` 回傳往後移 `n` 個元素（不是 `n` 個位元組）的指標，常用來走訪陣列。切片的 `as_ptr` 取得指向第一個元素的指標。

注意：`add` 是 `unsafe`，結果必須仍落在同一塊配置的記憶體內（或剛好在結尾後一格），超出範圍就是未定義行為。只需要計算位址而不解參考時，可用安全的 `wrapping_add`。

簽名：
```rust
pub const unsafe fn add(self, count: usize) -> *const T
pub fn as_ptr(&self) -> *const T
```

範例：
```rust
fn main() {
    let data = [3u16, 1, 4, 1, 5];
    let base: *const u16 = data.as_ptr();

    let mut sum = 0;
    for i in 0..data.len() {
        let v = unsafe { *base.add(i) };
        sum += v;
    }
    println!("總和 {}", sum);

    let third = unsafe { *base.add(2) };
    println!("第三個元素 {}", third);

    let end = base.wrapping_add(data.len());
    println!("結尾與起點相差 {} 個元素", unsafe { end.offset_from(base) });
}
```

輸出：
```text
總和 14
第三個元素 4
結尾與起點相差 5 個元素
```

### ptr::read、write 與 swap

`ptr::read` 從指標位置按位元複製出一個值（不管 `T` 是否 `Copy`）；`ptr::write` 把值寫進去且不會 drop 原本的舊值；`ptr::swap` 交換兩個位置的內容。這些是實作底層容器時的基本積木。

注意：`read` 出來的值與原位置的值是「同一份資料的兩個擁有者」，兩邊都 drop 會重複釋放；`write` 不會 drop 舊值，若舊值擁有資源就會洩漏。三者都是 `unsafe`。

簽名：
```rust
pub const unsafe fn read<T>(src: *const T) -> T
pub const unsafe fn write<T>(dst: *mut T, src: T)
pub const unsafe fn swap<T>(x: *mut T, y: *mut T)
```

範例：
```rust
use std::ptr;

fn main() {
    let mut a = [1, 2, 3];
    let p = a.as_mut_ptr();

    unsafe {
        let first = ptr::read(p);
        ptr::write(p.add(2), first * 100);
        ptr::swap(p, p.add(1));
    }
    println!("{:?}", a);

    let mut x = 5;
    let mut y = 9;
    unsafe { ptr::swap(&mut x, &mut y) };
    println!("x = {}, y = {}", x, y);
}
```

輸出：
```text
[2, 1, 100]
x = 9, y = 5
```

一般程式碼裡要交換兩個值，應該用安全的 `std::mem::swap`（見 [std::mem](/pkg-mem)）。

### NonNull：保證非空的指標

`NonNull<T>` 是包裝過的 `*mut T`，保證永遠不是空指標。好處有二：型別本身就表達「這裡一定有東西」；而且 `Option<NonNull<T>>` 與原始指標一樣大，`None` 用空值表示。標準庫的 `Box`、`Vec`、`Rc` 內部都用它。

`NonNull::new` 遇到空指標回傳 `None`；`as_ptr` 取回 `*mut T`；`as_ref`／`as_mut` 解參考，需要 `unsafe`。

簽名：
```rust
pub fn new(ptr: *mut T) -> Option<NonNull<T>>
pub const fn as_ptr(self) -> *mut T
pub const unsafe fn as_ref<'a>(&self) -> &'a T
pub const unsafe fn as_mut<'a>(&mut self) -> &'a mut T
```

範例：
```rust
use std::mem::size_of;
use std::ptr::{self, NonNull};

fn main() {
    let mut value = 7;
    let mut nn = NonNull::new(&raw mut value).expect("不會是空的");

    unsafe {
        *nn.as_mut() *= 6;
        println!("as_ref：{}", nn.as_ref());
    }
    println!("as_ptr 指向 value：{}", ptr::eq(nn.as_ptr(), &raw const value));

    let none = NonNull::new(ptr::null_mut::<i32>());
    println!("包裝空指標：{:?}", none.is_none());

    println!("*mut i32 = {} bytes", size_of::<*mut i32>());
    println!("Option<NonNull<i32>> = {} bytes", size_of::<Option<NonNull<i32>>>());
    println!("value = {}", value);
}
```

輸出：
```text
as_ref：42
as_ptr 指向 value：true
包裝空指標：true
*mut i32 = 8 bytes
Option<NonNull<i32>> = 8 bytes
value = 42
```

以上大小為 64 位元平台的結果。

### NonNull 搭配 Box：手動管理節點

實作鏈結結構時，常見做法是用 `Box::new` 配置節點、`Box::into_raw` 交出所有權並包進 `NonNull`，用完再以 `Box::from_raw` 收回釋放（見 [std::boxed](/pkg-boxed)）。`NonNull::from(&mut x)` 也能從參考直接建立，不需要 `unsafe`。

注意：每個透過 `into_raw` 交出的節點都必須剛好 `from_raw` 一次，否則不是洩漏就是重複釋放。

簽名：
```rust
impl<T: ?Sized> From<&mut T> for NonNull<T>
pub unsafe fn from_raw(raw: *mut T) -> Box<T>
```

範例：
```rust
use std::ptr::NonNull;

struct Node {
    val: i32,
    next: Option<NonNull<Node>>,
}

fn alloc(val: i32, next: Option<NonNull<Node>>) -> NonNull<Node> {
    let b = Box::new(Node { val, next });
    NonNull::from(Box::leak(b))
}

fn main() {
    let third = alloc(3, None);
    let second = alloc(2, Some(third));
    let head = alloc(1, Some(second));

    let mut cur = Some(head);
    let mut vals = Vec::new();
    while let Some(p) = cur {
        let node = unsafe { Box::from_raw(p.as_ptr()) };
        vals.push(node.val);
        cur = node.next;
    }
    println!("走訪並釋放：{:?}", vals);
}
```

輸出：
```text
走訪並釋放：[1, 2, 3]
```

`Box::leak` 回傳 `&mut Node`，透過 `NonNull::from` 包成指標；走訪時每個節點以 `Box::from_raw` 收回，`node` 離開迴圈本輪時就被釋放。

## 重點整理

- 原始指標可以為空、可以失效，建立安全、解參考必須 `unsafe`
- 解參考無效指標是未定義行為；外來指標先 `is_null` 或 `as_ref` 檢查
- `ptr::eq` 比較位置而非內容，是安全函式
- `add`、`read`、`write` 都是 `unsafe`，要自行保證範圍與所有權
- `NonNull<T>` 保證非空，`Option<NonNull<T>>` 不佔額外空間
