1use index_vec::{Idx, IdxSliceIndex, IndexVec};
11use serde::{Deserialize, Serialize, Serializer};
12use std::{
13 iter::{FromIterator, IntoIterator},
14 mem,
15 ops::{ControlFlow, Deref, Index, IndexMut},
16};
17
18use derive_generic_visitor::*;
19
20#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub struct Vector<I, T>
24where
25 I: Idx,
26{
27 vector: IndexVec<I, Option<T>>,
28 elem_count: usize,
30}
31
32impl<I: std::fmt::Debug, T: std::fmt::Debug> std::fmt::Debug for Vector<I, T>
33where
34 I: Idx,
35{
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 <IndexVec<_, _> as std::fmt::Debug>::fmt(&self.vector, f)
38 }
39}
40
41pub struct ReservedSlot<I: Idx>(I);
42
43impl<I, T> Vector<I, T>
44where
45 I: Idx,
46{
47 pub fn new() -> Self {
48 Vector {
49 vector: IndexVec::new(),
50 elem_count: 0,
51 }
52 }
53
54 pub fn with_capacity(capacity: usize) -> Self {
55 Vector {
56 vector: IndexVec::with_capacity(capacity),
57 elem_count: 0,
58 }
59 }
60
61 pub fn get(&self, i: I) -> Option<&T> {
62 self.vector.get(i).map(Option::as_ref).flatten()
63 }
64
65 pub fn get_mut(&mut self, i: I) -> Option<&mut T> {
66 self.vector.get_mut(i).map(Option::as_mut).flatten()
67 }
68
69 pub fn is_empty(&self) -> bool {
70 self.elem_count == 0
71 }
72
73 pub fn elem_count(&self) -> usize {
75 self.elem_count
76 }
77
78 pub fn slot_count(&self) -> usize {
80 self.vector.len()
81 }
82
83 pub fn next_id(&self) -> I {
85 self.vector.next_idx()
86 }
87
88 pub fn reserve_slot(&mut self) -> I {
90 self.vector.push(None)
92 }
93
94 pub fn set_slot(&mut self, id: I, x: T) {
96 assert!(self.vector[id].is_none());
97 self.vector[id] = Some(x);
98 self.elem_count += 1;
99 }
100
101 pub fn remove(&mut self, id: I) -> Option<T> {
103 if self.vector[id].is_some() {
104 self.elem_count -= 1;
105 }
106 self.vector[id].take()
107 }
108
109 pub fn remove_and_shift_ids(&mut self, id: I) -> Option<T> {
111 if id.index() >= self.slot_count() {
112 return None;
113 }
114 if self.vector[id].is_some() {
115 self.elem_count -= 1;
116 }
117 self.vector.remove(id)
118 }
119
120 pub fn pop(&mut self) -> Option<T> {
122 if self.vector.last().is_some() {
123 self.elem_count -= 1;
124 }
125 self.vector.pop().flatten()
126 }
127
128 pub fn push(&mut self, x: T) -> I {
129 self.elem_count += 1;
130 self.vector.push(Some(x))
131 }
132
133 pub fn push_with(&mut self, f: impl FnOnce(I) -> T) -> I {
134 let id = self.reserve_slot();
135 let x = f(id);
136 self.set_slot(id, x);
137 id
138 }
139
140 pub fn push_all<It>(&mut self, it: It) -> impl Iterator<Item = I> + use<'_, I, T, It>
141 where
142 It: IntoIterator<Item = T>,
143 {
144 it.into_iter().map(move |x| self.push(x))
145 }
146
147 pub fn extend<It>(&mut self, it: It)
148 where
149 It: IntoIterator<Item = T>,
150 {
151 self.push_all(it).for_each(|_| ())
152 }
153
154 pub fn extend_from_slice(&mut self, other: &Self)
155 where
156 T: Clone,
157 {
158 self.vector.extend_from_slice(&other.vector);
159 self.elem_count += other.elem_count;
160 }
161
162 pub fn insert_and_shift_ids(&mut self, id: I, x: T) {
164 self.elem_count += 1;
165 self.vector.insert(id, Some(x))
166 }
167
168 pub fn get_or_extend_and_insert(&mut self, id: I, f: impl FnOnce() -> T) -> &mut T {
172 if id.index() >= self.vector.len() {
173 self.vector.resize_with(id.index() + 1, || None);
174 }
175 self.vector[id].get_or_insert_with(f)
176 }
177
178 pub fn map<U>(self, mut f: impl FnMut(T) -> U) -> Vector<I, U> {
180 Vector {
181 vector: self
182 .vector
183 .into_iter()
184 .map(|x_opt| x_opt.map(&mut f))
185 .collect(),
186 elem_count: self.elem_count,
187 }
188 }
189
190 pub fn map_ref<'a, U>(&'a self, mut f: impl FnMut(&'a T) -> U) -> Vector<I, U> {
192 Vector {
193 vector: self
194 .vector
195 .iter()
196 .map(|x_opt| x_opt.as_ref().map(&mut f))
197 .collect(),
198 elem_count: self.elem_count,
199 }
200 }
201
202 pub fn map_ref_mut<'a, U>(&'a mut self, mut f: impl FnMut(&'a mut T) -> U) -> Vector<I, U> {
204 Vector {
205 vector: self
206 .vector
207 .iter_mut()
208 .map(|x_opt| x_opt.as_mut().map(&mut f))
209 .collect(),
210 elem_count: self.elem_count,
211 }
212 }
213
214 pub fn map_ref_indexed<'a, U>(&'a self, mut f: impl FnMut(I, &'a T) -> U) -> Vector<I, U> {
216 Vector {
217 vector: self
218 .vector
219 .iter_enumerated()
220 .map(|(i, x_opt)| x_opt.as_ref().map(|x| f(i, x)))
221 .collect(),
222 elem_count: self.elem_count,
223 }
224 }
225
226 pub fn map_opt<U>(self, f: impl FnMut(Option<T>) -> Option<U>) -> Vector<I, U> {
228 Vector {
229 vector: self.vector.into_iter().map(f).collect(),
230 elem_count: self.elem_count,
231 }
232 }
233
234 pub fn map_ref_opt<'a, U>(
236 &'a self,
237 mut f: impl FnMut(Option<&'a T>) -> Option<U>,
238 ) -> Vector<I, U> {
239 let mut ret = Vector {
240 vector: self.vector.iter().map(|x_opt| f(x_opt.as_ref())).collect(),
241 elem_count: self.elem_count,
242 };
243 ret.elem_count = ret.iter().count();
244 ret
245 }
246
247 pub fn iter(&self) -> impl Iterator<Item = &T> + DoubleEndedIterator + Clone {
249 self.vector.iter().filter_map(|opt| opt.as_ref())
250 }
251
252 pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> + DoubleEndedIterator {
253 self.vector.iter_mut().filter_map(|opt| opt.as_mut())
254 }
255
256 pub fn iter_indexed(&self) -> impl Iterator<Item = (I, &T)> {
257 self.vector
258 .iter_enumerated()
259 .flat_map(|(i, opt)| Some((i, opt.as_ref()?)))
260 }
261
262 pub fn iter_mut_indexed(&mut self) -> impl Iterator<Item = (I, &mut T)> {
263 self.vector
264 .iter_mut_enumerated()
265 .flat_map(|(i, opt)| Some((i, opt.as_mut()?)))
266 }
267
268 pub fn into_iter_indexed(self) -> impl Iterator<Item = (I, T)> {
269 self.vector
270 .into_iter_enumerated()
271 .flat_map(|(i, opt)| Some((i, opt?)))
272 }
273
274 pub fn iter_indexed_values(&self) -> impl Iterator<Item = (I, &T)> {
275 self.iter_indexed()
276 }
277
278 pub fn into_iter_indexed_values(self) -> impl Iterator<Item = (I, T)> {
279 self.into_iter_indexed()
280 }
281
282 pub fn iter_all_slots(&self) -> impl Iterator<Item = &Option<T>> {
284 self.vector.iter()
285 }
286
287 pub fn iter_indexed_all_slots(&self) -> impl Iterator<Item = (I, &Option<T>)> {
288 self.vector.iter_enumerated()
289 }
290
291 pub fn iter_indices(&self) -> impl Iterator<Item = I> + '_ {
292 self.iter_indexed().map(|(id, _)| id)
294 }
295
296 pub fn all_indices(&self) -> impl Iterator<Item = I> + use<I, T> {
297 self.vector.indices()
298 }
299
300 pub fn extract<'a, F: FnMut(&mut T) -> bool>(
303 &'a mut self,
304 mut f: F,
305 ) -> impl Iterator<Item = (I, T)> + use<'a, I, T, F> {
306 let elem_count = &mut self.elem_count;
307 self.vector
308 .iter_mut_enumerated()
309 .filter_map(move |(i, opt)| {
310 if f(opt.as_mut()?) {
311 *elem_count -= 1;
312 let elem = mem::replace(opt, None)?;
313 Some((i, elem))
314 } else {
315 None
316 }
317 })
318 }
319
320 pub fn retain(&mut self, mut f: impl FnMut(&mut T) -> bool) {
322 self.extract(|x| !f(x)).for_each(drop);
323 }
324
325 pub fn split_off(&mut self, at: usize) -> Self {
327 let mut ret = Self {
328 vector: self.vector.split_off(I::from_usize(at)),
329 elem_count: 0,
330 };
331 self.elem_count = self.iter().count();
332 ret.elem_count = ret.iter().count();
333 ret
334 }
335}
336
337impl<I: Idx, T> Default for Vector<I, T> {
338 fn default() -> Self {
339 Self::new()
340 }
341}
342
343impl<I: Idx> Deref for ReservedSlot<I> {
344 type Target = I;
345 fn deref(&self) -> &Self::Target {
346 &self.0
347 }
348}
349
350impl<I, R, T> Index<R> for Vector<I, T>
351where
352 I: Idx,
353 R: IdxSliceIndex<I, Option<T>, Output = Option<T>>,
354{
355 type Output = T;
356 fn index(&self, index: R) -> &Self::Output {
357 self.vector[index].as_ref().unwrap()
358 }
359}
360
361impl<I, R, T> IndexMut<R> for Vector<I, T>
362where
363 I: Idx,
364 R: IdxSliceIndex<I, Option<T>, Output = Option<T>>,
365{
366 fn index_mut(&mut self, index: R) -> &mut Self::Output {
367 self.vector[index].as_mut().unwrap()
368 }
369}
370
371impl<'a, I, T> IntoIterator for &'a Vector<I, T>
372where
373 I: Idx,
374{
375 type Item = &'a T;
376 type IntoIter = impl Iterator<Item = &'a T>;
377
378 fn into_iter(self) -> Self::IntoIter {
379 self.vector.iter().flat_map(|opt| opt.as_ref())
380 }
381}
382
383impl<'a, I, T> IntoIterator for &'a mut Vector<I, T>
384where
385 I: Idx,
386{
387 type Item = &'a mut T;
388 type IntoIter = impl Iterator<Item = &'a mut T>;
389
390 fn into_iter(self) -> Self::IntoIter {
391 self.vector.iter_mut().flat_map(|opt| opt.as_mut())
392 }
393}
394
395impl<I, T> IntoIterator for Vector<I, T>
396where
397 I: Idx,
398{
399 type Item = T;
400 type IntoIter = impl Iterator<Item = T>;
401
402 fn into_iter(self) -> Self::IntoIter {
403 self.vector.into_iter().flat_map(|opt| opt)
404 }
405}
406
407impl<I, T> FromIterator<T> for Vector<I, T>
409where
410 I: Idx,
411{
412 #[inline]
413 fn from_iter<It: IntoIterator<Item = T>>(iter: It) -> Vector<I, T> {
414 let mut elem_count = 0;
415 let vector = IndexVec::from_iter(iter.into_iter().inspect(|_| elem_count += 1).map(Some));
416 Vector { vector, elem_count }
417 }
418}
419
420impl<I, T> From<Vec<T>> for Vector<I, T>
422where
423 I: Idx,
424{
425 fn from(v: Vec<T>) -> Self {
426 v.into_iter().collect()
427 }
428}
429
430impl<I, T, const N: usize> From<[T; N]> for Vector<I, T>
432where
433 I: Idx,
434{
435 fn from(v: [T; N]) -> Self {
436 v.into_iter().collect()
437 }
438}
439
440impl<I: Idx, T: Serialize> Serialize for Vector<I, T> {
441 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
442 where
443 S: Serializer,
444 {
445 self.vector.serialize(serializer)
446 }
447}
448
449impl<'de, I: Idx, T: Deserialize<'de>> Deserialize<'de> for Vector<I, T> {
450 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
451 where
452 D: serde::Deserializer<'de>,
453 {
454 let mut ret = Self {
455 vector: Deserialize::deserialize(deserializer)?,
456 elem_count: 0,
457 };
458 ret.elem_count = ret.iter().count();
459 Ok(ret)
460 }
461}
462
463impl<'s, I: Idx, T, V: Visit<'s, T>> Drive<'s, V> for Vector<I, T> {
464 fn drive_inner(&'s self, v: &mut V) -> ControlFlow<V::Break> {
465 for x in self {
466 v.visit(x)?;
467 }
468 Continue(())
469 }
470}
471impl<'s, I: Idx, T, V: VisitMut<'s, T>> DriveMut<'s, V> for Vector<I, T> {
472 fn drive_inner_mut(&'s mut self, v: &mut V) -> ControlFlow<V::Break> {
473 for x in self {
474 v.visit(x)?;
475 }
476 Continue(())
477 }
478}