Implement swap

This commit is contained in:
Stjepan Glavina 2017-04-03 14:19:39 +02:00
parent 4e5dbaf6a8
commit 5e136e3121
1 changed files with 33 additions and 0 deletions

View File

@ -17,6 +17,7 @@ use std::fmt;
use std::iter;
use std::mem;
use std::ops::{Index, IndexMut};
use std::ptr;
use std::slice;
use std::vec;
@ -398,6 +399,38 @@ impl<T> Arena<T> {
}
}
/// Swaps two objects in the arena.
///
/// The two indices are `a` and `b`.
///
/// # Panics
///
/// Panics if any of the indices is out of bounds or any of the slots is vacant.
///
/// # Examples
///
/// ```
/// use vec_arena::Arena;
///
/// let mut arena = Arena::new();
/// let a = arena.insert(7);
/// let b = arena.insert(8);
///
/// arena.swap(a, b);
/// assert_eq!(arena.get(a), Some(&8));
/// assert_eq!(arena.get(b), Some(&7));
/// ```
#[inline]
pub fn swap(&mut self, a: usize, b: usize) {
unsafe {
let fst = self.get_mut(a).unwrap() as *mut _;
let snd = self.get_mut(b).unwrap() as *mut _;
if a != b {
ptr::swap(fst, snd);
}
}
}
/// Reserves capacity for at least `additional` more objects to be inserted. The arena may
/// reserve more space to avoid frequent reallocations.
///