linnet/half_edge/
typed_vec.rs

1use std::hash::Hash;
2pub trait IndexLike:
3    Copy + PartialEq + Eq + PartialOrd + Ord + Hash + From<usize> + Into<usize>
4{
5}
6
7impl<ID: Copy + PartialEq + Eq + PartialOrd + Ord + Hash + From<usize> + Into<usize>> IndexLike
8    for ID
9{
10}
11
12#[macro_export]
13macro_rules! define_indexed_vec {
14    (
15        $(#[$idx_meta:meta])*
16        $idx_vis:vis struct $Idx:ident ;
17
18        $(#[$vec_meta:meta])*
19        $vec_vis:vis struct $Vec:ident ;
20    ) => {
21        /* ——————————————————— index new‑type ——————————————————— */
22
23        $(#[$idx_meta])*
24        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
25        #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26        #[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
27        $idx_vis struct $Idx(pub usize);
28
29        impl ::std::convert::From<usize> for $Idx {
30            fn from(value: usize) -> Self {
31                $Idx(value)
32            }
33        }
34
35
36
37        impl ::std::ops::Add<$Idx> for $Idx {
38            type Output = $Idx;
39
40            fn add(self, other: $Idx) -> Self::Output {
41                $Idx(self.0 + other.0)
42            }
43        }
44
45        impl ::std::ops::Sub<$Idx> for $Idx {
46            type Output = $Idx;
47
48            fn sub(self, other: $Idx) -> Self::Output {
49                $Idx(self.0 - other.0)
50            }
51        }
52
53        impl ::std::ops::AddAssign<$Idx> for $Idx {
54            fn add_assign(&mut self, other: $Idx) {
55                self.0 += other.0;
56            }
57        }
58
59        impl ::std::ops::SubAssign<$Idx> for $Idx {
60            fn sub_assign(&mut self, other: $Idx) {
61                self.0 -= other.0;
62            }
63        }
64
65        impl ::std::convert::From<$Idx> for usize {
66            fn from(value: $Idx) -> Self {
67                value.0
68            }
69        }
70
71
72
73
74
75        /* ——————————————————— vector new‑type ——————————————————— */
76
77        $(#[$vec_meta])*
78        #[derive(Clone, Debug, Default, Hash, PartialEq, Eq,PartialOrd,Ord)]
79        #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
80        #[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
81        $vec_vis struct $Vec<T>(::std::vec::Vec<T>);
82
83        /* --- Restricted indexing -------------------------------------------------- */
84
85        impl<T> ::std::ops::Index<$Idx> for $Vec<T> {
86            type Output = T;
87            #[inline] fn index(&self, i: $Idx) -> &Self::Output { &self.0[i.0] }
88        }
89        impl<T> ::std::ops::IndexMut<$Idx> for $Vec<T> {
90            #[inline] fn index_mut(&mut self, i: $Idx) -> &mut Self::Output { &mut self.0[i.0] }
91        }
92
93        impl<T>  ::std::convert::AsMut<[T]> for $Vec<T>{
94            fn as_mut(&mut self)->&mut [T]{
95                self.0.as_mut()
96            }
97        }
98
99        impl<T> $crate::half_edge::swap::Swap<$Idx> for $Vec<T>{
100            fn swap(&mut self, a: $Idx, b: $Idx) {
101                self.0.swap(a.0, b.0);
102            }
103
104            // type Item = T;
105
106            // fn filter(&self, id: &$Idx, filter: &impl Fn(&$Idx, &Self::Item) -> bool) -> bool {
107            //     filter(id,&self[*id])
108            // }
109
110            fn len(&self) -> $Idx {
111                $Idx(self.0.len())
112            }
113            #[inline] fn is_zero_length(&self) -> bool { self.0.is_empty() }
114
115        }
116
117        /* --- Delegated Vec<T> API ------------------------------------------------- */
118
119        ::paste::paste! {
120                    #[derive(Clone)]
121                    $vec_vis struct [<$Vec Iter>]<'a, T>(std::iter::Map<
122                        std::iter::Enumerate<std::slice::Iter<'a, T>>,
123                        fn((usize, &T)) -> ($Idx, &T),
124                    >);
125                    impl<'a, T> ::std::iter::Iterator for [<$Vec Iter>]<'a, T> {
126                        type Item = ($Idx, &'a T);
127                        #[inline] fn next(&mut self) -> Option<Self::Item> { self.0.next() }
128                        #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
129                    }
130                    impl<'a, T> ::std::iter::DoubleEndedIterator for [<$Vec Iter>]<'a, T> {
131                        #[inline] fn next_back(&mut self) -> Option<Self::Item> { self.0.next_back() }
132                    }
133                    impl<'a, T> ::std::iter::ExactSizeIterator for [<$Vec Iter>]<'a, T> {}
134                    impl<'a, T> ::std::iter::FusedIterator     for [<$Vec Iter>]<'a, T> {}
135
136
137                    impl<'a, T> ::std::iter::IntoIterator for &'a $Vec<T> {
138                        type Item = ($Idx, &'a T);
139                        type IntoIter = [<$Vec Iter>]<'a, T>;
140                        fn into_iter(self) -> Self::IntoIter {
141                            [<$Vec Iter>](self.0.iter().enumerate().map(|(u, t)| ($Idx(u), t)))
142                        }
143                    }
144
145                    $vec_vis struct [<$Vec IterMut>]<'a, T>(::std::iter::Map<
146                        std::iter::Enumerate<std::slice::IterMut<'a, T>>,
147                        fn((usize, &mut T)) -> ($Idx, &mut T),
148                    >);
149                    impl<'a, T> ::std::iter::Iterator for [<$Vec IterMut>]<'a, T> {
150                        type Item = ($Idx, &'a mut T);
151                        #[inline] fn next(&mut self) -> Option<Self::Item> { self.0.next() }
152                        #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
153                    }
154                    impl<'a, T> ::std::iter::DoubleEndedIterator for [<$Vec IterMut>]<'a, T> {
155                        #[inline] fn next_back(&mut self) -> Option<Self::Item> { self.0.next_back() }
156                    }
157                    impl<'a, T> ::std::iter::ExactSizeIterator for [<$Vec IterMut>]<'a, T> {}
158                    impl<'a, T> ::std::iter::FusedIterator     for [<$Vec IterMut>]<'a, T> {}
159
160                    impl<'a, T> ::std::iter::IntoIterator for &'a mut $Vec<T> {
161                        type Item = ($Idx, &'a mut T);
162                        type IntoIter = [<$Vec IterMut>]<'a, T>;
163                        fn into_iter(self) -> Self::IntoIter {
164                            [<$Vec IterMut>](self.0.iter_mut().enumerate().map(|(u, t)| ($Idx(u), t)))
165                        }
166                    }
167
168
169
170                    $vec_vis struct [<$Vec IntoIter>]<T>(::std::iter::Map<std::iter::Enumerate<std::vec::IntoIter<T>>, fn((usize, T)) -> ($Idx, T)>);
171                    impl<T> ::std::iter::Iterator for [<$Vec IntoIter>]<T> {
172                        type Item = ($Idx,T);
173                        #[inline] fn next(&mut self) -> Option<Self::Item> { self.0.next() }
174                        #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
175                    }
176                    impl<T> ::std::iter::DoubleEndedIterator for [<$Vec IntoIter>]<T> {
177                        #[inline] fn next_back(&mut self) -> Option<Self::Item> { self.0.next_back() }
178                    }
179                    impl<T> ::std::iter::ExactSizeIterator for [<$Vec IntoIter>]<T> {}
180                    impl<T> ::std::iter::FusedIterator     for [<$Vec IntoIter>]<T> {}
181
182                    impl<T> ::std::iter::IntoIterator for $Vec<T> {
183                        type Item = ($Idx,T);
184                        type IntoIter =  [<$Vec IntoIter>]<T>;
185                        #[inline] fn into_iter(self) -> Self::IntoIter { [<$Vec IntoIter>](self.0.into_iter().enumerate().map(|(u, t)| ($Idx(u), t))) }
186                    }
187
188
189                    impl<T> $Vec<T>{
190                        #[inline] pub fn iter<'a>(&'a self) -> [<$Vec Iter>]<'a, T> { self.into_iter() }
191                        #[inline] pub fn iter_mut<'a>(&'a mut self) -> [<$Vec IterMut>]<'a, T> { self.into_iter() }
192
193                    }
194
195        }
196
197        impl<T> $Vec<T> {
198
199            pub fn write_display<W: ::std::fmt::Write>(&self, writer: &mut W,formater:impl Fn(&T)->String) -> ::std::fmt::Result {
200                writer.write_str("[")?;
201
202                for (i,item) in self {
203                    if i.0 != 0{
204                        write!(writer, ", ")?;
205                    }
206                    write!(writer, "{}", formater(item))?;
207                }
208                writer.write_str("]")?;
209                Ok(())
210            }
211
212            pub fn display_string(&self,formatter:impl Fn(&T)->String) -> String {
213                let mut result = String::new();
214                self.write_display(&mut result, formatter).unwrap();
215                result
216            }
217
218
219
220            /* construction */
221            #[inline] pub fn new() -> Self { Self(::std::vec::Vec::new()) }
222            #[inline] pub fn with_capacity(c: usize) -> Self { Self(::std::vec::Vec::with_capacity(c)) }
223
224            /* capacity */
225            // #[inline] pub fn len(&self) -> usize { self.0.len() }
226
227            #[inline] pub fn capacity(&self) -> usize { self.0.capacity() }
228            #[inline] pub fn reserve(&mut self, n: usize) { self.0.reserve(n) }
229            #[inline] pub fn reserve_exact(&mut self, n: usize) { self.0.reserve_exact(n) }
230            #[inline] pub fn shrink_to_fit(&mut self) { self.0.shrink_to_fit() }
231
232            /* push / pop */
233            #[inline] pub fn push(&mut self, value: T) { self.0.push(value) }
234            #[inline] pub fn pop(&mut self) -> Option<T> { self.0.pop() }
235
236
237            #[inline] pub fn swap(&mut self, a: $Idx, b: $Idx) {
238                self.0.swap(a.0, b.0);
239            }
240
241            #[inline] pub fn split_off(&mut self, at: $Idx) -> Self {
242                Self(self.0.split_off(at.0))
243            }
244
245            /* insertion / removal with the index new‑type */
246            #[inline] pub fn insert(&mut self, idx: $Idx, v: T) { self.0.insert(idx.0, v) }
247            #[inline] pub fn remove(&mut self, idx: $Idx) -> T { self.0.remove(idx.0) }
248            #[inline] pub fn swap_remove(&mut self, idx: $Idx) -> T { self.0.swap_remove(idx.0) }
249
250            /* get APIs using the index new‑type */
251            #[inline] pub fn get(&self, idx: $Idx) -> Option<&T> { self.0.get(idx.0) }
252            #[inline] pub fn get_mut(&mut self, idx: $Idx) -> Option<&mut T> { self.0.get_mut(idx.0) }
253
254            /* iteration */
255
256            /* miscellaneous */
257            #[inline] pub fn clear(&mut self) { self.0.clear() }
258            #[inline] pub fn truncate(&mut self, len: usize) { self.0.truncate(len) }
259
260            /* fall‑back escape hatch – intentionally *not* public: */
261            #[inline] pub fn raw(&self) -> &::std::vec::Vec<T> { &self.0 }
262        }
263
264        /* --- standard trait impls ------------------------------------------------- */
265
266        impl<T> ::std::iter::FromIterator<($Idx,T)> for $Vec<T> {
267            #[inline] fn from_iter<I: ::std::iter::IntoIterator<Item = ($Idx,T)>>(it: I) -> Self {
268                Self(::std::vec::Vec::from_iter(it.into_iter().map(|(_, val)|  val)))
269            }
270        }impl<T> ::std::iter::FromIterator<T> for $Vec<T> {
271            #[inline] fn from_iter<I: ::std::iter::IntoIterator<Item = T>>(it: I) -> Self {
272                Self(::std::vec::Vec::from_iter(it))
273            }
274        }
275
276        impl<T> ::std::convert::AsRef<[T]> for $Vec<T> {
277            #[inline] fn as_ref(&self) -> &[T] { &self.0 }
278        }
279
280
281
282        impl<T> ::std::iter::Extend<($Idx,T)> for $Vec<T> {
283            #[inline] fn extend<I: ::std::iter::IntoIterator<Item = ($Idx,T)>>(&mut self, it: I) {
284                self.0.extend(it.into_iter().map(|(_, val)|  val));
285            }
286        }
287
288
289        impl<T> ::std::convert::From<::std::vec::Vec<T>> for $Vec<T> {
290            #[inline] fn from(v: ::std::vec::Vec<T>) -> Self { Self(v) }
291        }
292
293
294
295
296        /// Permutation constructors
297
298        impl $Vec<Option<$Idx>>{
299            pub fn fill_in(&mut self,contained:impl Fn(&$Idx)->bool){
300                let mut new_shifted = $Idx(0);
301
302                for (_, new_e) in self {
303                    if new_e.is_none() {
304                        while contained(&new_shifted) {
305                            new_shifted.0 += 1;
306                        }
307                        *new_e = Some(new_shifted);
308                        new_shifted.0 += 1;
309                    }
310                }
311            }
312        }
313
314        impl ::std::convert::TryFrom<$Vec<Option<$Idx>>> for $Vec<$Idx>{
315            type Error = ();
316            fn try_from(vec: $Vec<Option<$Idx>>) -> Result<Self, Self::Error> {
317                vec.into_iter().map(|(i,e)| e.ok_or(()).map(|e|(i,e))).collect()
318            }
319        }
320
321        impl ::std::convert::TryFrom<$Vec<Option<$Idx>>> for $crate::permutation::Permutation{
322            type Error = ();
323            fn try_from(vec: $Vec<Option<$Idx>>) -> Result<Self, Self::Error> {
324                let new_vec:Vec<usize> = vec.into_iter().map(|(i,e)| e.ok_or(()).map(|e|(i,e))).collect::<Result<$Vec<$Idx>, ()>>()?.into_iter().map(|(_,x)| usize::from(x)).collect();
325
326                Ok($crate::permutation::Permutation::from_map(new_vec))
327            }
328        }
329    };
330}