Rust 1.27

最後更新


Rust 1.27 發布於 2018-06-21,目前最新修補版為 1.27.2,已停止支援,請升級到 1.100.1。

版本介紹


Rust 1.27 引入 dyn Trait 語法:特徵物件從 Box<Foo> 改寫成 Box<dyn Foo>,一眼就能和一般結構、impl Trait 區分。同一版穩定了 x86/x86_64 的 SIMD 基礎設施 std::arch,#[must_use] 也能標在函式上,Clone::clone、Iterator::collect 等結果沒用到時會發出警告。官方文件站的所有書籍都可以搜尋,並新增說明編譯器用法的 The rustc Book。

語言變更


  • 新增 dyn Trait 語法,與舊的裸特徵寫法等價,詳見 特徵物件。
  • #[must_use] 可以標在函式上,回傳值沒被使用時發出警告,詳見 函式。
  • 泛型參數(型別與生命週期)上可以加屬性;proc 不再是保留字。

標準庫重點


  • SIMD 穩定:新增 std::arch::x86、std::arch::x86_64、is_x86_feature_detected! 巨集與 #[target_feature(enable = "...")] 屬性。
  • 新增 Option::filter,詳見 Option。
  • 新增 Iterator::try_fold、Iterator::try_for_each,以及 DoubleEndedIterator::rfind、rfold、try_rfold,詳見 std::iter。
  • 新增 Duration::from_micros、from_nanos、subsec_micros、subsec_millis,詳見 std::time。
  • 新增 HashMap::remove_entry、String::replace_range、slice::rsplit、slice::swap_with_slice、hint::unreachable_unchecked。
  • str::replace、Clone::clone、Iterator::collect、ToOwned::to_owned 加上 #[must_use]。

Cargo 與工具


  • 新增 --target-dir,指定編譯產物的輸出目錄,詳見 Cargo。
  • Cargo.toml 新增 autobins、autoexamples、autotests、autobenches,控制是否自動偵測目標,詳見 Cargo.toml。
  • cargo metadata 多輸出 authors、categories、keywords、readme、repository 與 metadata 表;Cargo 會快取編譯器資訊。

相容性注意


  • 原子型別的 Debug 只印內部值,例如 AtomicBool::new(true) 印成 true。
  • repr(align(N)) 的上限改為 2²⁹。
  • Error::description() 改為軟性棄用,實作 Error 時不必再提供,詳見 自訂錯誤。
  • 不能再直接從 core 呼叫 CharExt、StrExt 的方法。

dyn Trait


以前 Box<Foo> 裡的 Foo 可能是結構,也可能是特徵,讀程式碼時要先查定義才知道。dyn 明確標示「這是特徵物件,透過 vtable 在執行期決定呼叫哪個實作」。需要在同一個集合放不同型別,或依條件回傳不同型別時,就用 Box<dyn Trait> 或 &dyn Trait。
範例:
  1. trait Notifier {
  2. fn send(&self, msg: &str) -> String;
  3. }
  4. struct Email(&'static str);
  5. struct Sms(u32);
  6. impl Notifier for Email {
  7. fn send(&self, msg: &str) -> String {
  8. format!("寄信給 {}:{}", self.0, msg)
  9. }
  10. }
  11. impl Notifier for Sms {
  12. fn send(&self, msg: &str) -> String {
  13. format!("傳簡訊到 {}:{}", self.0, msg)
  14. }
  15. }
  16. fn broadcast(targets: &[Box<dyn Notifier>], msg: &str) {
  17. for t in targets {
  18. println!("{}", t.send(msg));
  19. }
  20. }
  21. fn pick(use_email: bool) -> Box<dyn Notifier> {
  22. if use_email {
  23. Box::new(Email("ops@example.com"))
  24. } else {
  25. Box::new(Sms(912345678))
  26. }
  27. }
  28. fn main() {
  29. let targets = vec![pick(true), pick(false)];
  30. broadcast(&targets, "伺服器重新啟動");
  31. let single: &dyn Notifier = &Sms(987654321);
  32. println!("{}", single.send("測試"));
  33. }

輸出:
  1. 寄信給 ops@example.com:伺服器重新啟動
  2. 傳簡訊到 912345678:伺服器重新啟動
  3. 傳簡訊到 987654321:測試

注意:1.27 當時省略 dyn 只是預設不警告的 lint;在較新的 edition 中省略 dyn 已是編譯錯誤,詳見 Edition 演進。

Option::filter 與 Iterator::try_fold


Option::filter 在值存在且符合條件時保留 Some,否則變成 None。try_fold 像 fold 一樣累積結果,但閉包回傳 Option 或 Result,遇到 None/Err 就立刻停止;try_for_each 則是會提早停止的 for_each。
範例:
  1. fn main() {
  2. let ages = [Some(20), Some(15), None];
  3. for age in ages {
  4. println!("{:?} -> {:?}", age, age.filter(|a| *a >= 18));
  5. }
  6. let nums = [100u8, 80, 90];
  7. let total = nums.iter().try_fold(0u8, |acc, &n| acc.checked_add(n));
  8. println!("u8 加總:{:?}", total);
  9. let small = [10u8, 20, 30];
  10. println!("u8 加總:{:?}", small.iter().try_fold(0u8, |acc, &n| acc.checked_add(n)));
  11. let r = ["1", "2", "x", "4"].iter().try_for_each(|s| {
  12. let n: i32 = s.parse().map_err(|_| format!("無法解析 {:?}", s))?;
  13. println!("處理 {}", n);
  14. Ok::<(), String>(())
  15. });
  16. println!("{:?}", r);
  17. println!("{:?}", [1, 2, 3, 4].iter().rfind(|&&x| x % 2 == 1));
  18. }

輸出:
  1. Some(20) -> Some(20)
  2. Some(15) -> None
  3. None -> None
  4. u8 加總:None
  5. u8 加總:Some(60)
  6. 處理 1
  7. 處理 2
  8. Err("無法解析 \"x\"")
  9. Some(3)

注意:100 + 80 + 90 等於 270,超過 u8 上限 255,加到第三個數時 checked_add 回傳 None,try_fold 就此停止;"4" 也因為前面的錯誤而沒有被處理。

本版新增的棄用 API


本版沒有新增棄用 API。

修補版本


版本發布日期含安全修補內容(官方原文)
1.27.12018-07-10是rustdoc would execute plugins in the /tmp/rustdoc/plugins directory when running, which enabled executing code as some other user on a given machine. This release fixes that vulnerability; you can read more about this on the blog. The associated CVE is [CVE-2018-1000622]. Thank you to Red Hat for responsibly disclosing this vulnerability to us.;The borrow checker was fixed to avoid an additional potential unsoundness when using match ergonomics: #51415, #49534.
1.27.22018-07-20否The borrow checker was fixed to avoid potential unsoundness when using match ergonomics: #52213.

已知漏洞


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

本版已修正


編號元件摘要(官方原文)影響範圍修正於
CVE-2018-1000622rustdocUncontrolled search path element vulnerability in rustdoc plugins早於 1.27.11.27.1

仍影響 1.27.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-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
CVE-2018-1000810stdBuffer overflow vulnerability in str::repeat()1.26.0 起,早於 1.29.11.29.1
CVE-2019-1010299stdvec_deque::Iter has unsound Debug implementation1.18.0 起,早於 1.30.01.30.0
CVE-2018-25008stdInsufficient synchronization in Arc::get_mut1.3.0 起,早於 1.29.01.29.0

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

資料來源