# Rust 1.10

Rust 1.10 發布於 2016-07-07，目前最新修補版為 `1.10.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.10 帶來最受期待的功能之一：用 `-C panic=abort` 或 `Cargo.toml` 的 `profile.*.panic = "abort"`，讓 panic 直接中止行程而不做堆疊回溯，粗估二進位檔小約 10%、編譯也快約 10%。同一版新增 `cdylib` crate 類型，用來產生給其他語言載入的動態函式庫，並穩定了 `panic::set_hook`／`take_hook` 等約 70 個 API。升級要注意：`AtomicBool` 的大小改為與 `bool` 相同；`Duration::new` 溢位時一律 panic。

### 語言變更

- `-C panic=abort` 讓 panic 在執行期直接中止，詳見 [panic](/errors-panic)。
- 新增 `cdylib` crate 類型，產生適合非 Rust 程式載入的動態函式庫；這版 Cargo 尚未直接支援，詳見 [FFI](/lowlevel-ffi)。
- `Copy` 型別的 `Clone` 實作必須是單純的複製，詳見 [移動與複製](/ownership-move-copy)。
- 只有一個變體的列舉也能使用 `#[repr(..)]`。

### 標準庫重點

- `panic::set_hook`、`take_hook` 可以註冊與移除 panic 時執行的鉤子（hook），`PanicInfo::payload`、`location` 與 `Location::file`、`line` 提供 panic 的內容與位置（`std::panic::PanicInfo` 這個名稱後來已棄用，見 [棄用 API](/deprecations)），詳見 [std::panic](/pkg-panic)。
- `CStr::from_bytes_with_nul` 從結尾帶 `\0` 的位元組切片建立 C 字串，詳見 [std::ffi](/pkg-ffi)。
- 原子型別新增 `compare_exchange` 與 `compare_exchange_weak`，詳見 [std::sync::atomic](/pkg-sync-atomic)。
- `BTreeMap`／`HashMap` 新增 `values_mut`，Entry 新增 `key`；切片新增 `binary_search_by_key`，詳見 [BTreeMap](/pkg-collections-btree-map)。
- `fs::Metadata` 新增 `modified`、`accessed`、`created`，詳見 [std::fs](/pkg-fs)。
- Unix 專用的 `std::os::unix::net`（`UnixStream`、`UnixListener`、`UnixDatagram`）穩定，詳見 [std::net](/pkg-net)。
- `sync::Weak::new` 穩定；`Mutex`、`RwLock`、`Condvar`、`CString` 等實作 `Default`；`Cell`／`RefCell` 在 `T: Ord` 時實作 `Ord`。
- `VecDeque` 與 `Vec` 可以用 `From`／`Into` 互轉。

### Cargo 與工具

- `Cargo.toml` 支援 `profile.*.panic`，可設為 `"unwind"`（預設）或 `"abort"`，詳見 [Cargo](/modules-cargo)。
- 新增 `cargo test --doc`，只執行文件測試，詳見 [文件測試](/testing-doc)。
- 新增 `cargo --explain`，對應 `rustc --explain`；`cargo install` 新增 `--force`。
- Cargo 的狀態訊息改輸出到 stderr；網路請求失敗預設重試兩次；Rust 關鍵字不能當 crate 名稱。
- Rust 改由上一個穩定版自舉建置（1.10 由 1.9 編譯），方便 Linux 發行版打包。

### 相容性注意

- `AtomicBool` 的大小改與 `bool` 相同，不再是一個 word。
- Linux ARM 目標的 `target_env` 一律是 `gnu`。
- `Duration::new` 溢位時一致 panic；`String::truncate` 減少 panic 的情況。
- 巨集解析的 follow set 調整，`:ty` 與 `:path` 後可以接 `:block`，詳見 [宣告式巨集](/macros-declarative)。
- 型別推論中部分退回與歧義錯誤被抑制，推論結果有些微改變。

### 自訂 panic 鉤子

`panic::set_hook` 取代預設的 panic 訊息輸出，鉤子會收到 panic 的內容（payload）與發生位置；`take_hook` 移除自訂鉤子並恢復預設行為。常見用途是把 panic 寫進日誌，或輸出更友善的錯誤訊息。

範例：

```rust
use std::panic;

fn main() {
    panic::set_hook(Box::new(|info| {
        let msg = info.payload().downcast_ref::<&str>().copied().unwrap_or("未知錯誤");
        match info.location() {
            Some(loc) => println!("[自訂] {} (第 {} 行)", msg, loc.line()),
            None => println!("[自訂] {}", msg),
        }
    }));

    let result = panic::catch_unwind(|| {
        panic!("設定檔格式錯誤");
    });
    println!("catch_unwind 回傳 Err：{}", result.is_err());

    let _ = panic::take_hook();
    println!("已移除自訂 hook，恢復預設行為");
}
```

輸出：

```text
[自訂] 設定檔格式錯誤 (第 13 行)
catch_unwind 回傳 Err：true
已移除自訂 hook，恢復預設行為
```

注意：`panic!` 只帶字串字面值時 payload 是 `&str`，帶格式化參數時是 `String`，兩種都要處理才完整。

### CStr::from_bytes_with_nul

呼叫 C 函式庫時常拿到「以 `\0` 結尾」的位元組。`from_bytes_with_nul` 會檢查切片恰好以一個 `\0` 結尾、中間沒有其他 `\0`，符合才建立 `CStr`，否則回傳錯誤。

範例：

```rust
use std::ffi::CStr;

fn main() {
    let ok = CStr::from_bytes_with_nul(b"hello\0").unwrap();
    println!("{:?} -> {:?}", ok, ok.to_str());

    println!("{:?}", CStr::from_bytes_with_nul(b"no nul").is_err());
    println!("{:?}", CStr::from_bytes_with_nul(b"in\0side\0").is_err());
}
```

輸出：

```text
"hello" -> Ok("hello")
true
true
```

### values_mut 與 binary_search_by_key

`values_mut` 一次借出映射所有值的可變參考，不必逐一以鍵查找；`binary_search_by_key` 在「依某個鍵排序」的切片上二分搜尋，找到回傳 `Ok(索引)`，找不到回傳 `Err(應插入的位置)`。

範例：

```rust
use std::collections::BTreeMap;

fn main() {
    let mut stock = BTreeMap::new();
    stock.insert("apple", 3);
    stock.insert("pear", 0);
    for count in stock.values_mut() {
        *count += 10;
    }
    println!("{:?}", stock);

    let users = [(101, "ann"), (205, "bob"), (309, "cat")];
    println!("{:?}", users.binary_search_by_key(&205, |&(id, _)| id));
    println!("{:?}", users.binary_search_by_key(&150, |&(id, _)| id));
}
```

輸出：

```text
{"apple": 13, "pear": 10}
Ok(1)
Err(1)
```

注意：`binary_search_by_key` 要求切片已依同一個鍵排序，否則結果沒有意義。

## 本版新增的棄用 API

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

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std` | [`f32::abs_sub`](https://doc.rust-lang.org/std/primitive.f32.html#method.abs_sub) | you probably meant (self - other).abs(): this operation is (self - other).max(0.0) except that abs_sub also propagates NaNs (also known as fdimf in C). If you truly need the positive difference, consider using that expression or the C function fdimf, depending on how you wish to handle NaN (please consider filing an issue describing your use-case too). |
| `std` | [`f64::abs_sub`](https://doc.rust-lang.org/std/primitive.f64.html#method.abs_sub) | you probably meant (self - other).abs(): this operation is (self - other).max(0.0) except that abs_sub also propagates NaNs (also known as fdim in C). If you truly need the positive difference, consider using that expression or the C function fdim, depending on how you wish to handle NaN (please consider filing an issue describing your use-case too). |

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.10.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-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) |
| [CVE-2019-16760](https://github.com/rust-lang/rust/security/advisories/GHSA-phjm-8x66-qw4r) | cargo | Cargo prior to Rust 1.26.0 may download the wrong dependency | 早於 1.26.0 | [1.26.0](/rust-1-26) |
| [CVE-2018-1000657](https://github.com/rust-lang/rust/issues/44800) | std | Buffer overflow vulnerability in VecDeque::reserve() | 1.3.0 起，早於 1.22.0 | [1.22.0](/rust-1-22) |
| [CVE-2018-1000622](https://groups.google.com/forum/#!topic/rustlang-security-announcements/4ybxYLTtXuM) | rustdoc | Uncontrolled search path element vulnerability in rustdoc plugins | 早於 1.27.1 | [1.27.1](/rust-1-27) |
| [CVE-2018-25008](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-25008) | std | Insufficient synchronization in `Arc::get_mut` | 1.3.0 起，早於 1.29.0 | [1.29.0](/rust-1-29) |
| [CVE-2017-20004](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-20004) | std | MutexGuard\<Cell\<i32\>\> must not be Sync | 早於 1.19.0 | [1.19.0](/rust-1-19) |

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

## 資料來源

- [Rust 1.10 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1100-2016-07-07)
- [Rust 1.10 發布公告](https://blog.rust-lang.org/releases/1.10.0/)
- [rust-lang/rust 原始碼 1.10.0](https://github.com/rust-lang/rust/tree/1.10.0)
