# Rust 1.28

Rust 1.28 發布於 2018-08-02，目前最新修補版為 `1.28.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.28 穩定了 `#[global_allocator]` 與 `GlobalAlloc` 特徵，程式可以自行決定向系統取得記憶體的方式，例如改用系統配置器或包一層統計用的配置器。標準庫新增 `NonZeroU8` 等「保證不為零」的整數型別，讓 `Option<NonZeroU8>` 只占 1 byte；單元測試函式也可以回傳 `Result`。對新手比較有感的是 `Duration` 的 `Debug` 輸出變成 `1s` 這種好讀的格式，以及 `format!` 寫錯時更具體的錯誤訊息。

### 語言變更

- `#[global_allocator]` 屬性與 `GlobalAlloc` 特徵穩定，詳見 [智慧指標](/smart-pointers-overview)。
- `#[test]` 函式可以回傳 `Result<(), E>`（`E: Debug`），測試裡能直接用 `?`，詳見 [單元測試](/testing-unit)。
- `#[repr(transparent)]` 穩定，讓單一欄位的新型別（newtype）在 FFI 邊界上與內部型別有相同表示，詳見 [FFI](/lowlevel-ffi)。
- `macro_rules!` 新增 `lifetime` 片段指定符，詳見 [宣告式巨集](/macros-declarative)。
- `pure`、`sizeof`、`alignof`、`offsetof` 不再是保留字。

### 標準庫重點

- 新增 `num::NonZeroU8`、`NonZeroU16`、`NonZeroU32`、`NonZeroU64`、`NonZeroU128`、`NonZeroUsize`，詳見 [std::num](/pkg-num)。
- 新增 `Iterator::step_by` 與 `iter::repeat_with`，詳見 [std::iter](/pkg-iter)。
- 新增 `hash_map::Entry::or_default`、`btree_map::Entry::or_default`，詳見 [HashMap](/pkg-collections-hash-map)。
- 新增 `Path::ancestors`，詳見 [std::path](/pkg-path)；新增 `SystemTime::UNIX_EPOCH`。
- 新增 `alloc::Layout`、`alloc::System`、`alloc::alloc`、`alloc::dealloc` 等配置相關 API。
- `Duration` 的 `Debug` 改為 `1s`、`1.5s` 這類格式，詳見 [std::time](/pkg-time)。
- 所有整數型別實作 `From<bool>`；`Cow` 新增多個 `From` 轉換，詳見 [std::borrow](/pkg-borrow)；`Any + Send + Sync` 也能 `downcast_ref`，詳見 [std::any](/pkg-any)。

### Cargo 與工具

- 不能發布建置腳本會修改 `src` 目錄的 crate。
- 最佳化等級 `s` 與 `z`（以縮小執行檔為優先）穩定；`--error-format=short` 穩定，錯誤訊息改為精簡格式。
- 巨集解析器減少記憶體配置，大量使用巨集的 crate 編譯平均快約 5%。

### 相容性注意

- 重複約束的特徵物件（如 `Trait + Send + Send`）被視為與不重複的型別相同，為兩者各寫一個 `impl` 會因重複定義而編譯失敗。

### NonZero 整數

`NonZeroU8` 保證值不是 0，所以編譯器可以把 0 拿來代表 `Option` 的 `None`，不必額外多存一個標籤位元組。這個最佳化會一路傳遞：把它包在自己的結構裡，`Option<結構>` 也一樣小。建立時用 `NonZeroU8::new`，傳入 0 會得到 `None`。

範例：

```rust
use std::mem::size_of;
use std::num::NonZeroU8;

struct Key(NonZeroU8);

struct Door {
    key: Key,
}

fn main() {
    println!("Option<u8>：{} byte", size_of::<Option<u8>>());
    println!("Option<NonZeroU8>：{} byte", size_of::<Option<NonZeroU8>>());
    println!("Option<Door>：{} byte", size_of::<Option<Door>>());

    let door = NonZeroU8::new(7).map(|n| Door { key: Key(n) });
    if let Some(d) = &door {
        println!("鑰匙編號：{}", d.key.0.get());
    }
    println!("0 能不能當鑰匙：{:?}", NonZeroU8::new(0));
}
```

輸出：

```text
Option<u8>：2 byte
Option<NonZeroU8>：1 byte
Option<Door>：1 byte
鑰匙編號：7
0 能不能當鑰匙：None
```

注意：取出內部的一般整數要呼叫 `.get()`；`NonZeroU8` 本身不能直接和 `u8` 做算術。

### 自訂全域配置器

實作 `GlobalAlloc` 的 `alloc` 與 `dealloc`，再用 `#[global_allocator]` 標記一個 `static`，整個程式的 `Box`、`Vec`、`String` 都會改由它配置記憶體。下面把工作轉交給系統配置器 `System`，只多做一件事：計算配置次數。

範例：

```rust
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};

struct Counting;

static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0);

unsafe impl GlobalAlloc for Counting {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        ALLOCATIONS.fetch_add(1, Ordering::SeqCst);
        unsafe { System.alloc(layout) }
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        unsafe { System.dealloc(ptr, layout) }
    }
}

#[global_allocator]
static GLOBAL: Counting = Counting;

fn main() {
    let before = ALLOCATIONS.load(Ordering::SeqCst);
    let v: Vec<u64> = Vec::with_capacity(100);
    let s = String::from("hello");
    let after = ALLOCATIONS.load(Ordering::SeqCst);
    println!("這段程式碼配置了 {} 次記憶體", after - before);
    println!("{} {}", v.capacity(), s);
}
```

輸出：

```text
這段程式碼配置了 2 次記憶體
100 hello
```

注意：`GlobalAlloc` 是 `unsafe` 特徵，實作者必須保證回傳的指標符合 `layout` 的大小與對齊；配置器裡不能再配置記憶體，否則會無限遞迴，詳見 [unsafe](/lowlevel-unsafe)。

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

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