1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use std::collections::HashMap;
use std::collections::hash_map::Iter as HashMapIter;
use std::fmt::{self, Debug, Formatter};
use std::hash::Hash;

use crate::util::multiset::{self, Multiset, MultisetMap};

impl<T: Eq + Hash> MultisetMap<T> for HashMap<T, usize> {
    fn get_mut(&mut self, item: &T) -> Option<&mut usize> {
        HashMap::get_mut(self, item)
    }

    fn insert(&mut self, item: T) {
        self.insert(item, 1);
    }

    fn remove(&mut self, item: &T) {
        HashMap::remove(self, item);
    }
}

pub(crate) struct HashMultisetIter<'iter, T> {
    hash_map_iter: HashMapIter<'iter, T, usize>
}

impl<'iter, T> Iterator for HashMultisetIter<'iter, T> {
    type Item = (&'iter T, usize);

    fn next(&mut self) -> Option<(&'iter T, usize)> {
        self.hash_map_iter.next().map(|(value, multiplicity)| (value, *multiplicity))
    }
}

pub(crate) struct HashMultiset<T> {
    entries: HashMap<T, usize>
}

impl<T: Debug + Eq + Hash> Multiset<T> for HashMultiset<T> {

    type Iter<'iter> = HashMultisetIter<'iter, T>
    where
        T: 'iter,
        Self: 'iter;

    fn new() -> HashMultiset<T> {
        HashMultiset {
            entries: HashMap::new()
        }
    }

    fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    fn iter<'reference>(&'reference self) -> HashMultisetIter<'reference, T>
    where
        T: 'reference
    {
        HashMultisetIter {
            hash_map_iter: self.entries.iter()
        }
    }

    fn add(&mut self, item: T) {
        multiset::multiset_map_add(&mut self.entries, item)
    }

    fn remove(&mut self, item: &T) -> bool {
        multiset::multiset_map_remove(&mut self.entries, item)
    }
}

impl<T: Debug + Eq + Hash> FromIterator<T> for HashMultiset<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashMultiset<T> {
        multiset::multiset_from_iter(iter)
    }
}

impl<T: Debug + Eq + Hash> Debug for HashMultiset<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        multiset::fmt_multiset_debug(self, f)
    }
}

#[cfg(test)]
mod tests {

    use crate::test_multiset_impl;
    use crate::util::multiset::Multiset;
    use crate::util::multiset::hash::HashMultiset;

    test_multiset_impl!(HashMultiset);
}