Rust 1.51

最後更新


Rust 1.51 發布於 2021-03-25,目前最新修補版為 1.51.0,已停止支援,請升級到 1.100.1。

版本介紹


Rust 1.51 穩定了 const generics 的最小可用版本(MVP):型別與函式除了可以對型別、生命週期泛型,也能對常數值泛型,最典型的就是陣列長度 [T; N]。Cargo 同時推出新的特性解析器(feature resolver),用 resolver = "2" 開啟。對新手來說,「適用任意長度陣列」的函式從此能自己寫;目前常數參數只能是整數、bool 或 char 型別。

語言變更


  • 函式、特徵與結構體等項目可以用常數值當泛型參數(const generics),例如 struct Grid<const W: usize>,詳見 泛型。

標準庫重點


  • 新增 ptr::addr_of!、ptr::addr_of_mut!,不經過參考直接取得欄位的原始指標,詳見 std::ptr。
  • 新增 array::IntoIter,以值走訪陣列,詳見 陣列。
  • 新增 Peekable::next_if、Peekable::next_if_eq,詳見 std::iter。
  • 新增 slice::fill_with、slice::split_inclusive、slice::strip_prefix、slice::strip_suffix 與 str::split_inclusive,詳見 切片。
  • 新增 Arc::increment_strong_count/decrement_strong_count、Once::call_once_force、Seek::stream_position、panic::panic_any、task::Wake、VecDeque::range。
  • 所有有號整數新增 unsigned_abs;u64 與 u128 實作 From<char>。

Cargo 與工具


  • Cargo.toml 的 [package] 或 [workspace] 可以設定 resolver = "2",避免建置相依、程序式巨集與目標相依的特性被不當合併,詳見 Cargo。
  • 新增 split-debuginfo profile 選項;macOS 上設為 unpacked 可以跳過 dsymutil,大幅加快含除錯資訊的建置。
  • 測試可以用 cargo test -- --include-ignored 一併執行標記 #[ignore] 的測試,詳見 單元測試。
  • intra-doc links 可以連到 slice 等原生型別、關聯項目與帶泛型參數的項目。

相容性注意


  • rustc 不再把可能失敗的除法、取餘數與索引運算提升為 const。
  • WASI 平台改用 wasm32 ABI。
  • 部分平台的官方發行檔最低 glibc 版本提高到 2.31。

const generics


在泛型參數寫 const N: usize,就能讓型別或函式依「數值」產生不同版本。下面的 Grid<3, 2> 在編譯期就確定是 3×2,sum 則能接受任意長度的 i32 陣列。
範例:
  1. struct Grid<const W: usize, const H: usize> {
  2. cells: [[char; W]; H],
  3. }
  4. impl<const W: usize, const H: usize> Grid<W, H> {
  5. fn new(fill: char) -> Self {
  6. Grid { cells: [[fill; W]; H] }
  7. }
  8. fn area(&self) -> usize {
  9. W * H
  10. }
  11. }
  12. fn sum<const N: usize>(values: [i32; N]) -> i32 {
  13. values.iter().sum()
  14. }
  15. fn main() {
  16. let g: Grid<3, 2> = Grid::new('.');
  17. println!("{}", g.area());
  18. for row in &g.cells {
  19. println!("{}", row.iter().collect::<String>());
  20. }
  21. println!("{}", sum([1, 2, 3]));
  22. println!("{}", sum([10; 5]));
  23. }

輸出:
  1. 6
  2. ...
  3. ...
  4. 6
  5. 50

ptr::addr_of!


#[repr(packed)] 結構體的欄位可能沒有對齊,而 Rust 要求參考 & 一定對齊,所以 &h.len 會是未定義行為。addr_of!(h.len) 直接產生原始指標,不經過參考,再用 read_unaligned 讀值。讀取原始指標需要 unsafe,觀念詳見 unsafe。
範例:
  1. use std::ptr;
  2. #[repr(packed)]
  3. struct Header {
  4. tag: u8,
  5. len: u32,
  6. }
  7. fn main() {
  8. let h = Header { tag: 1, len: 512 };
  9. let p = ptr::addr_of!(h.len);
  10. let len = unsafe { p.read_unaligned() };
  11. let tag = h.tag;
  12. println!("tag={tag} len={len}");
  13. }

輸出:
  1. tag=1 len=512

Peekable::next_if


next_if(條件) 只在下一個元素符合條件時才取出,否則留在原地,適合寫簡單的解析器,例如先讀完開頭的數字。next_if_eq(&值) 則是比對相等的版本。
範例:
  1. fn main() {
  2. let mut it = "123abc".chars().peekable();
  3. let mut digits = String::new();
  4. while let Some(c) = it.next_if(|c| c.is_ascii_digit()) {
  5. digits.push(c);
  6. }
  7. let rest: String = it.collect();
  8. println!("{digits} | {rest}");
  9. let mut nums = [1, 1, 2, 3].into_iter().peekable();
  10. let first = nums.next().unwrap();
  11. let mut repeat = 1;
  12. while nums.next_if_eq(&first).is_some() {
  13. repeat += 1;
  14. }
  15. println!("{first} 連續出現 {repeat} 次");
  16. }

輸出:
  1. 123 | abc
  2. 1 連續出現 2 次

注意:這版公告示範的 std::array::IntoIter::new(array) 已於 Rust 1.59 棄用(見 棄用 API),2021 版次起直接對陣列呼叫 into_iter() 或用 for 走訪即可,範例中的 [1, 1, 2, 3].into_iter() 就是這種寫法。

本版新增的棄用 API


以下 API 從 Rust 1.51 起標記為棄用(deprecated),新程式不要再使用;說明欄為官方原文。
模組項目官方說明
std::sync::atomicspin_loop_hintuse hint::spin_loop instead

修補版本


本版沒有修補版本。

已知漏洞


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

仍影響 1.51.0


編號元件摘要(官方原文)影響範圍修正於
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-31162stdDouble free in Vec::from_iter specialization when drop panics1.48.0 起,早於 1.52.01.52.0
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-2020-36323stdAPI soundness issue in join() implementation of [Borrow<str>]1.28.0 起,早於 1.52.01.52.0
CVE-2021-29922stdImproper Input Validation of octal literals in std::net早於 1.53.01.53.0

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

資料來源