1use crate::{Clear, Len, MapGet, MapInsert, MapMut, Retain, VecMap};
2use alloc::collections::BTreeMap;
3use core::{borrow::Borrow, marker::PhantomData};
4use genindex::{GenIndex, IndexPair};
5
6static INVALID_INDEX: &str = "invalid index";
7
8#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
10#[repr(transparent)]
11pub struct GenIndexMap<T, I = IndexPair, M = VecMap<(I, T)>> {
12 map: M,
13 marker: PhantomData<(I, T)>,
14}
15
16pub type GenIndexVecMap<T, I = IndexPair> = GenIndexMap<T, I>;
18
19pub type GenIndexBTreeMap<T, I = IndexPair> =
21 GenIndexMap<T, I, BTreeMap<<I as GenIndex>::Index, (I, T)>>;
22
23#[cfg(feature = "std")]
24pub type GenIndexHashMap<T, I = IndexPair> =
26 GenIndexMap<T, I, std::collections::HashMap<<I as GenIndex>::Index, (I, T)>>;
27
28type GenIndexMapIntoIter<T, I, M> =
30 core::iter::Map<<M as IntoIterator>::IntoIter, fn(<M as IntoIterator>::Item) -> (I, T)>;
31
32type GenIndexMapIter<'a, T, I, M> = core::iter::Map<
34 <&'a M as IntoIterator>::IntoIter,
35 fn(<&'a M as IntoIterator>::Item) -> (&'a I, &'a T),
36>;
37
38type GenIndexMapIterMut<'a, T, I, M> = core::iter::Map<
40 <&'a mut M as IntoIterator>::IntoIter,
41 fn(<&'a mut M as IntoIterator>::Item) -> (&'a I, &'a mut T),
42>;
43
44impl<T, I, M> GenIndexMap<T, I, M> {
45 #[inline]
53 pub fn new() -> Self
54 where
55 M: Default,
56 {
57 Self {
58 map: Default::default(),
59 marker: PhantomData,
60 }
61 }
62
63 #[inline]
75 pub fn len(&self) -> usize
76 where
77 M: Len,
78 {
79 self.map.len()
80 }
81
82 #[inline]
94 pub fn clear(&mut self)
95 where
96 M: Clear,
97 {
98 self.map.clear()
99 }
100
101 #[inline]
120 pub fn iter<'a, K>(&'a self) -> GenIndexMapIter<'a, T, I, M>
121 where
122 &'a M: IntoIterator<Item = (K, &'a (I, T))>,
123 {
124 fn map<'a, K, I, T>((_, (i, t)): (K, &'a (I, T))) -> (&'a I, &'a T) {
125 (i, t)
126 }
127 (&self.map).into_iter().map(map)
128 }
129
130 #[inline]
149 pub fn iter_mut<'a, K>(&'a mut self) -> GenIndexMapIterMut<'a, T, I, M>
150 where
151 &'a mut M: IntoIterator<Item = (K, &'a mut (I, T))>,
152 {
153 fn map<'a, K, I, T>((_, (i, t)): (K, &'a mut (I, T))) -> (&'a I, &'a mut T) {
154 (i, t)
155 }
156 (&mut self.map).into_iter().map(map)
157 }
158}
159
160impl<T, I: GenIndex, M> GenIndexMap<T, I, M> {
161 pub fn get<K>(&self, key: &I) -> Option<&T>
173 where
174 I::Index: TryInto<K>,
175 M: MapGet<K, Value = (I, T)>,
176 M::Key: Borrow<K>,
177 {
178 let (i, v) = self.map.get(&index_of(key)?)?;
179 if i == key {
180 Some(v)
181 } else {
182 None
183 }
184 }
185
186 pub fn get_mut<K>(&mut self, key: &I) -> Option<&mut T>
199 where
200 I::Index: TryInto<K>,
201 M: MapMut<K, Value = (I, T)>,
202 M::Key: Borrow<K>,
203 {
204 let (i, v) = self.map.get_mut(&index_of(key)?)?;
205 if i == key {
206 Some(v)
207 } else {
208 None
209 }
210 }
211
212 #[inline]
224 pub fn remove<K>(&mut self, key: &I) -> Option<T>
225 where
226 I::Index: TryInto<K>,
227 M: MapMut<K, Value = (I, T)>,
228 M::Key: Borrow<K>,
229 {
230 if self.get(key).is_some() {
231 Some(self.map.remove(&index_of(key)?)?.1)
232 } else {
233 None
234 }
235 }
236
237 #[inline]
252 pub fn retain(&mut self, mut f: impl FnMut(&I, &mut T) -> bool)
253 where
254 M: Retain<Value = (I, T)>,
255 {
256 self.map.retain(|_, (i, t)| f(i, t))
257 }
258
259 #[inline]
272 pub fn insert(&mut self, key: I, value: T) -> Option<T>
273 where
274 M: MapInsert<Value = (I, T)>,
275 I::Index: TryInto<M::Key>,
276 {
277 Some(
278 self.map
279 .insert(index_of(&key).expect(INVALID_INDEX), (key, value))?
280 .1,
281 )
282 }
283}
284
285#[inline]
286fn index_of<I: GenIndex, K>(i: &I) -> Option<K>
287where
288 I::Index: TryInto<K>,
289{
290 i.index().try_into().ok()
291}
292
293mod core_impl {
294 use super::{GenIndexMap, INVALID_INDEX};
295 use crate::{MapGet, MapInsert, MapMut};
296 use core::ops::{Index, IndexMut};
297 use genindex::GenIndex;
298
299 impl<T, I: GenIndex, M> Extend<(I, T)> for GenIndexMap<T, I, M>
300 where
301 M: MapInsert<Value = (I, T)>,
302 I::Index: TryInto<M::Key>,
303 {
304 fn extend<It: IntoIterator<Item = (I, T)>>(&mut self, iter: It) {
305 for (i, v) in iter {
306 self.insert(i, v);
307 }
308 }
309 }
310
311 impl<'a, T: Clone + 'a, I: GenIndex + 'a, M> Extend<(&'a I, &'a T)> for GenIndexMap<T, I, M>
312 where
313 M: MapInsert<Value = (I, T)>,
314 I::Index: TryInto<M::Key>,
315 {
316 fn extend<It: IntoIterator<Item = (&'a I, &'a T)>>(&mut self, iter: It) {
317 for (i, v) in iter {
318 self.insert(*i, v.clone());
319 }
320 }
321 }
322
323 impl<T, I: GenIndex, M> FromIterator<(I, T)> for GenIndexMap<T, I, M>
324 where
325 M: Default + MapInsert<Value = (I, T)>,
326 I::Index: TryInto<M::Key>,
327 {
328 fn from_iter<It: IntoIterator<Item = (I, T)>>(iter: It) -> Self {
329 let iter = iter.into_iter();
330 let mut map = GenIndexMap::new();
331 map.extend(iter);
332 map
333 }
334 }
335
336 impl<'a, T: Clone + 'a, I: GenIndex + 'a, M> FromIterator<(&'a I, &'a T)> for GenIndexMap<T, I, M>
337 where
338 M: Default + MapInsert<Value = (I, T)>,
339 I::Index: TryInto<M::Key>,
340 {
341 fn from_iter<It: IntoIterator<Item = (&'a I, &'a T)>>(iter: It) -> Self {
342 let iter = iter.into_iter();
343 let mut set = GenIndexMap::new();
344 set.extend(iter);
345 set
346 }
347 }
348
349 impl<T, I: GenIndex, K, M> Index<I> for GenIndexMap<T, I, M>
350 where
351 M: MapGet<K, Key = K, Value = (I, T)>,
352 I::Index: TryInto<K>,
353 {
354 type Output = T;
355
356 fn index(&self, index: I) -> &Self::Output {
357 self.get(&index).expect(INVALID_INDEX)
358 }
359 }
360
361 impl<T, I: GenIndex, K, M> IndexMut<I> for GenIndexMap<T, I, M>
362 where
363 M: MapMut<K, Key = K, Value = (I, T)>,
364 I::Index: TryInto<K>,
365 {
366 fn index_mut(&mut self, index: I) -> &mut Self::Output {
367 self.get_mut(&index).expect(INVALID_INDEX)
368 }
369 }
370}
371
372mod collections_impl {
373 use super::GenIndexMap;
374 use crate::{Clear, Len, Map, MapGet, MapInsert, MapMut, Retain};
375 use genindex::GenIndex;
376
377 impl<T, I, M: Clear> Clear for GenIndexMap<T, I, M> {
378 #[inline]
379 fn clear(&mut self) {
380 self.clear();
381 }
382 }
383
384 impl<T, I, M: Len> Len for GenIndexMap<T, I, M> {
385 #[inline]
386 fn len(&self) -> usize {
387 self.len()
388 }
389 }
390
391 impl<T, I, M> Map for GenIndexMap<T, I, M> {
392 type Key = I;
393 type Value = T;
394 }
395
396 impl<T, I: GenIndex, M> MapGet<I> for GenIndexMap<T, I, M>
397 where
398 I::Index: TryInto<M::Key>,
399 M: MapGet<<M as Map>::Key, Value = (I, T)>,
400 {
401 #[inline]
402 fn get(&self, key: &I) -> Option<&Self::Value> {
403 self.get(key)
404 }
405 }
406
407 impl<T, I: GenIndex, M> MapMut<I> for GenIndexMap<T, I, M>
408 where
409 I::Index: TryInto<M::Key>,
410 M: MapMut<<M as Map>::Key, Value = (I, T)>,
411 {
412 #[inline]
413 fn get_mut(&mut self, key: &I) -> Option<&mut Self::Value> {
414 self.get_mut(key)
415 }
416
417 #[inline]
418 fn remove(&mut self, key: &I) -> Option<Self::Value> {
419 self.remove(key)
420 }
421 }
422
423 impl<T, I: GenIndex, M> MapInsert for GenIndexMap<T, I, M>
424 where
425 M: MapInsert<Value = (I, T)>,
426 I::Index: TryInto<M::Key>,
427 {
428 #[inline]
429 fn insert(&mut self, key: Self::Key, value: Self::Value) -> Option<Self::Value> {
430 self.insert(key, value)
431 }
432 }
433
434 impl<T, I: GenIndex, M: Retain<Value = (I, T)>> Retain for GenIndexMap<T, I, M> {
435 type Key = I;
436 type Value = T;
437
438 #[inline]
439 fn retain(&mut self, f: impl FnMut(&Self::Key, &mut Self::Value) -> bool) {
440 self.retain(f);
441 }
442 }
443}
444
445mod iter {
446 use super::{GenIndexMap, GenIndexMapIntoIter, GenIndexMapIter, GenIndexMapIterMut};
447
448 impl<T, I, K, M: IntoIterator<Item = (K, (I, T))>> IntoIterator for GenIndexMap<T, I, M> {
449 type Item = (I, T);
450 type IntoIter = GenIndexMapIntoIter<T, I, M>;
451
452 #[inline]
453 fn into_iter(self) -> Self::IntoIter {
454 fn map<K, I, T>((_, (i, t)): (K, (I, T))) -> (I, T) {
455 (i, t)
456 }
457 self.map.into_iter().map(map)
458 }
459 }
460
461 impl<'a, T: 'a, I: 'a, K: 'a, M> IntoIterator for &'a GenIndexMap<T, I, M>
462 where
463 &'a M: IntoIterator<Item = (K, &'a (I, T))>,
464 {
465 type Item = (&'a I, &'a T);
466 type IntoIter = GenIndexMapIter<'a, T, I, M>;
467
468 #[inline]
469 fn into_iter(self) -> Self::IntoIter {
470 self.iter()
471 }
472 }
473
474 impl<'a, T: 'a, I: 'a, K: 'a, M> IntoIterator for &'a mut GenIndexMap<T, I, M>
475 where
476 &'a mut M: IntoIterator<Item = (K, &'a mut (I, T))>,
477 {
478 type Item = (&'a I, &'a mut T);
479 type IntoIter = GenIndexMapIterMut<'a, T, I, M>;
480
481 #[inline]
482 fn into_iter(self) -> Self::IntoIter {
483 self.iter_mut()
484 }
485 }
486}
487
488#[cfg(feature = "serde")]
489mod serde_impl {
490 use super::GenIndexMap;
491 use core::marker::PhantomData;
492 use serde::{Deserialize, Deserializer, Serialize, Serializer};
493
494 impl<T, I, M: Serialize> Serialize for GenIndexMap<T, I, M> {
495 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
496 self.map.serialize(serializer)
497 }
498 }
499
500 impl<'de, T, I, M: Deserialize<'de>> Deserialize<'de> for GenIndexMap<T, I, M> {
501 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
502 where
503 D: Deserializer<'de>,
504 {
505 let map: M = Deserialize::deserialize(deserializer)?;
506 Ok(Self {
507 map,
508 marker: PhantomData,
509 })
510 }
511 }
512}
513
514#[cfg(test)]
515mod tests {
516 use crate::{Clear, Len, MapGet, MapInsert, MapMut, Retain};
517
518 use super::GenIndexMap;
519 use genindex::{GenIndex, IndexU64};
520
521 fn create_map() -> GenIndexMap<u32, IndexU64> {
522 let mut map = GenIndexMap::new();
523 for i in 0..10 {
524 map.insert(IndexU64::from_index(i), i);
525 }
526 map
527 }
528
529 #[test]
530 fn test_from_iter() {
531 let map = create_map();
532
533 let map2 = GenIndexMap::from_iter(map.iter());
534 assert!(map == map2);
535
536 let map2 = GenIndexMap::from_iter(map.clone().into_iter());
537 assert!(map == map2);
538 }
539
540 #[test]
541 fn test_iter() {
542 let map = create_map();
543 let mut i = 0;
544 for (idx, value) in &map {
545 assert_eq!(idx.index(), *value);
546 assert_eq!(i, *value);
547 i += 1;
548 }
549 assert_eq!(i, 10);
550 }
551
552 #[test]
553 fn test_iter_mut() {
554 let mut map = create_map();
555 let mut i = 0;
556 for (idx, value) in &mut map {
557 *value += 1;
558 assert_eq!(i, idx.index());
559 assert_eq!(i + 1, *value);
560 i += 1;
561 }
562 assert_eq!(i, 10);
563 }
564
565 #[test]
566 fn test_into_iter() {
567 let map = create_map();
568 let mut i = 0;
569 for (idx, value) in map {
570 assert_eq!(idx.index(), value);
571 assert_eq!(i, value);
572 i += 1;
573 }
574 assert_eq!(i, 10);
575 }
576
577 #[test]
578 fn test_clear_len() {
579 let mut map = create_map();
580 assert_eq!(Len::len(&map), 10);
581 Clear::clear(&mut map);
582 assert!(Len::is_empty(&map));
583 }
584
585 #[test]
586 fn test_map_get() {
587 let map = create_map();
588 let (&first, &value) = map.iter().next().unwrap();
589 assert!(MapGet::contains_key(&map, &first));
590 assert_eq!(MapGet::get(&map, &first), Some(&value));
591 assert_eq!(MapGet::get(&map, &IndexU64::from_index(123)), None);
592 }
593
594 #[test]
595 fn test_map_mut() {
596 let mut map = create_map();
597 let first = *map.iter().next().unwrap().0;
598
599 let new_value = 1234;
600 map[first] = new_value;
601 assert_eq!(map[first], new_value);
602
603 let new_value = 123;
604 *MapMut::get_mut(&mut map, &first).unwrap() = new_value;
605 assert_eq!(MapGet::get(&map, &first), Some(&new_value));
606
607 assert_eq!(MapMut::remove(&mut map, &first), Some(new_value));
608 assert_eq!(MapGet::get(&map, &first), None);
609 }
610
611 #[test]
612 fn test_map_insert() {
613 let mut map = create_map();
614 let (&first, &value) = map.iter().next().unwrap();
615
616 let new_value = 123;
617 assert_eq!(MapInsert::insert(&mut map, first, new_value), Some(value));
618 assert_eq!(MapGet::get(&map, &first), Some(&new_value));
619
620 let unknown_idx = IndexU64::from_index(123);
621 assert_eq!(MapInsert::insert(&mut map, unknown_idx, new_value), None);
622 assert_eq!(MapGet::get(&map, &unknown_idx), Some(&new_value));
623 }
624
625 #[test]
626 fn test_retain() {
627 let mut map = create_map();
628 let mut iter = map.iter();
629 iter.next();
630 let idx1 = *iter.next().unwrap().0;
631
632 Retain::retain(&mut map, |_, val| {
633 if *val == 1 {
634 *val = 3;
635 true
636 } else {
637 false
638 }
639 });
640 assert_eq!(map.len(), 1);
641 assert_eq!(map.get(&idx1), Some(&3));
642 }
643
644 #[cfg(feature = "serde")]
645 #[test]
646 fn test_genindex_btreemap_serialize() {
647 use super::GenIndexBTreeMap;
648 use alloc::collections::BTreeMap;
649 use genindex::{GenIndex, IndexPair};
650 use serde_json::Value;
651
652 let mut map = GenIndexBTreeMap::default();
653 map.insert(<IndexPair>::from_raw_parts(1, 2), "a");
654 map.insert(IndexPair::from_raw_parts(0, 3), "b");
655 map.insert(IndexPair::from_raw_parts(4, 5), "c");
656
657 let mut btree = BTreeMap::default();
658 btree.insert(1, (<IndexPair>::from_raw_parts(1, 2), "a"));
659 btree.insert(0, (IndexPair::from_raw_parts(0, 3), "b"));
660 btree.insert(4, (IndexPair::from_raw_parts(4, 5), "c"));
661
662 let expected_json: Value = serde_json::to_value(btree).unwrap();
663 let json: Value = serde_json::to_value(map).unwrap();
664
665 assert_eq!(json, expected_json);
666 }
667
668 #[cfg(feature = "serde")]
669 #[test]
670 fn test_genindex_btreemap_deserialize() {
671 use super::GenIndexBTreeMap;
672 use alloc::collections::BTreeMap;
673 use alloc::string::String;
674 use genindex::{GenIndex, IndexPair};
675 use serde_json::Value;
676
677 let mut btree = BTreeMap::default();
678 btree.insert(1usize, (<IndexPair>::from_raw_parts(1, 2), "a"));
679 btree.insert(3, (IndexPair::from_raw_parts(3, 4), "c"));
680
681 let json: Value = serde_json::to_value(btree).unwrap();
682
683 let map: GenIndexBTreeMap<String> = serde_json::from_value(json).unwrap();
684
685 assert_eq!(map.len(), 2);
686 assert_eq!(map[IndexPair::from_raw_parts(1, 2)], "a");
687 assert_eq!(map[IndexPair::from_raw_parts(3, 4)], "c");
688 }
689
690 #[cfg(all(feature = "serde", feature = "std"))]
691 #[test]
692 fn test_genindex_hashmap_serialize() {
693 use super::GenIndexHashMap;
694 use genindex::{GenIndex, IndexPair};
695 use serde_json::Value;
696 use std::collections::HashMap;
697
698 let mut map = GenIndexHashMap::default();
699 map.insert(<IndexPair>::from_raw_parts(1, 2), "a");
700 map.insert(IndexPair::from_raw_parts(0, 3), "b");
701 map.insert(IndexPair::from_raw_parts(4, 5), "c");
702
703 let mut hashmap = HashMap::<i32, (IndexPair, &str)>::default();
704 hashmap.insert(1, (<IndexPair>::from_raw_parts(1, 2), "a"));
705 hashmap.insert(0, (IndexPair::from_raw_parts(0, 3), "b"));
706 hashmap.insert(4, (IndexPair::from_raw_parts(4, 5), "c"));
707
708 let expected_json: Value = serde_json::to_value(hashmap).unwrap();
709 let json: Value = serde_json::to_value(map).unwrap();
710
711 assert_eq!(json, expected_json);
712 }
713
714 #[cfg(all(feature = "serde", feature = "std"))]
715 #[test]
716 fn test_genindex_hashmap_deserialize() {
717 use super::GenIndexHashMap;
718 use alloc::string::String;
719 use genindex::{GenIndex, IndexPair};
720 use serde_json::Value;
721 use std::collections::HashMap;
722
723 let mut btree = HashMap::<usize, (IndexPair, &str)>::default();
724 btree.insert(1usize, (<IndexPair>::from_raw_parts(1, 2), "a"));
725 btree.insert(3, (IndexPair::from_raw_parts(3, 4), "c"));
726
727 let json: Value = serde_json::to_value(btree).unwrap();
728
729 let map: GenIndexHashMap<String, IndexPair> = serde_json::from_value(json).unwrap();
730
731 assert_eq!(map.len(), 2);
732 assert_eq!(map[IndexPair::from_raw_parts(1, 2)], "a");
733 assert_eq!(map[IndexPair::from_raw_parts(3, 4)], "c");
734 }
735}