# Rust 1.3

Rust 1.3 發布於 2015-09-17，目前最新修補版為 `1.3.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.3 穩定了表示時間長度的 `Duration` 與 `std::time` 模組，`Error` 特徵物件也能像 `Any` 一樣向下轉型（downcast）回具體型別。官方文件新增專講 unsafe Rust 的《The Rustonomicon》，子字串搜尋改用 two-way 演算法而大幅加速。升級要注意：新的物件生命週期預設規則正式生效，`&'a Box<Trait>` 會被解讀成 `&'a Box<Trait + 'static>`，少數原本能編譯的程式會因 dropck 規則更新而失敗。

### 語言變更

- 新的物件生命週期預設（object lifetime default）規則在一個週期的警告後正式啟用，詳見 [特徵物件](/traits-objects)。
- 巨集中的型別與路徑後面可以接分號，詳見 [宣告式巨集](/macros-declarative)。
- `'static` 變數可以遞迴參考自己。
- `ref` 綁定會正確選擇 `Deref` 或 `DerefMut`，詳見 [模式](/control-patterns)。
- 檢查解構子不能存取已銷毀值的 dropck 規則已重寫並對齊 RFC。

### 標準庫重點

- `Duration` 與 `std::time` 模組穩定（目前模組內只有 `Duration`），詳見 [std::time](/pkg-time)。
- `Error` 特徵物件新增 `is`、`downcast`、`downcast_ref`、`downcast_mut`，詳見 [std::error](/pkg-error)。
- `io::Error` 新增 `get_ref`、`get_mut`、`into_inner` 取得內部錯誤，詳見 [std::io](/pkg-io)。
- `process::Child` 新增 `id`，回傳平台的行程識別碼，詳見 [std::process](/pkg-process)。
- `contains`、`find`、`rfind`、`split` 等子字串搜尋改用 two-way 演算法，`starts_with`／`ends_with` 也變快，詳見 [&str](/pkg-str)。
- `Hash` 特徵新增預設方法 `hash_slice`，`Hasher` 新增針對原始型別的 `write_*` 方法，詳見 [std::hash](/pkg-hash)。
- `Box<str>` 與 `Box<[T]>` 實作 `Clone`；`String` 實作 `DerefMut`。
- `CString` 實作 `Borrow`、`CStr` 實作 `ToOwned`，C 字串能在泛型程式碼中借用與複製，詳見 [std::ffi](/pkg-ffi)。
- `Wrapping` 型別支援 `Div` 運算子；`AtomicPtr` 實作 `Debug` 與 `Send`。

### Cargo 與工具

- 新書《The Rustonomicon》深入介紹 unsafe Rust，詳見 [unsafe](/lowlevel-unsafe)。
- Cargo 支援 lint 上限（lint capping）：相依套件的 lint 不再影響自己專案能否乾淨編譯。
- 編譯器新增許多延伸錯誤說明，可用 `--explain` 查看。
- 經過一些調整後可產生在 Windows XP 上執行的程式，但 XP 不是官方支援的平台。

### 相容性注意

- 物件生命週期預設規則改變，已知有一個尚未決定解法的回歸（regression）。
- `size_of_val` 與 `align_of_val` 對動態大小型別的行為改為更合理的結果，詳見 [std::mem](/pkg-mem)。
- dropck 規則更新修補了健全性（soundness）漏洞，部分原本能編譯的程式碼會失敗。
- 內部屬性 `#[prelude_import]` 先前被意外穩定，現改放在功能閘之後。

### Duration 表示時間長度

`Duration` 是「一段時間」而不是「某個時間點」，由秒與奈秒組成，可以相加、乘上整數、互相比較。標準庫的逾時、睡眠等 API 都以它為參數。

範例：

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

fn main() {
    let timeout = Duration::new(2, 500_000_000);
    println!("{:?}", timeout);
    println!("{} 秒又 {} 奈秒", timeout.as_secs(), timeout.subsec_nanos());

    let step = Duration::from_millis(250);
    let total = step * 4 + timeout;
    println!("{:?}", total);
    println!("{}", total > Duration::from_secs(3));
}
```

輸出：

```text
2.5s
2 秒又 500000000 奈秒
3.5s
true
```

注意：`Duration` 不能是負數；相減結果小於零時會 panic，需要時改用 `checked_sub`。

### Error 向下轉型

函式回傳 `Box<dyn Error>` 可以裝任何錯誤，但呼叫端有時要知道「到底是哪一種錯誤」。`downcast_ref::<T>()` 在型別相符時回傳 `Some(&T)`，`is::<T>()` 只回答是或不是，讓呼叫端依錯誤種類分別處理。

範例：

```rust
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
struct NotPositive(i64);

impl fmt::Display for NotPositive {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} 不是正數", self.0)
    }
}

impl Error for NotPositive {}

fn parse_positive(s: &str) -> Result<i64, Box<dyn Error>> {
    let n: i64 = s.parse()?;
    if n <= 0 {
        return Err(Box::new(NotPositive(n)));
    }
    Ok(n)
}

fn main() {
    for input in ["42", "-7", "abc"] {
        match parse_positive(input) {
            Ok(n) => println!("{input}: 成功 {n}"),
            Err(e) => {
                if let Some(np) = e.downcast_ref::<NotPositive>() {
                    println!("{input}: 業務錯誤，值為 {}", np.0);
                } else if e.is::<ParseIntError>() {
                    println!("{input}: 格式錯誤：{e}");
                }
            }
        }
    }
}
```

輸出：

```text
42: 成功 42
-7: 業務錯誤，值為 -7
abc: 格式錯誤：invalid digit found in string
```

## 本版新增的棄用 API

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

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std` | [`slice::connect`](https://doc.rust-lang.org/std/primitive.slice.html#method.connect) | renamed to join |
| `std::bstr` | [`ByteStr::connect`](https://doc.rust-lang.org/std/bstr/struct.ByteStr.html#method.connect) | renamed to join |
| `std::bstr` | [`ByteString::connect`](https://doc.rust-lang.org/std/bstr/struct.ByteString.html#method.connect) | renamed to join |
| `std::io` | [`IoSlice::connect`](https://doc.rust-lang.org/std/io/struct.IoSlice.html#method.connect) | renamed to join |
| `std::io` | [`IoSliceMut::connect`](https://doc.rust-lang.org/std/io/struct.IoSliceMut.html#method.connect) | renamed to join |
| `std::vec` | [`Vec::connect`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.connect) | renamed to join |

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.3.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.3 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-130-2015-09-17)
- [Rust 1.3 發布公告](https://blog.rust-lang.org/releases/1.3.0/)
- [rust-lang/rust 原始碼 1.3.0](https://github.com/rust-lang/rust/tree/1.3.0)
