flow-span 0.1.0-rc.5

Source positions, source files, the identifier interner, and the places in a run.
Documentation
//! A `Vec` whose positions are named by a typed index.

use std::fmt;
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};

use super::idx::Idx;

/// A vector keyed by `I` instead of by `usize`.
///
/// The whole point is [`push`](IndexVec::push): it appends and returns the
/// index it assigned, so a producer names a node at the moment it creates one
/// and never recomputes that name. Indexing panics on an out-of-range index the
/// way `Vec` does, because an index of the wrong domain cannot be constructed
/// in the first place and an index of the right domain that is out of range is
/// a defect in the producer.
///
/// `PhantomData<fn(I)>` keeps `I` out of drop-checking and out of auto-trait
/// inference: an `IndexVec<I, T>` is `Send`/`Sync` exactly when `T` is.
pub struct IndexVec<I: Idx, T> {
    raw: Vec<T>,
    key: PhantomData<fn(I)>,
}

impl<I: Idx, T> IndexVec<I, T> {
    /// Returns an empty vector.
    pub const fn new() -> Self {
        Self {
            raw: Vec::new(),
            key: PhantomData,
        }
    }

    /// Returns an empty vector with room for `capacity` elements.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            raw: Vec::with_capacity(capacity),
            key: PhantomData,
        }
    }

    /// Adopts `raw`, naming its positions with `I`.
    pub const fn from_raw(raw: Vec<T>) -> Self {
        Self {
            raw,
            key: PhantomData,
        }
    }

    /// Returns the underlying storage.
    pub fn into_raw(self) -> Vec<T> {
        self.raw
    }

    /// Appends `value` and returns the index it was assigned.
    pub fn push(&mut self, value: T) -> I {
        let index = self.next_index();
        self.raw.push(value);
        index
    }

    /// Removes and returns the last element.
    pub fn pop(&mut self) -> Option<T> {
        self.raw.pop()
    }

    /// Returns the index the next [`push`](IndexVec::push) will assign.
    pub fn next_index(&self) -> I {
        I::from_usize(self.raw.len())
    }

    /// Returns the number of elements.
    pub fn len(&self) -> usize {
        self.raw.len()
    }

    /// Returns whether there are no elements.
    pub fn is_empty(&self) -> bool {
        self.raw.is_empty()
    }

    /// Returns the element `index` names, or `None` when it is out of range.
    pub fn get(&self, index: I) -> Option<&T> {
        self.raw.get(index.index())
    }

    /// Returns the element `index` names mutably, or `None` when it is out of
    /// range.
    pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
        self.raw.get_mut(index.index())
    }

    /// Returns the elements in position order.
    pub fn iter(&self) -> std::slice::Iter<'_, T> {
        self.raw.iter()
    }

    /// Returns the elements in position order, mutably.
    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
        self.raw.iter_mut()
    }

    /// Returns each element paired with the index naming it.
    pub fn iter_enumerated(&self) -> impl DoubleEndedIterator<Item = (I, &T)> + ExactSizeIterator {
        self.raw
            .iter()
            .enumerate()
            .map(|(position, value)| (I::from_usize(position), value))
    }

    /// Returns each element paired with the index naming it, mutably.
    pub fn iter_enumerated_mut(
        &mut self,
    ) -> impl DoubleEndedIterator<Item = (I, &mut T)> + ExactSizeIterator {
        self.raw
            .iter_mut()
            .enumerate()
            .map(|(position, value)| (I::from_usize(position), value))
    }

    /// Returns every index this vector currently names.
    pub fn indices(&self) -> impl DoubleEndedIterator<Item = I> + ExactSizeIterator {
        (0..self.raw.len()).map(I::from_usize)
    }

    /// Returns the elements as a plain slice.
    pub fn as_slice(&self) -> &[T] {
        &self.raw
    }

    /// Returns the elements as a plain mutable slice.
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        &mut self.raw
    }

    /// Shortens the vector to `len` elements, dropping the rest.
    pub fn truncate(&mut self, len: usize) {
        self.raw.truncate(len);
    }

    /// Drops every element.
    pub fn clear(&mut self) {
        self.raw.clear();
    }
}

impl<I: Idx, T: Clone> IndexVec<I, T> {
    /// Returns a vector of `count` clones of `value`.
    pub fn from_elem_n(value: T, count: usize) -> Self {
        Self::from_raw(vec![value; count])
    }

    /// Grows the vector to `len` elements by cloning `value`.
    pub fn resize(&mut self, len: usize, value: T) {
        self.raw.resize(len, value);
    }
}

impl<I: Idx, T> Default for IndexVec<I, T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<I: Idx, T> Index<I> for IndexVec<I, T> {
    type Output = T;

    fn index(&self, index: I) -> &T {
        &self.raw[index.index()]
    }
}

impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
    fn index_mut(&mut self, index: I) -> &mut T {
        &mut self.raw[index.index()]
    }
}

impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
    fn from_iter<It: IntoIterator<Item = T>>(iter: It) -> Self {
        Self::from_raw(iter.into_iter().collect())
    }
}

impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
    type Item = T;
    type IntoIter = std::vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.raw.into_iter()
    }
}

impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
    type Item = &'a T;
    type IntoIter = std::slice::Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.raw.iter()
    }
}

impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
    type Item = &'a mut T;
    type IntoIter = std::slice::IterMut<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.raw.iter_mut()
    }
}

impl<I: Idx, T: Clone> Clone for IndexVec<I, T> {
    fn clone(&self) -> Self {
        Self::from_raw(self.raw.clone())
    }
}

impl<I: Idx, T: PartialEq> PartialEq for IndexVec<I, T> {
    fn eq(&self, other: &Self) -> bool {
        self.raw == other.raw
    }
}

impl<I: Idx, T: Eq> Eq for IndexVec<I, T> {}

impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(&self.raw).finish()
    }
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::IndexVec;

    use super::super::test_index::{Node, node};

    fn sample() -> IndexVec<Node, &'static str> {
        IndexVec::from_raw(vec!["a", "b", "c"])
    }

    #[test]
    fn push_returns_the_index_it_assigned() {
        let mut nodes = IndexVec::<Node, u8>::new();
        assert_eq!(nodes.next_index(), node(0));

        let first = nodes.push(10);
        let second = nodes.push(20);

        assert_eq!(first, node(0));
        assert_eq!(second, node(1));
        assert_eq!(nodes[first], 10);
        assert_eq!(nodes[second], 20);
        assert_eq!(nodes.next_index(), node(2));
        assert_eq!(nodes.len(), 2);
        assert!(!nodes.is_empty());
    }

    #[test]
    fn an_empty_vector_reports_itself_empty() {
        let empty = IndexVec::<Node, u8>::default();
        assert!(empty.is_empty());
        assert_eq!(empty.len(), 0);
        assert_eq!(empty.indices().count(), 0);

        let with_room = IndexVec::<Node, u8>::with_capacity(8);
        assert!(with_room.is_empty());
        assert_eq!(with_room.len(), 0);
        assert!(with_room.into_raw().capacity() >= 8);
    }

    #[test]
    fn indexing_reads_and_writes_the_named_position() {
        let mut nodes = sample();
        assert_eq!(nodes[node(1)], "b");

        nodes[node(1)] = "B";
        assert_eq!(nodes[node(1)], "B");

        *nodes.get_mut(node(2)).expect("in range") = "C";
        assert_eq!(nodes.get(node(2)), Some(&"C"));
    }

    #[test]
    fn an_out_of_range_index_reads_as_absent() {
        let mut nodes = sample();
        assert_eq!(nodes.get(node(3)), None);
        assert_eq!(nodes.get_mut(node(3)), None);
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn indexing_past_the_end_is_a_defect() {
        let _ = sample()[node(3)];
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn indexing_past_the_end_mutably_is_a_defect() {
        let mut nodes = sample();
        nodes[node(3)] = "d";
    }

    #[test]
    fn iteration_walks_positions_in_order() {
        let mut nodes = sample();

        assert_eq!(nodes.iter().copied().collect::<Vec<_>>(), ["a", "b", "c"]);
        assert_eq!(
            nodes
                .iter_enumerated()
                .map(|(index, value)| (index, *value))
                .collect::<Vec<_>>(),
            [(node(0), "a"), (node(1), "b"), (node(2), "c"),],
        );
        assert_eq!(
            nodes.indices().collect::<Vec<_>>(),
            [node(0), node(1), node(2)],
        );

        nodes.iter_mut().for_each(|value| *value = "x");
        assert_eq!(nodes.as_slice(), ["x", "x", "x"]);

        for (index, value) in nodes.iter_enumerated_mut() {
            if index == node(0) {
                *value = "y";
            }
        }
        assert_eq!(nodes.as_slice(), ["y", "x", "x"]);
        assert_eq!(nodes.as_mut_slice().len(), 3);
    }

    #[test]
    fn iteration_is_double_ended_and_sized() {
        let nodes = sample();
        assert_eq!(nodes.iter_enumerated().len(), 3);
        assert_eq!(
            nodes.iter_enumerated().next_back().map(|(_, v)| *v),
            Some("c")
        );
        assert_eq!(nodes.indices().len(), 3);
        assert_eq!(nodes.indices().next_back(), Some(node(2)));

        let mut nodes = sample();
        assert_eq!(nodes.iter_enumerated_mut().len(), 3);
        assert_eq!(
            nodes.iter_enumerated_mut().next_back().map(|(_, v)| *v),
            Some("c")
        );
    }

    #[test]
    fn a_vector_converts_to_and_from_plain_storage() {
        let nodes: IndexVec<Node, u8> = [1_u8, 2, 3].into_iter().collect();
        assert_eq!(nodes.clone().into_raw(), vec![1, 2, 3]);
        assert_eq!(nodes.into_iter().collect::<Vec<_>>(), vec![1, 2, 3]);
    }

    #[test]
    fn borrowed_iteration_reaches_both_reference_forms() {
        let mut nodes = sample();
        assert_eq!((&nodes).into_iter().count(), 3);

        let lengths: Vec<usize> = (&mut nodes).into_iter().map(|value| value.len()).collect();
        assert_eq!(lengths, [1, 1, 1]);
    }

    #[test]
    fn cloning_repeats_a_value_and_resizing_extends_it() {
        let mut nodes = IndexVec::<Node, u8>::from_elem_n(7, 2);
        assert_eq!(nodes.as_slice(), [7, 7]);

        nodes.resize(4, 9);
        assert_eq!(nodes.as_slice(), [7, 7, 9, 9]);
    }

    #[test]
    fn shortening_drops_the_tail() {
        let mut nodes = sample();
        assert_eq!(nodes.pop(), Some("c"));

        nodes.truncate(1);
        assert_eq!(nodes.as_slice(), ["a"]);

        nodes.clear();
        assert!(nodes.is_empty());
        assert_eq!(nodes.pop(), None);
    }

    #[test]
    fn equality_and_debug_read_through_to_the_elements() {
        assert_eq!(sample(), sample());
        assert_ne!(sample(), IndexVec::<Node, &str>::new());
        assert_eq!(format!("{:?}", sample()), r#"["a", "b", "c"]"#);
    }
}