# Rust 1.33

Rust 1.33 發布於 2019-02-28，目前最新修補版為 `1.33.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.33 大幅擴充 `const fn` 能做的事，並穩定了「釘選」（pinning）的核心型別 `Pin` 與 `Unpin`，為後來的 async/await 打下基礎。模式比對也更好用：`if let`、`while let` 可以用 `|` 寫多個模式，整數的 `match` 只要涵蓋全部範圍就不必再加 `_` 分支。升級時要注意：`str::trim_left` 系列與 `Error::cause` 從這版開始產生棄用警告。

### 語言變更

- `if let` 與 `while let` 可以用 `|` 列出多個模式，語法與 `match` 相同，詳見 [模式](/control-patterns)。
- 整數模式可以窮盡：`u8` 的 `match` 涵蓋 `0..=255` 就不需要 `_ => unreachable!()`，詳見 [match](/control-match)。
- `const fn` 中可以使用 `let` 綁定、可變綁定、賦值、運算式陳述句與不可反駁的解構，也能呼叫 `unsafe const fn`，詳見 [常數](/basics-constants)。
- 可以用 `use std::io::Read as _;` 匯入 trait 的方法而不佔用名稱。
- `Rc`、`Arc`、`Pin` 可以作為方法的接收者（`self: Rc<Self>`）。
- `#[repr(packed(N))]` 可以指定對齊值；`cfg_attr` 可以一次寫多個屬性；新增 `cfg(target_vendor)`。
- 不可反駁的 `if let` 與 `while let`（例如 `if let _ = 5 {}`）可以編譯，但預設會產生警告。

### 標準庫重點

- 穩定 `pin::Pin`、`marker::Unpin`、`marker::PhantomPinned`，詳見 [std::pin](/pkg-pin)。
- `Option::transpose` 與 `Result::transpose` 在 `Option<Result<T, E>>` 與 `Result<Option<T>, E>` 之間互換，詳見 [Option](/pkg-option)。
- `Vec::resize_with` 與 `VecDeque::resize_with` 用閉包產生新元素，詳見 [Vec](/pkg-vec)。
- `Duration::as_millis`、`as_micros`、`as_nanos` 回傳 `u128` 的總量，詳見 [std::time](/pkg-time)。
- 新增 `convert::identity`；Unix 的 `FileExt::read_exact_at` 與 `write_all_at` 穩定。
- 整數的 `overflowing_*`、`wrapping_*`、`rotate_left`、`count_ones`、`leading_zeros` 等方法與 `Ipv4Addr::new` 改為 `const fn`。

### Cargo 與工具

- `cargo publish` 支援 `--features` 與 `--all-features`。
- 檔案在第一次建置過程中被修改時，Cargo 會重新建置該 crate。

### 相容性注意

- libtest 在 `--test-threads=1` 時不再為每個測試開新執行緒，並以固定順序執行測試。

### if let 的多重模式

以前 `if let` 只能寫一個模式，想同時處理兩個列舉成員就得改用 `match`。現在可以用 `|` 連接多個模式，只要每個模式綁定相同名稱、相同型別的變數即可。

範例：

```rust
enum Shape {
    Circle(f64),
    Square(f64),
    Point,
}

fn main() {
    let shapes = [Shape::Circle(1.5), Shape::Square(2.0), Shape::Point];
    for s in &shapes {
        if let Shape::Circle(size) | Shape::Square(size) = s {
            println!("有尺寸：{}", size);
        } else {
            println!("沒有尺寸");
        }
    }
}
```

輸出：

```text
有尺寸：1.5
有尺寸：2
沒有尺寸
```

### 窮盡的整數 match

編譯器現在會檢查整數範圍是否完全涵蓋。`u8` 只有 0 到 255，三個分支剛好涵蓋全部，就不再要求 `_` 分支；如果漏掉某段範圍，編譯器會指出缺少哪些值。

範例：

```rust
fn describe(b: u8) -> &'static str {
    match b {
        0 => "零",
        1..=127 => "ASCII 範圍",
        128..=255 => "高位元組",
    }
}

fn main() {
    for b in [0u8, 65, 200] {
        println!("{} {}", b, describe(b));
    }
}
```

輸出：

```text
0 零
65 ASCII 範圍
200 高位元組
```

### Option::transpose 與其他新 API

`transpose` 把「可能沒有的結果」翻轉成「可能失敗的可選值」，搭配 `?` 處理 `Option<Result<_, _>>` 特別方便。範例同時示範 `Duration::as_millis` 與 `Vec::resize_with`。

範例：

```rust
use std::time::Duration;

fn parse_all(inputs: &[&str]) -> Option<Result<i32, std::num::ParseIntError>> {
    inputs.first().map(|s| s.parse::<i32>())
}

fn main() {
    let r = parse_all(&["10"]).transpose();
    println!("{:?}", r);
    let empty = parse_all(&[]).transpose();
    println!("{:?}", empty);

    let d = Duration::from_secs(2);
    println!("{} ms", d.as_millis());

    let mut v = vec![1, 2];
    let mut next = 10;
    v.resize_with(5, || {
        next += 1;
        next
    });
    println!("{:?}", v);
}
```

輸出：

```text
Ok(Some(10))
Ok(None)
2000 ms
[1, 2, 11, 12, 13]
```

## 本版新增的棄用 API

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

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std` | [`str::trim_left`](https://doc.rust-lang.org/std/primitive.str.html#method.trim_left) | superseded by trim_start |
| `std` | [`str::trim_left_matches`](https://doc.rust-lang.org/std/primitive.str.html#method.trim_left_matches) | superseded by trim_start_matches |
| `std` | [`str::trim_right`](https://doc.rust-lang.org/std/primitive.str.html#method.trim_right) | superseded by trim_end |
| `std` | [`str::trim_right_matches`](https://doc.rust-lang.org/std/primitive.str.html#method.trim_right_matches) | superseded by trim_end_matches |
| `std::error` | [`Error::cause`](https://doc.rust-lang.org/std/error/trait.Error.html#method.cause) | replaced by Error::source, which can support downcasting |
| `std::string` | [`String::trim_left`](https://doc.rust-lang.org/std/string/struct.String.html#method.trim_left) | superseded by trim_start |
| `std::string` | [`String::trim_left_matches`](https://doc.rust-lang.org/std/string/struct.String.html#method.trim_left_matches) | superseded by trim_start_matches |
| `std::string` | [`String::trim_right`](https://doc.rust-lang.org/std/string/struct.String.html#method.trim_right) | superseded by trim_end |
| `std::string` | [`String::trim_right_matches`](https://doc.rust-lang.org/std/string/struct.String.html#method.trim_right_matches) | superseded by trim_end_matches |

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.33.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-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.33 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1330-2019-02-28)
- [Rust 1.33 發布公告](https://blog.rust-lang.org/releases/1.33.0/)
- [rust-lang/rust 原始碼 1.33.0](https://github.com/rust-lang/rust/tree/1.33.0)
