1use std::{
2 marker::PhantomData,
3 ops::{Deref, DerefMut},
4};
5
6pub struct TypedVec<I: TypedVecIndex, T> {
7 data: Vec<T>,
8 phantom: PhantomData<I>,
9}
10
11pub trait TypedVecIndex {
12 fn into_usize(self) -> usize;
13 fn from_usize(v: usize) -> Self;
14}
15
16impl<I: TypedVecIndex, T> Default for TypedVec<I, T> {
17 fn default() -> Self {
18 TypedVec {
19 data: Vec::new(),
20 phantom: PhantomData,
21 }
22 }
23}
24
25impl<I: TypedVecIndex, T> From<Vec<T>> for TypedVec<I, T> {
26 fn from(data: Vec<T>) -> Self {
27 TypedVec {
28 data,
29 phantom: PhantomData,
30 }
31 }
32}
33
34impl<I: TypedVecIndex, T> From<TypedVec<I, T>> for Vec<T> {
35 fn from(data: TypedVec<I, T>) -> Self {
36 data.data
37 }
38}
39
40impl<I: TypedVecIndex, T> TypedVec<I, T> {
41 pub fn new() -> Self {
42 Self::default()
43 }
44
45 pub fn into_data(self) -> Vec<T> {
46 self.data
47 }
48}
49
50impl<I: TypedVecIndex, T> std::ops::Index<I> for TypedVec<I, T> {
51 type Output = T;
52
53 fn index(&self, index: I) -> &Self::Output {
54 &self.data[index.into_usize()]
55 }
56}
57
58impl<I: TypedVecIndex, T> std::ops::IndexMut<I> for TypedVec<I, T> {
59 fn index_mut(&mut self, index: I) -> &mut Self::Output {
60 &mut self.data[index.into_usize()]
61 }
62}
63
64impl<I: TypedVecIndex, T> Deref for TypedVec<I, T> {
65 type Target = Vec<T>;
66
67 fn deref(&self) -> &Self::Target {
68 &self.data
69 }
70}
71
72impl<I: TypedVecIndex, T> DerefMut for TypedVec<I, T> {
73 fn deref_mut(&mut self) -> &mut Self::Target {
74 &mut self.data
75 }
76}
77
78impl<I: TypedVecIndex, T> Extend<T> for TypedVec<I, T> {
79 fn extend<TI: IntoIterator<Item = T>>(&mut self, iter: TI) {
80 self.data.extend(iter);
81 }
82}