# Rust 1.34

Rust 1.34 發布於 2019-04-11，目前最新修補版為 `1.34.2`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.34 讓 `TryFrom` 與 `TryInto` 正式穩定，「可能失敗的型別轉換」從此有了標準寫法；Cargo 也開始支援 crates.io 以外的替代 registry，企業可以架設私有套件庫。文件測試裡可以直接使用 `?`，範例程式寫起來更貼近真實程式。升級時要注意：`Command::before_exec` 將由 `unsafe` 的 `Command::pre_exec` 取代。

### 語言變更

- `#[deprecated = "reason"]` 可以作為 `#[deprecated(note = "reason")]` 的簡寫。
- 自訂屬性巨集的參數可以是任意 token 串流，例如 `#[range(0..10)]`，詳見 [程序式巨集](/macros-procedural)。
- 可以寫 `extern crate self as foo;`，把自己的 crate 根放進 extern prelude。

### 標準庫重點

- 穩定 `convert::TryFrom`、`convert::TryInto` 與 `convert::Infallible`，詳見 [std::convert](/pkg-convert) 與 [型別轉換](/types-conversion)。
- 新增固定寬度的原子整數 `AtomicU8`、`AtomicI16`、`AtomicU32`、`AtomicI64` 等，詳見 [std::sync::atomic](/pkg-sync-atomic)。
- `iter::from_fn` 與 `iter::successors` 用閉包建立迭代器，詳見 [std::iter](/pkg-iter)。
- `slice::sort_by_cached_key` 排序時每個元素只計算一次鍵值，詳見 [切片](/pkg-slice)。
- 新增 `NonZeroI8`、`NonZeroI32` 等有號 `NonZero` 型別；`Any::type_id` 穩定。
- `str::split_ascii_whitespace` 與 `str::escape_debug`、`escape_default`、`escape_unicode` 穩定，詳見 [str](/pkg-str)。
- `Instant` 與 `SystemTime` 新增 `checked_add`、`checked_sub`，詳見 [std::time](/pkg-time)。
- 所有數值型別新增 `checked_pow`、`saturating_pow`、`wrapping_pow`、`overflowing_pow`。
- `HashMap`、`HashSet`、`BinaryHeap` 部分基本方法移除了不必要的 trait 限制，例如建立迭代器不再要求 `Hash` 或 `Ord`。

### Cargo 與工具

- 可以使用 crates.io 以外的替代 registry，在相依中以 `registry` 指定來源；crates.io 上的 crate 不能依賴外部 registry。
- 文件測試可以直接使用 `?`，不必手動包一層 `fn main() -> Result<(), _>`，詳見 [文件測試](/testing-doc)。

### 相容性注意

- `ATOMIC_BOOL_INIT`、`ATOMIC_ISIZE_INIT`、`ATOMIC_USIZE_INIT` 已棄用，現在可以直接在 `static` 中呼叫 `const fn`（如 `AtomicUsize::new`）。

### TryFrom 與 TryInto

`as` 轉型在數值放不下時會靜默截斷，`300 as u8` 得到 `44` 而不報錯。`TryFrom` 改為回傳 `Result`，放得下就是 `Ok`，放不下就是 `Err`，呼叫端必須處理失敗。`TryInto` 是反方向的寫法，由目標型別推斷要轉成什麼。2021 edition 起兩者都在 prelude 裡，本書使用 2024 edition，所以範例不需要 `use`。

範例：

```rust
fn main() {
    let big: i64 = 300;
    let small: Result<u8, _> = u8::try_from(big);
    println!("{:?}", small);

    let ok: Result<u8, _> = 200i64.try_into();
    println!("{:?}", ok);

    match i32::try_from(u64::MAX) {
        Ok(v) => println!("轉換成功：{}", v),
        Err(e) => println!("轉換失敗：{}", e),
    }
}
```

輸出：

```text
Err(TryFromIntError(PosOverflow))
Ok(200)
轉換失敗：number too large to fit in target type
```

### iter::successors 與 iter::from_fn

`successors` 從一個起始值開始，每次用前一個值算出下一個，閉包回傳 `None` 時結束；範例用 `checked_mul` 產生 10 的次方，溢位前就會停。`from_fn` 每次呼叫閉包取得下一個元素，適合包裝「有狀態的產生器」。範例最後用 `sort_by_cached_key` 做不分大小寫排序，`to_lowercase` 對每個字串只執行一次。

範例：

```rust
use std::iter;

fn main() {
    let powers: Vec<u32> = iter::successors(Some(1u32), |&n| n.checked_mul(10))
        .take(5)
        .collect();
    println!("{:?}", powers);

    let mut count = 0;
    let counter = iter::from_fn(|| {
        count += 1;
        if count <= 3 { Some(count) } else { None }
    });
    println!("{:?}", counter.collect::<Vec<_>>());

    let mut words = vec!["banana", "Apple", "cherry"];
    words.sort_by_cached_key(|w| w.to_lowercase());
    println!("{:?}", words);
}
```

輸出：

```text
[1, 10, 100, 1000, 10000]
[1, 2, 3]
["Apple", "banana", "cherry"]
```

## 本版新增的棄用 API

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

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std::sync::atomic` | [`ATOMIC_BOOL_INIT`](https://doc.rust-lang.org/std/sync/atomic/constant.ATOMIC_BOOL_INIT.html) | the new function is now preferred |
| `std::sync::atomic` | [`ATOMIC_ISIZE_INIT`](https://doc.rust-lang.org/std/sync/atomic/constant.ATOMIC_ISIZE_INIT.html) | the new function is now preferred |
| `std::sync::atomic` | [`ATOMIC_USIZE_INIT`](https://doc.rust-lang.org/std/sync/atomic/constant.ATOMIC_USIZE_INIT.html) | the new function is now preferred |

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.34.1` | 2019-04-25 | 否 | Fix false positives for the `redundant_closure` Clippy lint；Fix false positives for the `missing_const_for_fn` Clippy lint；Fix Clippy panic when checking some macros |
| `1.34.2` | 2019-05-14 | 是 | Destabilize the `Error::type_id` function due to a security vulnerability ([CVE-2019-12083]) |

## 已知漏洞

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

### 本版已修正

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [CVE-2019-12083](https://groups.google.com/forum/#!topic/rustlang-security-announcements/aZabeCMUv70) | std | Memory safety vulnerabilities arising from `Error::type_id` | 1.34.0 起，早於 1.34.2 | [1.34.2](/rust-1-34) |

### 仍影響 `1.34.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) |

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

## 資料來源

- [Rust 1.34 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1340-2019-04-11)
- [Rust 1.34 發布公告](https://blog.rust-lang.org/releases/1.34.0/)
- [rust-lang/rust 原始碼 1.34.0](https://github.com/rust-lang/rust/tree/1.34.0)
