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
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#![cfg_attr(docsrs, feature(doc_cfg))]
//! This is a very simple crate which you can use for creating many-to-many data structures in Rust, it's intended purpose or use case is for situations where you need to map a set of ids to another set of ids (for example in PubSub, such as `hive_pubsub` which is what this crate was designed for). It does this by using two `HashMap`s, one linking `Left` to a set of `Right` and vice-versa.
//!
//! This crate is like a fusion of `bimap` and `multimap`. I didn't see anything like this on crates.io, or anywhere really so I made my own thing.
//!
//! ## Constraints
//!
//! Keys on either side (left or right) must implement the following traits:
//! - [std::hash::Hash](std::hash::Hash)
//! - [std::cmp::Eq](std::cmp::Eq)
//! - [core::clone::Clone](core::clone::Clone)
//!
//! ## Example
//!
//! ```rust
//! use many_to_many::ManyToMany;
//!
//! let mut map = ManyToMany::new();
//! map.insert(1, 2);
//! map.insert(1, 3);
//! map.insert(1, 4);
//!
//! assert_eq_sorted(map.get_left(&1), vec![ 2, 3, 4 ]);
//!
//! map.insert(5, 2);
//! map.remove(&1, &4);
//!
//! assert_eq_sorted(map.get_left(&1), vec![ 2, 3 ]);
//! assert_eq_sorted(map.get_right(&2), vec![ 1, 5 ]);
//!
//! map.remove(&1, &2);
//! map.remove(&1, &3);
//!
//! assert_eq!(map.get_left(&1), None);
//!
//! map.insert(11, 10);
//! map.insert(12, 10);
//! map.insert(13, 10);
//! map.remove_right(&10);
//!
//! assert_eq!(map.get_left(&11), None);
//! assert_eq!(map.get_right(&10), None);
//!
//! /// This is a helper function to unwrap the option,
//! /// sort the array and compare it with a sorted array.
//! fn assert_eq_sorted(a: Option<Vec<i32>>, b: Vec<i32>) {
//!     assert!(a.is_some());
//!     let mut list = a.unwrap();
//!     list.sort();
//!     assert_eq!(list, b);
//! }
//! ```
//! 
//! ### Serde support
//! This crate has optional Serde support. To enable it, specify the `serde` feature in `Cargo.toml`. For example:
//! 
//! ```toml
//! [dependencies]
//! many-to-many = { version = "^0.1.7", features = ["serde"] }
//! ```
//!
//! <script>console.log("many-to-many, crated by insrt.uk")</script>

use std::collections::hash_map::Keys;
use std::collections::{HashMap, HashSet};

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
pub mod serde;

/// # Many-To-Many data structure.
#[derive(Debug)]
pub struct ManyToMany<L: std::hash::Hash + Eq + Clone, R: std::hash::Hash + Eq + Clone> {
    left: HashMap<L, HashSet<R>>,
    right: HashMap<R, HashSet<L>>,
}

impl<L: std::hash::Hash + Eq + Clone, R: std::hash::Hash + Eq + Clone> ManyToMany<L, R> {
    pub fn new() -> ManyToMany<L, R> {
        ManyToMany {
            left: HashMap::new(),
            right: HashMap::new(),
        }
    }

    fn get_mut_left(&mut self, left: &L) -> &mut HashSet<R> {
        if self.left.contains_key(left) {
            self.left.get_mut(left).expect(ERROR)
        } else {
            self.left.insert(left.clone(), HashSet::new());
            self.left.get_mut(left).expect(ERROR)
        }
    }

    fn get_mut_right(&mut self, right: &R) -> &mut HashSet<L> {
        if self.right.contains_key(right) {
            self.right.get_mut(right).expect(ERROR)
        } else {
            self.right.insert(right.clone(), HashSet::new());
            self.right.get_mut(right).expect(ERROR)
        }
    }

    /// Insert a new mapping between Left and Right.
    ///
    /// Returns whether the mapping already existed.
    pub fn insert(&mut self, left: L, right: R) -> bool {
        self.get_mut_left(&left).insert(right.clone()) && self.get_mut_right(&right).insert(left)
    }

    /// Remove an existing mapping between Left and Right.
    ///
    /// Returns whether the mapping was removed.
    pub fn remove(&mut self, left: &L, right: &R) -> bool {
        let list = self.get_mut_left(&left);
        let removed = list.remove(right);

        if list.len() == 0 {
            self.left.remove(left);
        }

        let list = self.get_mut_right(&right);
        list.remove(left);

        if list.len() == 0 {
            self.right.remove(right);
        }

        // We should have a guarantee that if it was removed from the
        // right list, it should also be present in the left list and
        // hence also removed from the left list.
        removed
    }

    /// Get all Left keys.
    pub fn get_left_keys(&self) -> Keys<L, HashSet<R>> {
        self.left.keys()
    }

    /// Get all Right keys.
    pub fn get_right_keys(&self) -> Keys<R, HashSet<L>> {
        self.right.keys()
    }

    /// Get all mappings to Right from specific Left key.
    pub fn get_left(&self, left: &L) -> Option<Vec<R>> {
        if let Some(entry) = self.left.get(left) {
            Some(entry.iter().cloned().collect())
        } else {
            None
        }
    }

    /// Get all mappings to Left from specific Right key.
    pub fn get_right(&self, right: &R) -> Option<Vec<L>> {
        if let Some(entry) = self.right.get(right) {
            Some(entry.iter().cloned().collect())
        } else {
            None
        }
    }

    /// Remove all mappings from Left.
    ///
    /// Returns whether any mappings existed.
    pub fn remove_left(&mut self, left: &L) -> bool {
        if let Some(list) = self.get_left(left) {
            for right in &list {
                self.remove(left, right);
            }

            true
        } else {
            false
        }
    }

    /// Remove all mappings from Right.
    ///
    /// Returns whether any mappings existed.
    pub fn remove_right(&mut self, right: &R) -> bool {
        if let Some(list) = self.get_right(right) {
            for left in &list {
                self.remove(left, right);
            }

            true
        } else {
            false
        }
    }
}

static ERROR: &str = "Hit impossible condition.";

#[cfg(test)]
mod tests {
    #[test]
    fn test() {
        use crate::ManyToMany;

        let mut map = ManyToMany::new();
        map.insert(1, 2);
        map.insert(1, 3);
        map.insert(1, 4);

        assert_eq_sorted(map.get_left(&1), vec![2, 3, 4]);

        map.insert(5, 2);
        map.remove(&1, &4);

        assert_eq_sorted(map.get_left(&1), vec![2, 3]);
        assert_eq_sorted(map.get_right(&2), vec![1, 5]);

        assert_eq!(
            map.get_left_keys().collect::<Vec<_>>().sort(),
            vec![&1, &5].sort()
        );
        assert_eq!(
            map.get_right_keys().collect::<Vec<_>>().sort(),
            vec![&2, &3].sort()
        );

        map.remove(&1, &2);
        map.remove(&1, &3);

        assert_eq!(map.get_left(&1), None);

        map.insert(11, 10);
        map.insert(12, 10);
        map.insert(13, 10);
        map.remove_right(&10);

        assert_eq!(map.get_left(&11), None);
        assert_eq!(map.get_right(&10), None);
    }

    #[test]
    #[cfg(feature = "test")]
    fn serde_test() {
        use crate::ManyToMany;
        use serde_json::{to_string, from_str};

        let mut map = ManyToMany::new();
        map.insert(1, 2);
        map.insert(1, 3);
        map.insert(5, 2);

        let json_string = to_string(&map).unwrap();
        let our_map: ManyToMany<i32, i32> = from_str(&json_string).unwrap();
        
        assert_eq_sorted(our_map.get_left(&1), vec![2, 3]);
        assert_eq_sorted(our_map.get_left(&5), vec![2]);
    }

    /// This is a helper function to unwrap the option,
    /// sort the array and compare it with a sorted array.
    fn assert_eq_sorted(a: Option<Vec<i32>>, b: Vec<i32>) {
        assert!(a.is_some());
        let mut list = a.unwrap();
        list.sort();
        assert_eq!(list, b);
    }
}