Rust 1.34

最後更新


Rust 1.34 發布於 2019-04-11,目前最新修補版為 1.34.2,已停止支援,請升級到 1.100.1。

版本介紹


Rust 1.34 讓 TryFrom 與 TryInto 正式穩定,「可能失敗的型別轉換」從此有了標準寫法;Cargo 也開始支援 crates.io 以外的替代 registry,企業可以架設私有套件庫。文件測試裡可以直接使用 ?,範例程式寫起來更貼近真實程式。升級時要注意:Command::before_exec 將由 unsafe 的 Command::pre_exec 取代。

語言變更


  • #[deprecated = "reason"] 可以作為 #[deprecated(note = "reason")] 的簡寫。
  • 自訂屬性巨集的參數可以是任意 token 串流,例如 #[range(0..10)],詳見 程序式巨集。
  • 可以寫 extern crate self as foo;,把自己的 crate 根放進 extern prelude。

標準庫重點


  • 穩定 convert::TryFrom、convert::TryInto 與 convert::Infallible,詳見 std::convert 與 型別轉換。
  • 新增固定寬度的原子整數 AtomicU8、AtomicI16、AtomicU32、AtomicI64 等,詳見 std::sync::atomic。
  • iter::from_fn 與 iter::successors 用閉包建立迭代器,詳見 std::iter。
  • slice::sort_by_cached_key 排序時每個元素只計算一次鍵值,詳見 切片。
  • 新增 NonZeroI8、NonZeroI32 等有號 NonZero 型別;Any::type_id 穩定。
  • str::split_ascii_whitespace 與 str::escape_debug、escape_default、escape_unicode 穩定,詳見 str。
  • Instant 與 SystemTime 新增 checked_add、checked_sub,詳見 std::time。
  • 所有數值型別新增 checked_pow、saturating_pow、wrapping_pow、overflowing_pow。
  • HashMap、HashSet、BinaryHeap 部分基本方法移除了不必要的 trait 限制,例如建立迭代器不再要求 Hash 或 Ord。

Cargo 與工具


  • 可以使用 crates.io 以外的替代 registry,在相依中以 registry 指定來源;crates.io 上的 crate 不能依賴外部 registry。
  • 文件測試可以直接使用 ?,不必手動包一層 fn main() -> Result<(), _>,詳見 文件測試。

相容性注意


  • ATOMIC_BOOL_INIT、ATOMIC_ISIZE_INIT、ATOMIC_USIZE_INIT 已棄用,現在可以直接在 static 中呼叫 const fn(如 AtomicUsize::new)。

TryFrom 與 TryInto


as 轉型在數值放不下時會靜默截斷,300 as u8 得到 44 而不報錯。TryFrom 改為回傳 Result,放得下就是 Ok,放不下就是 Err,呼叫端必須處理失敗。TryInto 是反方向的寫法,由目標型別推斷要轉成什麼。2021 edition 起兩者都在 prelude 裡,本書使用 2024 edition,所以範例不需要 use。
範例:
  1. fn main() {
  2. let big: i64 = 300;
  3. let small: Result<u8, _> = u8::try_from(big);
  4. println!("{:?}", small);
  5. let ok: Result<u8, _> = 200i64.try_into();
  6. println!("{:?}", ok);
  7. match i32::try_from(u64::MAX) {
  8. Ok(v) => println!("轉換成功:{}", v),
  9. Err(e) => println!("轉換失敗:{}", e),
  10. }
  11. }

輸出:
  1. Err(TryFromIntError(PosOverflow))
  2. Ok(200)
  3. 轉換失敗:number too large to fit in target type

iter::successors 與 iter::from_fn


successors 從一個起始值開始,每次用前一個值算出下一個,閉包回傳 None 時結束;範例用 checked_mul 產生 10 的次方,溢位前就會停。from_fn 每次呼叫閉包取得下一個元素,適合包裝「有狀態的產生器」。範例最後用 sort_by_cached_key 做不分大小寫排序,to_lowercase 對每個字串只執行一次。
範例:
  1. use std::iter;
  2. fn main() {
  3. let powers: Vec<u32> = iter::successors(Some(1u32), |&n| n.checked_mul(10))
  4. .take(5)
  5. .collect();
  6. println!("{:?}", powers);
  7. let mut count = 0;
  8. let counter = iter::from_fn(|| {
  9. count += 1;
  10. if count <= 3 { Some(count) } else { None }
  11. });
  12. println!("{:?}", counter.collect::<Vec<_>>());
  13. let mut words = vec!["banana", "Apple", "cherry"];
  14. words.sort_by_cached_key(|w| w.to_lowercase());
  15. println!("{:?}", words);
  16. }

輸出:
  1. [1, 10, 100, 1000, 10000]
  2. [1, 2, 3]
  3. ["Apple", "banana", "cherry"]

本版新增的棄用 API


以下 API 從 Rust 1.34 起標記為棄用(deprecated),新程式不要再使用;說明欄為官方原文。
模組項目官方說明
std::sync::atomicATOMIC_BOOL_INITthe new function is now preferred
std::sync::atomicATOMIC_ISIZE_INITthe new function is now preferred
std::sync::atomicATOMIC_USIZE_INITthe new function is now preferred

修補版本


版本發布日期含安全修補內容(官方原文)
1.34.12019-04-25否Fix false positives for the redundant_closure Clippy lint;Fix false positives for the missing_const_for_fn Clippy lint;Fix Clippy panic when checking some macros
1.34.22019-05-14是Destabilize the Error::type_id function due to a security vulnerability ([CVE-2019-12083])

已知漏洞


影響 1.34.0 的已知漏洞共 19 個;在本版修正的共 1 個;仍影響最新修補版 1.34.2 的共 18 個。官方未公布影響範圍的漏洞只列在修正它的版本,不計入其他版本。

本版已修正


編號元件摘要(官方原文)影響範圍修正於
CVE-2019-12083stdMemory safety vulnerabilities arising from Error::type_id1.34.0 起,早於 1.34.21.34.2

仍影響 1.34.2


編號元件摘要(官方原文)影響範圍修正於
CVE-2026-5222cargoCargo can be coerced to share credentials between registries早於 1.96.01.96.0
CVE-2026-5223cargoCrates in third party registries can override the cached source of other crates早於 1.96.01.96.0
CVE-2024-43402stdstd::process::Command batch files argument escaping could be bypassed with trailing whitespace or periods早於 1.81.01.81.0
CVE-2024-24576stdstd::process::Command did not properly escape arguments of batch files on Windows早於 1.77.21.77.2
CVE-2023-38497cargoCargo not respecting umask when extracting crate archives早於 1.71.11.71.1
CVE-2022-46176cargoCargo did not verify SSH host keys早於 1.66.11.66.1
CVE-2022-36113cargoExtracting malicious crates can corrupt arbitrary files早於 1.64.01.64.0
CVE-2022-36114cargoExtracting malicious crates can fill the file system早於 1.64.01.64.0
CVE-2022-21658stdRace condition in std::fs::remove_dir_all早於 1.58.11.58.1
CVE-2021-42574rustcrustc and bidirectional-override codepoints in source code早於 1.56.11.56.1
CVE-2021-28878stdZip may call __iterator_get_unchecked twice with the same index1.14.0 起,早於 1.52.01.52.0
CVE-2021-28879stdZip can cause buffer overflow when a consumed Zip iterator is used again1.14.0 起,早於 1.52.01.52.0
CVE-2021-28876stdPanic safety issue in Zip specialization1.14.0 起,早於 1.52.01.52.0
CVE-2021-28875stdLogic bug in Read can cause buffer overflow in read_to_end()1.20.0 起,早於 1.50.01.50.0
CVE-2021-28877stdTrustedRandomAccess specialization composes incorrectly for nested iter::Zips1.11.0 起,早於 1.51.01.51.0
CVE-2020-36323stdAPI soundness issue in join() implementation of [Borrow<str>]1.28.0 起,早於 1.52.01.52.0
CVE-2020-36317stdString::retain allows safely creating invalid strings when abusing panic1.26.0 起,早於 1.49.01.49.0
CVE-2021-29922stdImproper Input Validation of octal literals in std::net早於 1.53.01.53.0

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

資料來源