# Rust 1.51

Rust 1.51 發布於 2021-03-25，目前最新修補版為 `1.51.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.51 穩定了 const generics 的最小可用版本（MVP）：型別與函式除了可以對型別、生命週期泛型，也能對常數值泛型，最典型的就是陣列長度 `[T; N]`。Cargo 同時推出新的特性解析器（feature resolver），用 `resolver = "2"` 開啟。對新手來說，「適用任意長度陣列」的函式從此能自己寫；目前常數參數只能是整數、`bool` 或 `char` 型別。

### 語言變更

- 函式、特徵與結構體等項目可以用常數值當泛型參數（const generics），例如 `struct Grid<const W: usize>`，詳見 [泛型](/generics-basics)。

### 標準庫重點

- 新增 `ptr::addr_of!`、`ptr::addr_of_mut!`，不經過參考直接取得欄位的原始指標，詳見 [std::ptr](/pkg-ptr)。
- 新增 `array::IntoIter`，以值走訪陣列，詳見 [陣列](/pkg-array)。
- 新增 `Peekable::next_if`、`Peekable::next_if_eq`，詳見 [std::iter](/pkg-iter)。
- 新增 `slice::fill_with`、`slice::split_inclusive`、`slice::strip_prefix`、`slice::strip_suffix` 與 `str::split_inclusive`，詳見 [切片](/pkg-slice)。
- 新增 `Arc::increment_strong_count`／`decrement_strong_count`、`Once::call_once_force`、`Seek::stream_position`、`panic::panic_any`、`task::Wake`、`VecDeque::range`。
- 所有有號整數新增 `unsigned_abs`；`u64` 與 `u128` 實作 `From<char>`。

### Cargo 與工具

- `Cargo.toml` 的 `[package]` 或 `[workspace]` 可以設定 `resolver = "2"`，避免建置相依、程序式巨集與目標相依的特性被不當合併，詳見 [Cargo](/modules-cargo)。
- 新增 `split-debuginfo` profile 選項；macOS 上設為 `unpacked` 可以跳過 `dsymutil`，大幅加快含除錯資訊的建置。
- 測試可以用 `cargo test -- --include-ignored` 一併執行標記 `#[ignore]` 的測試，詳見 [單元測試](/testing-unit)。
- intra-doc links 可以連到 `slice` 等原生型別、關聯項目與帶泛型參數的項目。

### 相容性注意

- `rustc` 不再把可能失敗的除法、取餘數與索引運算提升為 `const`。
- WASI 平台改用 wasm32 ABI。
- 部分平台的官方發行檔最低 glibc 版本提高到 2.31。

### const generics

在泛型參數寫 `const N: usize`，就能讓型別或函式依「數值」產生不同版本。下面的 `Grid<3, 2>` 在編譯期就確定是 3×2，`sum` 則能接受任意長度的 `i32` 陣列。

範例：

```rust
struct Grid<const W: usize, const H: usize> {
    cells: [[char; W]; H],
}

impl<const W: usize, const H: usize> Grid<W, H> {
    fn new(fill: char) -> Self {
        Grid { cells: [[fill; W]; H] }
    }

    fn area(&self) -> usize {
        W * H
    }
}

fn sum<const N: usize>(values: [i32; N]) -> i32 {
    values.iter().sum()
}

fn main() {
    let g: Grid<3, 2> = Grid::new('.');
    println!("{}", g.area());
    for row in &g.cells {
        println!("{}", row.iter().collect::<String>());
    }
    println!("{}", sum([1, 2, 3]));
    println!("{}", sum([10; 5]));
}
```

輸出：

```text
6
...
...
6
50
```

### ptr::addr_of!

`#[repr(packed)]` 結構體的欄位可能沒有對齊，而 Rust 要求參考 `&` 一定對齊，所以 `&h.len` 會是未定義行為。`addr_of!(h.len)` 直接產生原始指標，不經過參考，再用 `read_unaligned` 讀值。讀取原始指標需要 `unsafe`，觀念詳見 [unsafe](/lowlevel-unsafe)。

範例：

```rust
use std::ptr;

#[repr(packed)]
struct Header {
    tag: u8,
    len: u32,
}

fn main() {
    let h = Header { tag: 1, len: 512 };
    let p = ptr::addr_of!(h.len);
    let len = unsafe { p.read_unaligned() };
    let tag = h.tag;
    println!("tag={tag} len={len}");
}
```

輸出：

```text
tag=1 len=512
```

### Peekable::next_if

`next_if(條件)` 只在下一個元素符合條件時才取出，否則留在原地，適合寫簡單的解析器，例如先讀完開頭的數字。`next_if_eq(&值)` 則是比對相等的版本。

範例：

```rust
fn main() {
    let mut it = "123abc".chars().peekable();
    let mut digits = String::new();
    while let Some(c) = it.next_if(|c| c.is_ascii_digit()) {
        digits.push(c);
    }
    let rest: String = it.collect();
    println!("{digits} | {rest}");

    let mut nums = [1, 1, 2, 3].into_iter().peekable();
    let first = nums.next().unwrap();
    let mut repeat = 1;
    while nums.next_if_eq(&first).is_some() {
        repeat += 1;
    }
    println!("{first} 連續出現 {repeat} 次");
}
```

輸出：

```text
123 | abc
1 連續出現 2 次
```

注意：這版公告示範的 `std::array::IntoIter::new(array)` 已於 Rust 1.59 棄用（見 [棄用 API](/deprecations)），2021 版次起直接對陣列呼叫 `into_iter()` 或用 `for` 走訪即可，範例中的 `[1, 1, 2, 3].into_iter()` 就是這種寫法。

## 本版新增的棄用 API

以下 API 從 Rust 1.51 起標記為棄用（deprecated），新程式不要再使用；說明欄為官方原文。

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std::sync::atomic` | [`spin_loop_hint`](https://doc.rust-lang.org/std/sync/atomic/fn.spin_loop_hint.html) | use hint::spin_loop instead |

## 修補版本

本版沒有修補版本。

## 已知漏洞

影響 `1.51.0` 的已知漏洞共 16 個；在本版修正的共 0 個；仍影響最新修補版 `1.51.0` 的共 16 個。官方未公布影響範圍的漏洞只列在修正它的版本，不計入其他版本。

### 仍影響 `1.51.0`

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [CVE-2026-5222](https://github.com/rust-lang/cargo/security/advisories/GHSA-p688-r7jv-fm6f) | cargo | Cargo can be coerced to share credentials between registries | 早於 1.96.0 | [1.96.0](/rust-1-96) |
| [CVE-2026-5223](https://github.com/rust-lang/cargo/security/advisories/GHSA-jq42-7mfv-hm57) | cargo | Crates in third party registries can override the cached source of other crates | 早於 1.96.0 | [1.96.0](/rust-1-96) |
| [CVE-2024-43402](https://github.com/rust-lang/rust/security/advisories/GHSA-2xg3-7mm6-98jj) | std | `std::process::Command` batch files argument escaping could be bypassed with trailing whitespace or periods | 早於 1.81.0 | [1.81.0](/rust-1-81) |
| [CVE-2024-24576](https://github.com/rust-lang/rust/security/advisories/GHSA-q455-m56c-85mh) | std | `std::process::Command` did not properly escape arguments of batch files on Windows | 早於 1.77.2 | [1.77.2](/rust-1-77) |
| [CVE-2023-38497](https://github.com/rust-lang/cargo/security/advisories/GHSA-j3xp-wfr4-hx87) | cargo | Cargo not respecting umask when extracting crate archives | 早於 1.71.1 | [1.71.1](/rust-1-71) |
| [CVE-2022-46176](https://github.com/rust-lang/cargo/security/advisories/GHSA-r5w3-xm58-jv6j) | cargo | Cargo did not verify SSH host keys | 早於 1.66.1 | [1.66.1](/rust-1-66) |
| [CVE-2022-36113](https://github.com/rust-lang/cargo/security/advisories/GHSA-rfj2-q3h3-hm5j) | cargo | Extracting malicious crates can corrupt arbitrary files | 早於 1.64.0 | [1.64.0](/rust-1-64) |
| [CVE-2022-36114](https://github.com/rust-lang/cargo/security/advisories/GHSA-2hvr-h6gw-qrxp) | cargo | Extracting malicious crates can fill the file system | 早於 1.64.0 | [1.64.0](/rust-1-64) |
| [CVE-2022-21658](https://github.com/rust-lang/rust/security/advisories/GHSA-r9cc-f5pr-p3j2) | std | Race condition in std::fs::remove_dir_all | 早於 1.58.1 | [1.58.1](/rust-1-58) |
| [CVE-2021-42574](https://github.com/rust-lang/rust/security/advisories/GHSA-rcv6-wg5m-24v6) | rustc | rustc and bidirectional-override codepoints in source code | 早於 1.56.1 | [1.56.1](/rust-1-56) |
| [CVE-2021-31162](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-31162) | std | Double free in Vec::from_iter specialization when drop panics | 1.48.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28878](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28878) | std | Zip may call __iterator_get_unchecked twice with the same index | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28879](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28879) | std | Zip can cause buffer overflow when a consumed Zip iterator is used again | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28876](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28876) | std | Panic safety issue in Zip specialization | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2020-36323](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-36323) | std | API soundness issue in join() implementation of \[Borrow\<str\>\] | 1.28.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-29922](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-29922) | std | Improper Input Validation of octal literals in `std::net` | 早於 1.53.0 | [1.53.0](/rust-1-53) |

本版已停止支援，不會再修正這些漏洞；請升級到 `1.100.1`。

## 資料來源

- [Rust 1.51 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1510-2021-03-25)
- [Rust 1.51 發布公告](https://blog.rust-lang.org/releases/1.51.0/)
- [rust-lang/rust 原始碼 1.51.0](https://github.com/rust-lang/rust/tree/1.51.0)
