# Rust 1.29

Rust 1.29 發布於 2018-09-13，目前最新修補版為 `1.29.2`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.29 是為 1.30 與 1.31（Rust 2018 edition）鋪路的小版本，主角是兩個和警告有關的 Cargo 工具：`cargo fix` 會自動套用編譯器建議來修正警告，也能協助把專案從 2015 edition 遷移到 2018；`cargo clippy` 預覽版提供大量額外的 lint，抓出語法正確但很可能有錯的寫法。標準庫只穩定了 `Iterator::flatten`、`Rc::downcast`、`Arc::downcast` 三個 API。升級時要注意：`std::env::home_dir` 因行為不直覺而被棄用（[Rust 1.87](/rust-1-87) 起已取消棄用）。

### 標準庫重點

- 新增 `Iterator::flatten`，把「迭代器的迭代器」攤平成一層，詳見 [迭代器](/iterators-basics)。
- 新增 `Rc::downcast`、`Arc::downcast`，把 `Rc<dyn Any>` 轉回具體型別，詳見 [std::any](/pkg-any)。
- `Once::call_once` 不再要求 `Once` 是 `'static`，詳見 [std::sync](/pkg-sync)。
- `Cell<T>` 允許 `T` 為大小不固定的型別；`Box<CStr>`、`Box<OsStr>`、`Box<Path>` 實作 `Clone`。
- `OsString` 與 `&str` 可以直接比較是否相等，詳見 [std::ffi](/pkg-ffi)。

### Cargo 與工具

- 新增 `cargo fix`，自動修正部分警告並協助遷移 edition，詳見 [Edition 演進](/evolution-editions)。
- 可以用 `rustup component add clippy-preview` 安裝 Clippy 預覽版，執行 `cargo clippy`，詳見 [開發工具](/modules-tools)。
- `cargo doc --document-private-items` 也會產生私有項目的文件，詳見 [文件註解](/basics-comments-docs)。
- Cargo 會自動修正被 git 合併弄壞的 lock 檔，加 `--locked` 可停用；`cargo install` 支援 `--target` 交叉編譯。
- `rustc` 與 `rustdoc` 編譯失敗時結束碼為 `1`，panic 時為 `101`；`rustdoc` 新增 `--cap-lints`。
- 升級到 LLVM 7。

### 相容性注意

- `std::env::home_dir` 已棄用（Rust 1.87 起取消棄用），`str::slice_unchecked`、`slice_unchecked_mut` 也已棄用，改用 `str::get_unchecked(begin..end)`，詳見 [棄用 API](/deprecations)。
- `cfg` 屬性與 `--cfg` 命令列旗標的檢查更嚴格；`rustc` 不再默默忽略目標規格中的無效資料。

### Iterator::flatten

當迭代器的每個元素本身也可以迭代（例如 `Vec<Vec<T>>`、`Option<T>`、`split` 的結果），`flatten` 會把它們依序串成一條。`Option` 也可以迭代，`Some(x)` 產生一個元素、`None` 不產生，所以 `flatten` 也能順便濾掉解析失敗的值。

範例：

```rust
fn main() {
    let teams = vec![vec!["Amy", "Ben"], vec![], vec!["Cat"]];
    let everyone: Vec<&str> = teams.into_iter().flatten().collect();
    println!("{:?}", everyone);

    let inputs = ["3", "x", "5", ""];
    let numbers: Vec<i32> = inputs.iter().map(|s| s.parse().ok()).flatten().collect();
    println!("{:?}", numbers);

    let lines = ["a,b", "c", "d,e,f"];
    let parts: Vec<&str> = lines.iter().map(|l| l.split(',')).flatten().collect();
    println!("{:?}", parts);
}
```

輸出：

```text
["Amy", "Ben", "Cat"]
[3, 5]
["a", "b", "c", "d", "e", "f"]
```

注意：`map(...).flatten()` 和早就存在的 `flat_map(...)` 等價，Clippy 會建議改寫成 `flat_map`；`flatten` 只攤平一層。

### Rc::downcast

`Rc<dyn Any>` 可以裝任何 `'static` 型別，但用的時候需要知道實際型別。`downcast::<T>()` 檢查內容是不是 `T`：是就回傳 `Ok(Rc<T>)`，不是就把原本的 `Rc<dyn Any>` 放在 `Err` 裡還給你，可以接著嘗試其他型別。`Arc::downcast` 用法相同，但要求 `dyn Any + Send + Sync`。

範例：

```rust
use std::any::Any;
use std::rc::Rc;

fn describe(value: Rc<dyn Any>) -> String {
    match value.downcast::<String>() {
        Ok(s) => format!("字串：{}", s),
        Err(other) => match other.downcast::<i32>() {
            Ok(n) => format!("整數：{}", n),
            Err(_) => String::from("不認得的型別"),
        },
    }
}

fn main() {
    let items: Vec<Rc<dyn Any>> = vec![
        Rc::new(String::from("Ferris")),
        Rc::new(42i32),
        Rc::new(1.5f64),
    ];
    for item in items {
        println!("{}", describe(item));
    }
}
```

輸出：

```text
字串：Ferris
整數：42
不認得的型別
```

注意：`downcast` 比對的是完全相同的型別，`Rc::new(42)` 沒標型別時預設是 `i32`，用 `downcast::<i64>()` 會失敗；能用列舉或特徵表達的情況，通常比 `Any` 更好，詳見 [列舉](/enums-basics)。

## 本版新增的棄用 API

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

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std` | [`str::slice_mut_unchecked`](https://doc.rust-lang.org/std/primitive.str.html#method.slice_mut_unchecked) | use get_unchecked_mut(begin..end) instead |
| `std` | [`str::slice_unchecked`](https://doc.rust-lang.org/std/primitive.str.html#method.slice_unchecked) | use get_unchecked(begin..end) instead |
| `std::string` | [`String::slice_mut_unchecked`](https://doc.rust-lang.org/std/string/struct.String.html#method.slice_mut_unchecked) | use get_unchecked_mut(begin..end) instead |
| `std::string` | [`String::slice_unchecked`](https://doc.rust-lang.org/std/string/struct.String.html#method.slice_unchecked) | use get_unchecked(begin..end) instead |

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.29.1` | 2018-09-25 | 否 | The standard library's `str::repeat` function contained an out of bounds write caused by an integer overflow. This has been fixed by deterministically panicking when an overflow happens. Thank you to Scott McMurray for responsibly disclosing this vulnerability to us. |
| `1.29.2` | 2018-10-11 | 否 | Workaround for an aliasing-related LLVM bug, which caused miscompilation.；The `rls-preview` component on the windows-gnu targets has been restored. |

## 已知漏洞

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

### 本版已修正

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [CVE-2018-1000810](https://groups.google.com/forum/#!topic/rustlang-security-announcements/CmSuTm-SaU0) | std | Buffer overflow vulnerability in str::repeat() | 1.26.0 起，早於 1.29.1 | [1.29.1](/rust-1-29) |

### 仍影響 `1.29.2`

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [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-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-2021-28875](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28875) | std | Logic bug in Read can cause buffer overflow in read_to_end() | 1.20.0 起，早於 1.50.0 | [1.50.0](/rust-1-50) |
| [CVE-2021-28877](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28877) | std | TrustedRandomAccess specialization composes incorrectly for nested iter::Zips | 1.11.0 起，早於 1.51.0 | [1.51.0](/rust-1-51) |
| [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-2020-36317](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-36317) | std | String::retain allows safely creating invalid strings when abusing panic | 1.26.0 起，早於 1.49.0 | [1.49.0](/rust-1-49) |
| [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-1010299](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-1010299) | std | vec_deque::Iter has unsound Debug implementation | 1.18.0 起，早於 1.30.0 | [1.30.0](/rust-1-30) |

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

## 資料來源

- [Rust 1.29 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1290-2018-09-13)
- [Rust 1.29 發布公告](https://blog.rust-lang.org/releases/1.29.0/)
- [rust-lang/rust 原始碼 1.29.0](https://github.com/rust-lang/rust/tree/1.29.0)
