Skip to content

Commit

Permalink
Rollup merge of rust-lang#122015 - dev-ardi:master, r=nnethercote
Browse files Browse the repository at this point in the history
Add better explanation for `rustc_index::IndexVec`

I feel like I didn't do a great job explaining what this does in rust-lang#119800, so this PR tries to give an example of why and how you would use it.

Addresses rust-lang#93792.
  • Loading branch information
matthiaskrgr authored Mar 6, 2024
2 parents 3c05059 + beb45df commit e5503b6
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions compiler/rustc_index/src/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,27 @@ 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`?
///
/// 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<usize, Something>` it's not
/// immediately clear what the `usize` means, while a `HashMap<FieldIdx, Something>` makes it obvious.
///
/// ```compile_fail
/// use rustc_index::{Idx, IndexVec};
///
/// fn f<I1: Idx, I2: Idx>(vec1: IndexVec<I1, u8>, idx1: I1, idx2: I2) {
/// &vec1[idx1]; // Ok
/// &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.
///
Expand Down

0 comments on commit e5503b6

Please sign in to comment.