# Rust 1.5

Rust 1.5 發布於 2015-12-10，目前最新修補版為 `1.5.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.5 最大的消息是 `cargo install`：可以把 crates.io 上的 Rust 應用程式安裝到 `~/.cargo/bin`，名為 `cargo-foo` 的執行檔還能直接用 `cargo foo` 當成 Cargo 子命令呼叫。標準庫穩定了大量路徑與檔案系統相關的 API（`Path::exists`、`Path::is_file`、`fs::canonicalize` 等），crate metadata 也縮小約 20%。升級要注意：發布到 crates.io 時使用萬用字元（`*`）版本的相依會出現警告，1.6 起直接禁止。

### 語言變更

- 在非常數情境下於編譯期求值時，過長的位移或算術溢位改為警告而非錯誤，錯誤延到執行期才發生。
- `improper_ctypes` lint 不再對 FFI 中使用 `isize`／`usize` 發出警告，詳見 [FFI](/lowlevel-ffi)。

### 標準庫重點

- `Path` 新增 `exists`、`is_file`、`is_dir`、`metadata`、`read_dir`、`canonicalize` 等方法，詳見 [std::path](/pkg-path)。
- `Vec::resize` 把長度調整成指定值，不足的部分以給定值補上，詳見 [Vec](/pkg-vec)。
- 切片新增 `split_first`、`split_last`，詳見 [切片](/pkg-slice)。
- `str::match_indices` 與 `rmatch_indices` 回傳每個符合位置與內容，詳見 [&str](/pkg-str)。
- `Iterator` 新增 `eq`、`ne`、`lt`、`le`、`gt`、`ge`、`cmp`、`partial_cmp`，可以逐元素比較兩個迭代器，詳見 [std::iter](/pkg-iter)。
- `Formatter` 新增 `width`、`precision`、`fill`、`alternate` 等，自訂格式化時能讀取格式參數，詳見 [std::fmt](/pkg-fmt)。
- 整數之間、浮點數之間在不損失資訊時提供 `From` 轉換，詳見 [型別轉換](/types-conversion)。
- 解析整數時接受開頭的 `+`；`BinaryHeap::into_sorted_vec`、`Condvar::wait_timeout` 等穩定。
- `Arc<T>` 與 `Rc<T>` 對 `T` 改為共變（covariant）。

### Cargo 與工具

- 新增 `cargo install`，安裝 crates.io 上的應用程式（例如 rustfmt）或新的 Cargo 子命令，詳見 [Cargo 工具](/modules-tools)。
- 發布含萬用字元相依的 crate 會出現警告。

### 相容性注意

- dropck 判斷生命週期的規則不再依賴參數化（parametricity）。
- `Box`、`Rc`、`Arc` 新增 `AsRef`／`AsMut` 實作；內部型別有同名方法時可能產生衝突。
- 長期棄用的 `#[derive(Show)]` 已移除。
- 對無號整數取負號會產生錯誤。
- 父特徵（supertrait）含有 `Self` 的特徵不再是物件安全（object safe），詳見 [特徵物件](/traits-objects)。

### Vec::resize 與 split_first

`resize(n, value)` 把 `Vec` 調整成剛好 `n` 個元素：變長時用 `value` 補，變短時截掉尾端。`split_first` 一次取出「第一個元素」與「其餘部分」，空切片時回傳 `None`，比手動檢查長度再索引安全。

範例：

```rust
fn main() {
    let mut scores = vec![90, 85];
    scores.resize(5, 0);
    println!("{:?}", scores);
    scores.resize(3, 0);
    println!("{:?}", scores);

    if let Some((first, rest)) = scores.split_first() {
        println!("第一個 {}，其餘 {:?}", first, rest);
    }
    let empty: [i32; 0] = [];
    println!("{:?}", empty.split_last());
}
```

輸出：

```text
[90, 85, 0, 0, 0]
[90, 85, 0]
第一個 90，其餘 [85, 0]
None
```

### match_indices 找出所有位置

`find` 只回傳第一個符合的位置；`match_indices` 回傳每個符合的 `(位置, 內容)`，`rmatch_indices` 則從尾端往前找。整數解析接受 `+` 號也一併示範。

範例：

```rust
fn main() {
    let log = "ok,err,ok,ok,err";
    let errs: Vec<(usize, &str)> = log.match_indices("err").collect();
    println!("{:?}", errs);

    let last_ok: Vec<(usize, &str)> = log.rmatch_indices("ok").take(1).collect();
    println!("{:?}", last_ok);

    println!("{:?}", "+42".parse::<i32>());
}
```

輸出：

```text
[(3, "err"), (13, "err")]
[(10, "ok")]
Ok(42)
```

### 比較兩個迭代器

迭代器的 `eq`、`cmp` 會逐一比較元素，不必先收集成 `Vec`。下面用它比較版本號：把每段轉成數字再比，`1.4.0` 小於 `1.10.0`；直接比較字串則會依字典序得到相反的結果。

範例：

```rust
use std::cmp::Ordering;

fn main() {
    let a = [1, 2, 3];
    let v = vec![1, 2, 3];
    println!("{}", a.iter().eq(v.iter()));

    let version_a = "1.4.0".split('.').map(|s| s.parse::<u32>().unwrap());
    let version_b = "1.10.0".split('.').map(|s| s.parse::<u32>().unwrap());
    let ord = version_a.cmp(version_b);
    println!("{:?}", ord);
    println!("{}", ord == Ordering::Less);

    println!("{}", "1.4.0" < "1.10.0");
}
```

輸出：

```text
true
Less
true
false
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.5.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.5 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-150-2015-12-10)
- [Rust 1.5 發布公告](https://blog.rust-lang.org/releases/1.5.0/)
- [rust-lang/rust 原始碼 1.5.0](https://github.com/rust-lang/rust/tree/1.5.0)
