From cace4b070f6802ca41bdc726cfc6e9cd617b121c Mon Sep 17 00:00:00 2001 From: "orion GONZALEZ (contractor)" Date: Mon, 4 Mar 2024 22:31:23 +0100 Subject: [PATCH 1/2] doc: Add better explanation --- compiler/rustc_index/src/vec.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_index/src/vec.rs b/compiler/rustc_index/src/vec.rs index d876174e620f4..16a9160fc4e67 100644 --- a/compiler/rustc_index/src/vec.rs +++ b/compiler/rustc_index/src/vec.rs @@ -12,7 +12,19 @@ use std::vec; use crate::{Idx, IndexSlice}; /// An owned contiguous collection of `T`s, indexed by `I` rather than by `usize`. -/// Its purpose is to avoid mixing indexes. +/// +/// Why use this instead of a `Vec`? +/// This enforces the user to index a given IndexVec only with the associated index thus making it +/// impossible to use the wrong index for a given `IndexVec`. +/// +/// ```compile_fail +/// use rustc_index::{Idx, IndexVec}; +/// +/// fn f(vec1: IndexVec, idx1: I1, idx2: I2) { +/// &vec1[idx1]; // Ok +/// &vec1[idx2]; // Error! +/// } +/// ``` /// /// While it's possible to use `u32` or `usize` directly for `I`, /// you almost certainly want to use a [`newtype_index!`]-generated type instead. From beb45df84fd287eb5e83fae100aba82fea0cc639 Mon Sep 17 00:00:00 2001 From: "orion GONZALEZ (contractor)" Date: Tue, 5 Mar 2024 15:27:53 +0100 Subject: [PATCH 2/2] Apply suggestions --- compiler/rustc_index/src/vec.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_index/src/vec.rs b/compiler/rustc_index/src/vec.rs index 16a9160fc4e67..ff460ed85b815 100644 --- a/compiler/rustc_index/src/vec.rs +++ b/compiler/rustc_index/src/vec.rs @@ -13,21 +13,26 @@ use crate::{Idx, IndexSlice}; /// An owned contiguous collection of `T`s, indexed by `I` rather than by `usize`. /// -/// Why use this instead of a `Vec`? -/// This enforces the user to index a given IndexVec only with the associated index thus making it -/// impossible to use the wrong index for a given `IndexVec`. +/// ## Why use this instead of a `Vec`? +/// +/// An `IndexVec` allows element access only via a specific associated index type, meaning that +/// trying to use the wrong index type (possibly accessing an invalid element) will fail at +/// compile time. +/// +/// It also documents what the index is indexing: in a `HashMap` it's not +/// immediately clear what the `usize` means, while a `HashMap` makes it obvious. /// /// ```compile_fail /// use rustc_index::{Idx, IndexVec}; /// /// fn f(vec1: IndexVec, idx1: I1, idx2: I2) { /// &vec1[idx1]; // Ok -/// &vec1[idx2]; // Error! +/// &vec1[idx2]; // Compile error! /// } /// ``` /// /// While it's possible to use `u32` or `usize` directly for `I`, -/// you almost certainly want to use a [`newtype_index!`]-generated type instead. +/// you almost certainly want to use a [`newtype_index!`] generated type instead. /// /// This allows to index the IndexVec with the new index type. ///