# Rust 1.45

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

## 版本介紹

Rust 1.45 修好了一個從 2013 年就存在的健全性（soundness）問題：浮點數用 `as` 轉成整數時，超出範圍的值以前是未定義行為（undefined behavior），現在固定改為「飽和轉換」。同一版讓函式型程序式巨集（procedural macro）可以用在運算式、模式與陳述式位置，Rocket 等框架因此能在 stable 上編譯。對新手來說，`300.0 as u8` 這類寫法從此有確定的結果；升級時要注意，依賴舊行為的極少數效能敏感程式可改用 `unsafe` 的 `to_int_unchecked`。

### 語言變更

- 超出範圍的浮點數轉整數改為飽和轉換：太大取最大值、太小取最小值、NaN 變 0，詳見 [型別轉換](/types-conversion)。
- 函式型程序式巨集可以出現在運算式、模式與陳述式位置，和 `macro_rules!` 巨集一樣，詳見 [程序式巨集](/macros-procedural)。
- `mem::Discriminant<T>` 改用 `T` 自己的判別值型別，不再一律用 `u64`。

### 標準庫重點

- `char` 可以搭配範圍型別逐一走訪碼位，例如 `'a'..='z'`，詳見 [char](/pkg-char)。
- 新增 `str::strip_prefix`、`str::strip_suffix`，詳見 [str](/pkg-str)。
- 新增 `Rc::as_ptr`、`Arc::as_ptr`，以及 `rc::Weak`／`sync::Weak` 的 `as_ptr`、`from_raw`、`into_raw`，詳見 [Rc](/pkg-rc)。
- 新增 `BTreeMap::remove_entry`，詳見 [BTreeMap](/pkg-collections-btree-map)。
- 有號整數新增 `saturating_neg`，所有整數新增 `saturating_abs`；原子整數型別新增 `fetch_min`、`fetch_max`、`fetch_update`，詳見 [原子型別](/pkg-sync-atomic)。
- `Box<[T]>` 實作 `From<[T; N]>`；`SocketAddr` 系列實作 `PartialOrd` 與 `Ord`。

### Cargo 與工具

- Cargo 改用 `embed-bitcode` 旗標減少磁碟用量與編譯時間。
- rustdoc 的 Markdown 支援刪除線 `~~文字~~`。
- 升級到 LLVM 10。

### 相容性注意

- 用自己初始化自己的 `static` 不健全，現在會編譯錯誤。
- Windows 上 `f32::powi`／`f64::powi` 的結果可能和以前有些微差異。
- 透過 `RUSTFLAGS` 自行開啟 `lto` 可能和 Cargo 加上的 `embed-bitcode=no` 衝突，建議改用 Cargo profile 控制 LTO。

### 浮點數轉整數改為飽和轉換

`as` 是 Rust 的基本型別轉換運算子。1.44 以前，把放不下的浮點數轉成小整數會產生未定義行為，而且程式裡根本沒有 `unsafe`。現在結果固定：超過上限得到該型別最大值，低於下限得到最小值，NaN 得到 0，範圍內的值則捨去小數。

範例：

```rust
fn main() {
    let values = [300.0_f32, -100.0, 42.9, f32::INFINITY];
    for v in values {
        println!("{v} as u8 = {}", v as u8);
    }
    let nan = "NaN".parse::<f32>().unwrap();
    println!("NaN as u8 = {}", nan as u8);
    println!("1e10 as i32 = {}", 1e10_f64 as i32);
}
```

輸出：

```text
300 as u8 = 255
-100 as u8 = 0
42.9 as u8 = 42
inf as u8 = 255
NaN as u8 = 0
1e10 as i32 = 2147483647
```

注意：飽和轉換不會報錯，數值「被默默截斷」仍可能是邏輯錯誤；需要知道是否超出範圍時，先自行檢查範圍再轉換。

### char 範圍

`char` 現在可以放進 `..`、`..=` 等範圍，直接當迭代器（iterator）使用，常用來產生字母表或檢查字元區間。

範例：

```rust
fn main() {
    let letters: String = ('a'..='e').collect();
    println!("{letters}");

    println!("{}", ('a'..='z').count());

    for c in 'x'..='z' {
        print!("{} ", c.to_ascii_uppercase());
    }
    println!();
}
```

輸出：

```text
abcde
26
X Y Z 
```

### strip_prefix 與 strip_suffix

想去掉字串開頭或結尾的固定文字時，`strip_prefix`／`strip_suffix` 回傳 `Option<&str>`：有該前綴（後綴）就是 `Some(剩下的部分)`，沒有就是 `None`，不必自己算索引切片。

範例：

```rust
fn main() {
    let url = "https://example.com/index.html";
    println!("{:?}", url.strip_prefix("https://"));
    println!("{:?}", url.strip_prefix("ftp://"));

    let name = "report.txt";
    match name.strip_suffix(".txt") {
        Some(stem) => println!("stem = {stem}"),
        None => println!("not a txt file"),
    }
}
```

輸出：

```text
Some("example.com/index.html")
None
stem = report
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.45.1` | 2020-07-30 | 否 | Fix const propagation with references.；rustfmt accepts rustfmt_skip in cfg_attr again.；Avoid spurious implicit region bound.；Install clippy on x.py install |
| `1.45.2` | 2020-08-03 | 否 | Fix bindings in tuple struct patterns；Fix track_caller integration with trait objects |

## 已知漏洞

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

### 仍影響 `1.45.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.45 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1450-2020-07-16)
- [Rust 1.45 發布公告](https://blog.rust-lang.org/releases/1.45.0/)
- [rust-lang/rust 原始碼 1.45.0](https://github.com/rust-lang/rust/tree/1.45.0)
