#![no_std]
#![forbid(unsafe_code)]
extern crate alloc;
use alloc::vec::Vec;
use core::ops::{Index, IndexMut};
mod ring;
use ring::Ring;
pub struct MappedVec<T> {
vector: Vec<T>,
indices: Ring<usize>,
}
impl<T> MappedVec<T> {
pub fn new() -> MappedVec<T> {
MappedVec {
vector: Vec::new(),
indices: Ring::new(),
}
}
pub fn append(&mut self, v: &mut MappedVec<T>) {
for x in 0..v.indices.len() {
v.indices[x] += self.vector.len();
}
self.indices.append(&mut v.indices);
self.vector.append(&mut v.vector);
*v = MappedVec::new();
}
pub fn len(&self) -> usize {
self.indices.len()
}
pub fn push(&mut self, value: T) {
self.indices.push(self.vector.len());
self.vector.push(value);
}
pub fn swap(&mut self, x: usize, y: usize) {
self.indices.swap(x, y);
}
pub fn pop(&mut self) {
self.indices.pop();
}
pub fn remove(&mut self, index: usize) {
self.indices.remove(index);
}
pub fn insert(&mut self, index: usize, value: T) {
self.vector.push(value);
self.indices.insert(index, self.vector.len() - 1);
}
pub fn reverse(&mut self) {
self.indices.reverse();
}
pub fn rotate(&mut self, offs: isize) {
self.indices.rotate(offs);
}
pub fn clear(&mut self) {
*self = MappedVec::new();
}
pub fn resize_with<F: Fn() -> T>(&mut self, nl: usize, f: F) {
if nl <= self.len() {
for _ in nl..self.len() {
self.indices.pop();
}
} else {
let diff = nl - self.len();
for _ in 0..diff {
self.push(f());
}
}
}
pub fn swap_remove(&mut self, index: usize) {
self.swap(index, self.len() - 1);
self.indices.pop();
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn update_vector(&mut self) {
for (n, x) in self.indices.iter_mut().enumerate() {
self.vector.swap(*x, n);
*x = n;
}
}
pub fn extend<I: Iterator<Item = T> + Clone>(&mut self, iterator: I) {
self.indices.extend(0 + self.vector.len()..iterator.clone().count() + self.vector.len());
self.vector.extend(iterator);
}
pub fn get_mapped(&self) -> Vec<&T> {
let mut output = Vec::new();
for x in 0..self.len() {
output.push(self.index(x));
}
output
}
}
impl<T> Index<usize> for MappedVec<T> {
type Output = T;
fn index(&self, index: usize) -> &T {
self.vector.index(self.indices[index])
}
}
impl<T> IndexMut<usize> for MappedVec<T> {
fn index_mut(&mut self, index: usize) -> &mut T {
self.vector.index_mut(self.indices[index])
}
}
impl<T: Clone> MappedVec<T> {
pub fn extend_from_slice(&mut self, input: &[T]) {
self.indices.extend(self.len()..self.len() + input.len());
self.vector.extend(input.iter().cloned());
}
pub fn to_vec(&self) -> Vec<T> {
let mut output = Vec::new();
for x in 0..self.len() {
output.push(self.index(x).clone());
}
output
}
pub fn resize(&mut self, nl: usize, v: T) {
if nl <= self.len() {
for _ in nl..self.len() {
self.indices.pop();
}
} else {
let diff = nl - self.len();
for _ in 0..diff {
self.push(v.clone());
}
}
}
}