# Rust 1.25

Rust 1.25 發布於 2018-03-29，目前最新修補版為 `1.25.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.25 讓 `use` 可以巢狀分組，例如 `use std::{fs::File, io::Read, path::{Path, PathBuf}};`，一行就能整理一整串匯入；`match` 分支也允許以 `|` 開頭。對新手最直接的改變是 `cargo new` 預設建立可執行的程式（binary）而不是函式庫，建好就能 `cargo run`。其他重點包括升級到 LLVM 6、穩定 `#[repr(align(N))]` 與 `ptr::NonNull`，以及 Rust by Example 隨發行版一起提供。

### 語言變更

- `use` 支援巢狀匯入群組，詳見 [模組系統](/modules-system)。
- `match` 分支可以用 `|` 開頭，方便多行排列多個模式，詳見 [match](/control-match)。
- `#[repr(align(N))]` 穩定，可以指定型別的對齊方式，詳見 [std::mem](/pkg-mem)。

### 標準庫重點

- 新增 `ptr::NonNull<T>`：保證不為空的原始指標，`Option<NonNull<T>>` 和 `*mut T` 一樣大，詳見 [std::ptr](/pkg-ptr)。
- `Duration::new`、`Duration::from_secs`、`Duration::from_millis` 可以在常數運算式中使用；`Duration` 移到 libcore，詳見 [std::time](/pkg-time)。
- 新增 `Location::column`，詳見 [std::panic](/pkg-panic)。
- `UnsafeCell::into_inner` 改為安全函式；Unix 上的 `process::Command` 實作 `Send`。
- `Cursor<&mut Vec<u8>>` 實作 `Write`，詳見 [std::io](/pkg-io)；`Component` 實作 `AsRef<Path>`。

### Cargo 與工具

- `cargo new` 預設建立 binary crate，要函式庫請加 `--lib`，詳見 [Cargo](/start-cargo)。
- `cargo new` 不再自動去掉名稱中的 `rust-` 前綴或 `-rs` 後綴。
- `cargo doc` 改用 `cargo check` 的方式產生，部分情況更快；git 相依盡可能使用硬連結，簽出更快。
- rustdoc 預設改用 pulldown-cmark 解析 Markdown，完全遵循 CommonMark，詳見 [文件註解](/basics-comments-docs)。
- 新增 `-C lto=val` 編譯選項。

### 相容性注意

- 尚未穩定的 `net::lookup_host` 已棄用，穩定版程式改用 `ToSocketAddrs`，詳見 [std::net](/pkg-net)。
- 修正借用檢查器在索引運算附近錯誤允許重疊借用的問題，同時讓一些原本被誤判的正確程式碼可以編譯。
- 移除已棄用的不穩定屬性 `#[simd]`。

### 巢狀匯入與 match 開頭的 |

同一個 crate 底下的多個路徑，現在可以用大括號層層分組，一個 `use` 就寫完。`match` 分支開頭也可以多寫一個 `|`，多個模式垂直排列時每行看起來一致。

範例：

```rust
use std::{
    collections::{btree_map::Entry, BTreeMap},
    fmt::Write,
};

enum Level {
    Debug,
    Info,
    Warn,
    Error,
}

fn label(level: &Level) -> &'static str {
    match level {
        | Level::Debug
        | Level::Info => "一般",
        | Level::Warn
        | Level::Error => "需要注意",
    }
}

fn main() {
    let mut counts = BTreeMap::new();
    for level in [Level::Info, Level::Warn, Level::Debug, Level::Error, Level::Info] {
        match counts.entry(label(&level)) {
            Entry::Occupied(mut e) => *e.get_mut() += 1,
            Entry::Vacant(e) => {
                e.insert(1);
            }
        }
    }

    let mut report = String::new();
    write!(report, "{:?}", counts).unwrap();
    println!("{}", report);
}
```

輸出：

```text
{"一般": 3, "需要注意": 2}
```

注意：`use std::fmt::Write` 匯入的是特徵，`write!` 寫進 `String` 需要它在作用域內；匯入特徵後才能呼叫該特徵的方法。

### #[repr(align(N))]

對齊（alignment）決定一個值可以放在哪些記憶體位址：對齊 16 表示位址必須是 16 的倍數。`#[repr(align(N))]` 讓你把型別的對齊提高到 N（必須是 2 的次方），常見用途是讓資料剛好占一條 CPU 快取線（cache line），避免多執行緒互相干擾，或符合 SIMD 與硬體介面的要求。型別大小會被補齊到對齊的倍數。

以下數值為 64 位元平台的結果。

範例：

```rust
use std::mem::{align_of, size_of};

#[allow(dead_code)]
struct Plain(i32);

#[allow(dead_code)]
#[repr(align(16))]
struct Aligned16(i32);

#[allow(dead_code)]
#[repr(align(64))]
struct CacheLine {
    counter: u64,
}

fn main() {
    println!("Plain：align {}，size {}", align_of::<Plain>(), size_of::<Plain>());
    println!("Aligned16：align {}，size {}", align_of::<Aligned16>(), size_of::<Aligned16>());
    println!("CacheLine：align {}，size {}", align_of::<CacheLine>(), size_of::<CacheLine>());

    let items = [Aligned16(1), Aligned16(2)];
    let a = &items[0] as *const Aligned16 as usize;
    let b = &items[1] as *const Aligned16 as usize;
    println!("相鄰元素相距 {} bytes，位址是 16 的倍數：{}", b - a, a % 16 == 0);
}
```

輸出：

```text
Plain：align 4，size 4
Aligned16：align 16，size 16
CacheLine：align 64，size 64
相鄰元素相距 16 bytes，位址是 16 的倍數：true
```

注意：`align` 只能提高對齊，不能降低；N 不是 2 的次方會編譯失敗。要降低對齊請用 `#[repr(packed)]`，但存取其欄位需要特別小心。

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

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

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

## 資料來源

- [Rust 1.25 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1250-2018-03-29)
- [Rust 1.25 發布公告](https://blog.rust-lang.org/releases/1.25.0/)
- [rust-lang/rust 原始碼 1.25.0](https://github.com/rust-lang/rust/tree/1.25.0)
