Skip to main content

rapier2d/utils/
index_mut2.rs

1//! IndexMut2 trait for simultaneously indexing with two distinct indices.
2#[cfg(feature = "alloc")]
3use crate::alloc_prelude::*;
4
5use core::ops::IndexMut;
6
7/// Methods for simultaneously indexing a container with two distinct indices.
8pub trait IndexMut2<I>: IndexMut<I> {
9    /// Gets mutable references to two distinct elements of the container.
10    ///
11    /// Panics if `i == j`.
12    fn index_mut2(&mut self, i: usize, j: usize) -> (&mut Self::Output, &mut Self::Output);
13
14    /// Gets a mutable reference to one element, and immutable reference to a second one.
15    ///
16    /// Panics if `i == j`.
17    #[inline]
18    fn index_mut_const(&mut self, i: usize, j: usize) -> (&mut Self::Output, &Self::Output) {
19        let (a, b) = self.index_mut2(i, j);
20        (a, &*b)
21    }
22}
23
24#[cfg(feature = "alloc")]
25impl<T> IndexMut2<usize> for Vec<T> {
26    #[inline]
27    fn index_mut2(&mut self, i: usize, j: usize) -> (&mut T, &mut T) {
28        self.as_mut_slice().index_mut2(i, j)
29    }
30}
31
32impl<T> IndexMut2<usize> for [T] {
33    #[inline]
34    fn index_mut2(&mut self, i: usize, j: usize) -> (&mut T, &mut T) {
35        assert!(i != j, "Unable to index the same element twice.");
36        let [a, b] = self.get_disjoint_mut([i, j]).expect("Index out of bounds.");
37        (a, b)
38    }
39}