# Rust 1.7

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

## 版本介紹

Rust 1.7 以標準庫為主，約 40 個 API 穩定，其中最重要的是 `HashMap` 可以換用自訂雜湊演算法：預設的 SipHash 能抵禦 DoS 攻擊，但對小型鍵不快，在可接受失去這層保護時換成 FNV 等演算法能明顯加速。同時穩定的還有 `Path::strip_prefix`、`sort_by_key`，以及各數值型別的 checked、saturating、overflowing 運算。升級要注意：RFC 1214 的關聯型別與生命週期健全性修正從 1.4 起警告至今，這版正式變成錯誤。

### 標準庫重點

- `HashMap::with_hasher`、`BuildHasher`、`BuildHasherDefault`、`RandomState` 等穩定，可以自選雜湊演算法，詳見 [HashMap](/pkg-collections-hash-map) 與 [std::hash](/pkg-hash)。
- `Path::strip_prefix`（原名 `relative_from`）去掉路徑前綴，失敗時回傳 `StripPrefixError`，詳見 [std::path](/pkg-path)。
- 數值型別新增 `checked_rem`、`checked_neg`、`checked_shl`、`saturating_mul`、`overflowing_add` 等運算，詳見 [std::num](/pkg-num)。
- 切片新增 `sort_by_key`；`clone_from_slice` 穩定並要求兩個切片等長，詳見 [切片](/pkg-slice)。
- `Vec::as_slice`、`String::as_str` 等明確取得切片的方法穩定，詳見 [String](/pkg-string)。
- `Ipv4Addr` 新增 `is_loopback`、`is_private`、`is_multicast` 等判斷方法，詳見 [std::net](/pkg-net)。
- `CString::into_string`、`into_bytes` 等 FFI 相關 API 穩定，詳見 [std::ffi](/pkg-ffi)。
- ASCII 輸入的 UTF-8 驗證快 7 到 14 倍；`BTreeMap` 重寫，記憶體用量更少、走訪最多快 5 倍。
- `str::replace` 接受 `Pattern`；`Any` 實作於不定大小型別；`Duration` 實作 `Hash`。

### Cargo 與工具

- `cargo rustc` 接受 `--profile`，可用 dev、bench、test 等設定檔執行，詳見 [Cargo](/modules-cargo)。
- 建置腳本的 `rerun-if-changed` 在某些情況會讓建置腳本多跑一次的問題已修正。
- 編譯器預設帶 RPATH 資訊，安裝在特殊位置時不必另外設定動態連結器的搜尋路徑。

### 相容性注意

- RFC 1214 的健全性修正正式產生錯誤，已知會破壞既有程式碼。
- 編譯器的可見性計算修正了多個 bug，新錯誤先以 `private_in_public` lint 的警告呈現。
- 出現在型別定義以外的預設型別參數會產生警告，未來會變成錯誤。
- 把 `"."` 解析成浮點數改為回傳 `Err`，不再得到 `Ok(0.0)`。
- 閉包參數的借用不能活得比閉包久，詳見 [閉包](/closures-basics)。

### 自訂 HashMap 的雜湊演算法

`HashMap` 的第三個型別參數決定雜湊演算法。實作 `Hasher` 特徵，再用 `BuildHasherDefault` 包起來，就得到一個能用 `default()` 建立的 `HashMap`。下面自己寫一個簡單的 FNV-1a 雜湊器，實務上可以改用 crates.io 上現成的實作。

範例：

```rust
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};

struct Fnv1a(u64);

impl Default for Fnv1a {
    fn default() -> Self {
        Fnv1a(0xcbf29ce484222325)
    }
}

impl Hasher for Fnv1a {
    fn finish(&self) -> u64 {
        self.0
    }

    fn write(&mut self, bytes: &[u8]) {
        for b in bytes {
            self.0 ^= u64::from(*b);
            self.0 = self.0.wrapping_mul(0x100000001b3);
        }
    }
}

type FastMap<K, V> = HashMap<K, V, BuildHasherDefault<Fnv1a>>;

fn main() {
    let mut map: FastMap<u32, &str> = FastMap::default();
    map.insert(1, "one");
    map.insert(2, "two");
    map.insert(3, "three");

    let mut keys: Vec<_> = map.keys().copied().collect();
    keys.sort();
    println!("{:?}", keys);
    println!("{:?}", map.get(&2));
}
```

輸出：

```text
[1, 2, 3]
Some("two")
```

注意：換成非加密的雜湊演算法就失去 SipHash 對 DoS 攻擊的防護；鍵來自不可信的外部輸入（例如 HTTP 請求）時，保留預設的 `RandomState`。

### checked、saturating、overflowing 運算

預設算術溢位在除錯建置會 panic。需要明確處理溢位時：`checked_*` 溢位回傳 `None`，`saturating_*` 停在最大／最小值，`overflowing_*` 回傳環繞後的結果與是否溢位的旗標。除以零時 `checked_rem` 也會回傳 `None`。

範例：

```rust
fn main() {
    let a: u8 = 250;
    println!("{:?}", a.checked_add(10));
    println!("{}", a.saturating_add(10));
    println!("{:?}", a.overflowing_add(10));
    println!("{}", 100i32.saturating_mul(i32::MAX));
    println!("{:?}", 7i32.checked_rem(0));
}
```

輸出：

```text
None
255
(4, true)
2147483647
None
```

### Path::strip_prefix 與 sort_by_key

`strip_prefix` 去掉路徑開頭的一段，得到相對路徑；前綴不符時回傳 `Err`。`sort_by_key` 依照從元素取出的鍵排序。同一版把 `"."` 解析成浮點數改為錯誤，也一併示範。

範例：

```rust
use std::path::Path;

fn main() {
    let full = Path::new("/home/ferris/project/src/main.rs");
    let rel = full.strip_prefix("/home/ferris/project").unwrap();
    println!("{}", rel.display());
    println!("{}", full.strip_prefix("/opt").is_err());

    let mut people = vec![("Bob", 30), ("Alice", 25), ("Carol", 35)];
    people.sort_by_key(|p| p.1);
    println!("{:?}", people);

    println!("{:?}", ".".parse::<f32>().is_err());
}
```

輸出：

```text
src/main.rs
true
[("Alice", 25), ("Bob", 30), ("Carol", 35)]
true
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.7.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-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-2018-1000657](https://github.com/rust-lang/rust/issues/44800) | std | Buffer overflow vulnerability in VecDeque::reserve() | 1.3.0 起，早於 1.22.0 | [1.22.0](/rust-1-22) |
| [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) |
| [CVE-2017-20004](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-20004) | std | MutexGuard\<Cell\<i32\>\> must not be Sync | 早於 1.19.0 | [1.19.0](/rust-1-19) |

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

## 資料來源

- [Rust 1.7 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-170-2016-03-03)
- [Rust 1.7 發布公告](https://blog.rust-lang.org/releases/1.7.0/)
- [rust-lang/rust 原始碼 1.7.0](https://github.com/rust-lang/rust/tree/1.7.0)
