multi_bimap 0.5.0

Many-to-many bidirectional map in Rust.
Documentation
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
// SPDX-FileCopyrightText: 2025 multi_bimap contributors
//
// SPDX-License-Identifier: MIT OR Apache-2.0

#![doc(html_root_url = "https://docs.rs/multi_bimap")]
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, doc = "\n## Feature flags\n")]
#![cfg_attr(docsrs, doc = document_features::document_features!())]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(missing_docs)]
#![forbid(unsafe_code)]
#![no_std]

// There's a lot of `<... as Container>` down here because it fixes a compiler
// error that seems to happen due to some type circularity.

#[cfg(feature = "std")]
extern crate std;

extern crate alloc;

use core::borrow::Borrow;

use maplike::containers::Container;
use maplike::one::One;
use maplike::ops::{Clear, Get, Insert, Modify, Put, Remove, WithOne};

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
/// One-to-one bimap made of two antiparallel hash maps.
pub type HashBimap<L, R> =
    MultiBimap<std::collections::HashMap<L, One<R>>, std::collections::HashMap<R, One<L>>>;
/// One-to-one bimap made of two antiparallel B-tree maps.
pub type BTreeBimap<L, R> =
    MultiBimap<alloc::collections::BTreeMap<L, One<R>>, alloc::collections::BTreeMap<R, One<L>>>;

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
/// Many-to-many bimap made of two antiparallel hash-set-valued hash maps.
pub type HashMultiBimap<L, R> = MultiBimap<
    std::collections::HashMap<L, std::collections::HashSet<R>>,
    std::collections::HashMap<R, std::collections::HashSet<L>>,
>;
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
/// Many-to-many bimap made of two antiparallel hash-set-valued hash maps.
pub type HashHashMultiBimap<L, R> = MultiBimap<
    std::collections::HashMap<L, std::collections::HashSet<R>>,
    std::collections::HashMap<R, std::collections::HashSet<L>>,
>;
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
/// Many-to-many bimap made of two antiparallel B-tree-set-valued hash maps.
pub type HashBTreeMultiBimap<L, R> = MultiBimap<
    std::collections::HashMap<L, alloc::collections::BTreeSet<R>>,
    std::collections::HashMap<R, alloc::collections::BTreeSet<L>>,
>;
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
/// Many-to-many bimap made of two antiparallel vec-valued hash maps.
pub type HashVecMultiBimap<L, R> = MultiBimap<
    std::collections::HashMap<L, alloc::collections::BTreeSet<R>>,
    std::collections::HashMap<R, alloc::collections::BTreeSet<L>>,
>;

/// Many-to-many bimap made of two antiparallel B-tree-set-valued B-tree maps.
pub type BTreeMultiBimap<L, R> = MultiBimap<
    alloc::collections::BTreeMap<L, alloc::collections::BTreeSet<R>>,
    alloc::collections::BTreeMap<R, alloc::collections::BTreeSet<L>>,
>;
/// Many-to-many bimap made of two antiparallel B-tree-set-valued B-tree maps.
pub type BTreeBTreeMultiBimap<L, R> = MultiBimap<
    alloc::collections::BTreeMap<L, alloc::collections::BTreeSet<R>>,
    alloc::collections::BTreeMap<R, alloc::collections::BTreeSet<L>>,
>;
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
/// Many-to-many bimap made of two antiparallel B-tree-set-valued B-tree maps.
pub type BTreeHashMultiBimap<L, R> = MultiBimap<
    alloc::collections::BTreeMap<L, std::collections::HashSet<R>>,
    alloc::collections::BTreeMap<R, std::collections::HashSet<L>>,
>;
/// Many-to-many bimap made of two antiparallel vec-valued B-tree maps.
pub type BTreeVecMultiBimap<L, R> = MultiBimap<
    alloc::collections::BTreeMap<L, alloc::vec::Vec<R>>,
    alloc::collections::BTreeMap<R, alloc::vec::Vec<L>>,
>;

/// Many-to-many bidirectional map made of two antiparallel maps.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "undoredo", derive(undoredo::Delta))]
pub struct MultiBimap<L2R, R2L> {
    left_to_right: L2R,
    right_to_left: R2L,
}

impl<L2R, R2L> MultiBimap<L2R, R2L> {
    /// Returns a reference to the left-to-right map.
    pub fn left_to_right(&self) -> &L2R {
        &self.left_to_right
    }

    /// Returns a reference to the right-to-left map.
    pub fn right_to_left(&self) -> &R2L {
        &self.right_to_left
    }
}

impl<L2R: Default, R2L: Default> MultiBimap<L2R, R2L> {
    /// Creates a new, empty `MultiBimap`.
    pub fn new() -> Self {
        MultiBimap {
            left_to_right: Default::default(),
            right_to_left: Default::default(),
        }
    }
}

impl<L2R, R2L> MultiBimap<L2R, R2L>
where
    L2R: Container,
    R2L: Container,
{
    /// Returns the container holding right-side values associated with given
    /// left-side key.
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_bimap::MultiBimap;
    /// use std::collections::{HashMap, HashSet};
    ///
    /// let mut m: MultiBimap<HashMap<&str, HashSet<i32>>, HashMap<i32, HashSet<&str>>> = MultiBimap::new();
    ///
    /// m.insert("a", 1);
    /// m.insert("a", 2);
    ///
    /// assert_eq!(m.get_by_left("a"), Some(&HashSet::from([1, 2])));
    /// assert_eq!(m.get_by_left("missing"), None);
    /// ```
    pub fn get_by_left<Q: ?Sized>(&self, left: &Q) -> Option<&<L2R as Container>::Value>
    where
        L2R: Get<<L2R as Container>::Key, Q>,
        <L2R as Container>::Key: Borrow<Q>,
    {
        self.left_to_right.get(left)
    }

    /// Returns the container holding right-side values associated with given
    /// left-side key.
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_bimap::MultiBimap;
    /// use std::collections::{HashMap, HashSet};
    ///
    /// let mut m: MultiBimap<HashMap<&str, HashSet<i32>>, HashMap<i32, HashSet<&str>>> = MultiBimap::new();
    ///
    /// m.insert("a", 1);
    /// m.insert("b", 1);
    ///
    /// assert_eq!(m.get_by_right(&1), Some(&HashSet::from(["a", "b"])));
    /// assert_eq!(m.get_by_right(&2), None);
    /// ```
    pub fn get_by_right<Q: ?Sized>(&self, right: &Q) -> Option<&<R2L as Container>::Value>
    where
        R2L: Get<<R2L as Container>::Key, Q>,
        <R2L as Container>::Key: Borrow<Q>,
    {
        self.right_to_left.get(right)
    }
}

impl<L2R, R2L> Container for MultiBimap<L2R, R2L>
where
    L2R: Container,
    R2L: Container,
{
    type Key = <L2R as Container>::Key;
    type Value = <R2L as Container>::Key;
}

impl<L2R, R2L> Insert<<L2R as Container>::Key> for MultiBimap<L2R, R2L>
where
    L2R: Container,
    R2L: Container,
    L2R: Get<<L2R as Container>::Key>
        + Insert<<L2R as Container>::Key>
        + Modify<<L2R as Container>::Key>
        + Remove<<L2R as Container>::Key>,
    R2L: Get<<R2L as Container>::Key>
        + Insert<<R2L as Container>::Key>
        + Modify<<R2L as Container>::Key>
        + Remove<<R2L as Container>::Key>,
    <L2R as Container>::Value: WithOne<<R2L as Container>::Key> + Put<<R2L as Container>::Key>,
    <R2L as Container>::Value: WithOne<<L2R as Container>::Key> + Put<<L2R as Container>::Key>,
    <L2R as Container>::Key: Clone + PartialEq,
    <R2L as Container>::Key: Clone + PartialEq,
{
    type Output = (
        Option<<R2L as Container>::Key>,
        Option<<L2R as Container>::Key>,
    );

    fn insert(
        &mut self,
        key: <L2R as Container>::Key,
        value: <R2L as Container>::Key,
    ) -> Self::Output {
        MultiBimap::insert(self, key, value)
    }
}

impl<L2R, R2L> MultiBimap<L2R, R2L>
where
    L2R: Container,
    R2L: Container,
    L2R: Get<<L2R as Container>::Key>
        + Insert<<L2R as Container>::Key>
        + Modify<<L2R as Container>::Key>
        + Remove<<L2R as Container>::Key>,
    R2L: Get<<R2L as Container>::Key>
        + Insert<<R2L as Container>::Key>
        + Modify<<R2L as Container>::Key>
        + Remove<<R2L as Container>::Key>,
    <L2R as Container>::Value: WithOne<<R2L as Container>::Key> + Put<<R2L as Container>::Key>,
    <R2L as Container>::Value: WithOne<<L2R as Container>::Key> + Put<<L2R as Container>::Key>,
{
    /// Insert a left-right association into the bimap.
    ///
    /// Both sides may map to multiple values.
    ///
    /// Returns any values that have been displaced on each side by this
    /// insertion. This can happen if a value container with finite maximum
    /// number of elements is used. For example, [`maplike::one::One`] and
    /// [`Box`] can hold only one element and will always have it displaced and
    /// returned upon insertion.
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_bimap::MultiBimap;
    /// use std::collections::{HashMap, HashSet};
    ///
    /// let mut m: MultiBimap<HashMap<&str, HashSet<i32>>, HashMap<i32, HashSet<&str>>> = MultiBimap::new();
    ///
    /// assert_eq!(m.insert("a", 1), (None, None));
    /// m.insert("a", 2);
    /// m.insert("b", 1);
    ///
    /// assert_eq!(m.get_by_left("a"), Some(&HashSet::from([1, 2])));
    /// ```
    pub fn insert(
        &mut self,
        left: <L2R as Container>::Key,
        right: <R2L as Container>::Key,
    ) -> (
        Option<<R2L as Container>::Key>,
        Option<<L2R as Container>::Key>,
    )
    where
        <L2R as Container>::Key: Clone + PartialEq,
        <R2L as Container>::Key: Clone + PartialEq,
    {
        // PERF: Using Entry API may be faster here, but not all collections
        // support it.

        let left_out = if self.left_to_right.get(&left).is_some() {
            let mut out = None;

            self.left_to_right.modify(&left, |rights| {
                out = rights.put(right.clone());
            });

            out
        } else {
            self.left_to_right
                .insert(left.clone(), WithOne::with_one(right.clone()));
            None
        };

        // A displaced right-side value is no longer associated with `left`, so
        // drop its reverse entry. Skip when it is the same as `right`; the
        // right-side update further below will refresh that entry.
        if let Some(ref old_right) = left_out
            && old_right != &right
        {
            self.right_to_left.remove(old_right);
        }

        let right_out = if self.right_to_left.get(&right).is_some() {
            let mut out = None;
            self.right_to_left.modify(&right, |lefts| {
                out = lefts.put(left.clone());
            });
            out
        } else {
            self.right_to_left
                .insert(right.clone(), WithOne::with_one(left.clone()));
            None
        };

        // Same as above for a displaced left-side key.
        if let Some(ref old_left) = right_out
            && old_left != &left
        {
            self.left_to_right.remove(old_left);
        }

        (left_out, right_out)
    }
}

impl<L2R, R2L> Remove<(<L2R as Container>::Key, <R2L as Container>::Key)> for MultiBimap<L2R, R2L>
where
    L2R: Container,
    R2L: Container,
    L2R: Get<<L2R as Container>::Key>
        + Modify<<L2R as Container>::Key>
        + Remove<<L2R as Container>::Key>,
    R2L: Get<<R2L as Container>::Key>
        + Modify<<R2L as Container>::Key>
        + Remove<<R2L as Container>::Key>,
    <L2R as Container>::Value:
        Remove<<R2L as Container>::Key, Output = Option<()>> + Default + PartialEq,
    <R2L as Container>::Value:
        Remove<<L2R as Container>::Key, Output = Option<()>> + Default + PartialEq,
    <L2R as Container>::Key: Clone,
    <R2L as Container>::Key: Clone,
{
    type Output = Option<(<L2R as Container>::Key, <R2L as Container>::Key)>;

    fn remove(
        &mut self,
        key: &(<L2R as Container>::Key, <R2L as Container>::Key),
    ) -> Option<(<L2R as Container>::Key, <R2L as Container>::Key)> {
        MultiBimap::remove(self, &key.0, &key.1)
    }
}

impl<L2R, R2L> MultiBimap<L2R, R2L>
where
    L2R: Container,
    R2L: Container,
    L2R: Get<<L2R as Container>::Key>
        + Modify<<L2R as Container>::Key>
        + Remove<<L2R as Container>::Key>,
    R2L: Get<<R2L as Container>::Key>
        + Modify<<R2L as Container>::Key>
        + Remove<<R2L as Container>::Key>,
    <L2R as Container>::Value:
        Remove<<R2L as Container>::Key, Output = Option<()>> + Default + PartialEq,
    <R2L as Container>::Value:
        Remove<<L2R as Container>::Key, Output = Option<()>> + Default + PartialEq,
    <L2R as Container>::Key: Clone,
    <R2L as Container>::Key: Clone,
{
    /// Remove a left-right association from the bimap.
    ///
    /// Empty keys are dropped from both sides.
    ///
    /// Returns the removed pair if it was present.
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_bimap::MultiBimap;
    /// use std::collections::{HashMap, HashSet};
    ///
    /// let mut m: MultiBimap<HashMap<&str, HashSet<i32>>, HashMap<i32, HashSet<&str>>> = MultiBimap::new();
    ///
    /// m.insert("a", 1);
    /// m.insert("a", 2);
    /// m.insert("b", 1);
    ///
    /// assert_eq!(m.remove(&"a", &1), Some(("a", 1)));
    /// assert_eq!(m.remove(&"a", &1), None);
    ///
    /// assert_eq!(m.get_by_left("a"), Some(&HashSet::from([2])));
    /// ```
    pub fn remove(
        &mut self,
        left: &<L2R as Container>::Key,
        right: &<R2L as Container>::Key,
    ) -> Option<(<L2R as Container>::Key, <R2L as Container>::Key)> {
        let mut present = false;

        if self.left_to_right.get(left).is_some() {
            self.left_to_right.modify(left, |rights| {
                present = rights.remove(right).is_some();
            });

            if present && self.left_to_right.get(left) == Some(&Default::default()) {
                self.left_to_right.remove(left);
            }
        }

        if self.right_to_left.get(right).is_some() {
            let mut present_right = false;

            self.right_to_left.modify(right, |lefts| {
                present_right = lefts.remove(left).is_some();
            });

            if present_right && self.right_to_left.get(right) == Some(&Default::default()) {
                self.right_to_left.remove(right);
            }
        }

        present.then(|| (left.clone(), right.clone()))
    }
}

impl<L2R, R2L> Clear for MultiBimap<L2R, R2L>
where
    L2R: Clear,
    R2L: Clear,
{
    fn clear(&mut self) {
        MultiBimap::clear(self)
    }
}

impl<L2R, R2L> MultiBimap<L2R, R2L>
where
    L2R: Clear,
    R2L: Clear,
{
    /// Remove all associations from the bimap.
    ///
    /// Clears both the left-to-right and right-to-left sides.
    ///
    /// # Examples
    ///
    /// ```
    /// use multi_bimap::MultiBimap;
    /// use std::collections::{HashMap, HashSet};
    ///
    /// let mut m: MultiBimap<HashMap<&str, HashSet<i32>>, HashMap<i32, HashSet<&str>>> = MultiBimap::new();
    ///
    /// m.insert("a", 1);
    /// m.insert("b", 2);
    /// m.clear();
    ///
    /// assert!(m.left_to_right().is_empty());
    /// assert!(m.right_to_left().is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.left_to_right.clear();
        self.right_to_left.clear();
    }
}

#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;
    use std::collections::{HashMap, HashSet};

    #[test]
    fn insert_allows_many_on_both_sides() {
        let mut m: MultiBimap<HashMap<&str, HashSet<i32>>, HashMap<i32, HashSet<&str>>> =
            MultiBimap::new();

        m.insert("a", 1);
        m.insert("a", 2);
        m.insert("b", 1);

        assert_eq!(m.get_by_left("a"), Some(&HashSet::from([1, 2])));
        assert_eq!(m.get_by_left("b"), Some(&HashSet::from([1])));
        assert_eq!(m.get_by_right(&1), Some(&HashSet::from(["a", "b"])));
        assert_eq!(m.get_by_right(&2), Some(&HashSet::from(["a"])));
    }

    #[test]
    fn remove_pair_and_drop_empty_keys() {
        let mut m: MultiBimap<HashMap<&str, HashSet<i32>>, HashMap<i32, HashSet<&str>>> =
            MultiBimap::new();

        m.insert("a", 1);
        m.insert("a", 2);
        m.insert("b", 1);

        assert_eq!(m.remove(&"a", &1), Some(("a", 1)));
        assert_eq!(m.remove(&"a", &1), None);

        assert_eq!(m.get_by_left("a"), Some(&HashSet::from([2])));
        assert_eq!(m.get_by_right(&1), Some(&HashSet::from(["b"])));

        assert_eq!(m.remove(&"a", &2), Some(("a", 2)));
        assert!(m.get_by_left("a").is_none());
        assert!(m.get_by_right(&2).is_none());
    }

    #[test]
    fn clear_empties_both_sides() {
        let mut m: MultiBimap<HashMap<&str, HashSet<i32>>, HashMap<i32, HashSet<&str>>> =
            MultiBimap::new();

        m.insert("a", 1);
        m.insert("b", 2);
        m.clear();

        assert!(m.left_to_right().is_empty());
        assert!(m.right_to_left().is_empty());
    }

    #[test]
    fn one_to_one_insert_drops_displaced_reverse() {
        let mut m: HashBimap<&str, &str> = HashBimap::new();

        m.insert("Lithuania", "Vilnius");
        assert_eq!(m.insert("Lithuania", "Kaunas"), (Some("Vilnius"), None));
        assert_eq!(m.get_by_left("Lithuania"), Some(&One::new("Kaunas")));
        assert!(m.get_by_right("Vilnius").is_none());
        assert_eq!(m.get_by_right("Kaunas"), Some(&One::new("Lithuania")));

        assert_eq!(m.insert("Lithuania", "Vilnius"), (Some("Kaunas"), None));
        assert_eq!(m.get_by_left("Lithuania"), Some(&One::new("Vilnius")));
        assert!(m.get_by_right("Kaunas").is_none());
        assert_eq!(m.get_by_right("Vilnius"), Some(&One::new("Lithuania")));
    }

    #[test]
    fn one_to_one_insert_steals_existing_right() {
        let mut m: HashBimap<&str, &str> = HashBimap::new();

        m.insert("Poland", "Warsaw");
        assert_eq!(m.insert("Lithuania", "Warsaw"), (None, Some("Poland")));
        assert_eq!(m.get_by_left("Lithuania"), Some(&One::new("Warsaw")));
        assert!(m.get_by_left("Poland").is_none());
        assert_eq!(m.get_by_right("Warsaw"), Some(&One::new("Lithuania")));
    }
}