use iceoryx2_bb_memory::heap_allocator::HeapAllocator;
use crate::prelude::*;
pub trait VectorExtension<T> {
fn swap_remove(&mut self, index: usize) -> Option<T>;
fn new_in_global(capacity: usize) -> Self;
}
impl<T> VectorExtension<T> for Vec<T> {
fn swap_remove(&mut self, index: usize) -> Option<T> {
let length = self.len();
if index >= length {
return None;
} else if index < length - 1 {
self.swap(index, length - 1);
}
self.pop()
}
fn new_in_global(capacity: usize) -> Self
where
Self: Sized,
{
let capacity = core::cmp::max(capacity, 1); Vec::new(HeapAllocator::global(), capacity).expect("Failed to create Vec with specified capacity")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::containers::Vec;
#[test]
fn swap_remove_mid_element() {
const VEC_SIZE: usize = 10;
let mut vec = Vec::new_in_global(VEC_SIZE);
for i in 0..VEC_SIZE {
vec.push(i).unwrap();
}
assert_eq!(vec.swap_remove(5).unwrap(), 5);
assert_eq!(vec[4], 4); assert_eq!(vec[5], 9); assert_eq!(vec[6], 6); assert_eq!(vec.len(), VEC_SIZE - 1); }
#[test]
fn swap_remove_first_element() {
const VEC_SIZE: usize = 10;
let mut vec = Vec::new_in_global(VEC_SIZE);
for i in 0..VEC_SIZE {
vec.push(i).unwrap();
}
assert_eq!(vec.swap_remove(0).unwrap(), 0);
assert_eq!(vec[0], 9);
assert_eq!(vec[1], 1);
assert_eq!(vec.len(), VEC_SIZE - 1);
}
#[test]
fn swap_remove_last_element() {
const VEC_SIZE: usize = 10;
let mut vec = Vec::new_in_global(VEC_SIZE);
for i in 0..VEC_SIZE {
vec.push(i).unwrap();
}
assert_eq!(vec.swap_remove(VEC_SIZE - 1).unwrap(), 9);
assert_eq!(vec[0], 0);
assert_eq!(vec[8], 8);
assert_eq!(vec.len(), VEC_SIZE - 1);
}
#[test]
fn swap_remove_vec_with_one_element() {
let mut vec = Vec::new_in_global(1);
vec.push(100).unwrap();
assert_eq!(vec.swap_remove(0).unwrap(), 100);
assert_eq!(vec.len(), 0);
}
#[test]
fn swap_remove_out_of_bounds() {
const VEC_SIZE: usize = 10;
let mut vec = Vec::new_in_global(VEC_SIZE);
for i in 0..VEC_SIZE {
vec.push(i).unwrap();
}
assert_eq!(vec.swap_remove(VEC_SIZE), None); }
#[test]
fn remove_mid_element_and_drop() {
struct TestData {
data: usize,
}
impl Drop for TestData {
fn drop(&mut self) {
increment_counter(self.data);
}
}
static mut DROPPED_DATA: usize = 0;
static mut DROP_COUNTER: usize = 0;
fn increment_counter(data: usize) {
unsafe {
DROPPED_DATA = data;
DROP_COUNTER += 1;
}
}
const VEC_SIZE: usize = 10;
let mut vec = Vec::new_in_global(VEC_SIZE);
for i in 0..VEC_SIZE {
vec.push(TestData { data: i }).unwrap();
}
vec.remove(5);
assert_eq!(unsafe { DROP_COUNTER }, 1); assert_eq!(unsafe { DROPPED_DATA }, 5); }
}