-
Notifications
You must be signed in to change notification settings - Fork 114
/
map.rs
2613 lines (2413 loc) · 72.9 KB
/
map.rs
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//! An ordered map.
//!
//! An immutable ordered map implemented as a [B-tree] [1].
//!
//! Most operations on this type of map are O(log n). A
//! [`HashMap`][hashmap::HashMap] is usually a better choice for
//! performance, but the `OrdMap` has the advantage of only requiring
//! an [`Ord`][std::cmp::Ord] constraint on the key, and of being
//! ordered, so that keys always come out from lowest to highest,
//! where a [`HashMap`][hashmap::HashMap] has no guaranteed ordering.
//!
//! [1]: https://en.wikipedia.org/wiki/B-tree
//! [hashmap::HashMap]: ../hashmap/struct.HashMap.html
//! [std::cmp::Ord]: https://doc.rust-lang.org/std/cmp/trait.Ord.html
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections;
use std::fmt::{Debug, Error, Formatter};
use std::hash::{BuildHasher, Hash, Hasher};
use std::iter::{FromIterator, Iterator, Sum};
use std::mem;
use std::ops::{Add, Index, IndexMut, RangeBounds};
use crate::hashmap::HashMap;
use crate::nodes::btree::{BTreeValue, Insert, Node, Remove};
#[cfg(has_specialisation)]
use crate::util::linear_search_by;
use crate::util::{Pool, PoolRef};
pub use crate::nodes::btree::{
ConsumingIter, DiffItem as NodeDiffItem, DiffIter as NodeDiffIter, Iter as RangedIter,
};
/// Construct a map from a sequence of key/value pairs.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// # fn main() {
/// assert_eq!(
/// ordmap!{
/// 1 => 11,
/// 2 => 22,
/// 3 => 33
/// },
/// OrdMap::from(vec![(1, 11), (2, 22), (3, 33)])
/// );
/// # }
/// ```
#[macro_export]
macro_rules! ordmap {
() => { $crate::ordmap::OrdMap::new() };
( $( $key:expr => $value:expr ),* ) => {{
let mut map = $crate::ordmap::OrdMap::new();
$({
map.insert($key, $value);
})*;
map
}};
}
#[cfg(not(has_specialisation))]
impl<K: Ord, V> BTreeValue for (K, V) {
type Key = K;
fn ptr_eq(&self, _other: &Self) -> bool {
false
}
fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
where
BK: Ord + ?Sized,
Self::Key: Borrow<BK>,
{
slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key))
}
fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
slice.binary_search_by(|value| value.0.cmp(&key.0))
}
fn cmp_keys<BK>(&self, other: &BK) -> Ordering
where
BK: Ord + ?Sized,
Self::Key: Borrow<BK>,
{
Self::Key::borrow(&self.0).cmp(other)
}
fn cmp_values(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0)
}
}
#[cfg(has_specialisation)]
impl<K: Ord, V> BTreeValue for (K, V) {
type Key = K;
fn ptr_eq(&self, _other: &Self) -> bool {
false
}
default fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
where
BK: Ord + ?Sized,
Self::Key: Borrow<BK>,
{
slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key))
}
default fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
slice.binary_search_by(|value| value.0.cmp(&key.0))
}
fn cmp_keys<BK>(&self, other: &BK) -> Ordering
where
BK: Ord + ?Sized,
Self::Key: Borrow<BK>,
{
Self::Key::borrow(&self.0).cmp(other)
}
fn cmp_values(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0)
}
}
#[cfg(has_specialisation)]
impl<K: Ord + Copy, V> BTreeValue for (K, V) {
fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
where
BK: Ord + ?Sized,
Self::Key: Borrow<BK>,
{
linear_search_by(slice, |value| Self::Key::borrow(&value.0).cmp(key))
}
fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
linear_search_by(slice, |value| value.0.cmp(&key.0))
}
}
def_pool!(OrdMapPool<K, V>, Node<(K, V)>);
/// An ordered map.
///
/// An immutable ordered map implemented as a B-tree.
///
/// Most operations on this type of map are O(log n). A
/// [`HashMap`][hashmap::HashMap] is usually a better choice for
/// performance, but the `OrdMap` has the advantage of only requiring
/// an [`Ord`][std::cmp::Ord] constraint on the key, and of being
/// ordered, so that keys always come out from lowest to highest,
/// where a [`HashMap`][hashmap::HashMap] has no guaranteed ordering.
///
/// [hashmap::HashMap]: ../hashmap/struct.HashMap.html
/// [std::cmp::Ord]: https://doc.rust-lang.org/std/cmp/trait.Ord.html
pub struct OrdMap<K, V> {
size: usize,
pool: OrdMapPool<K, V>,
root: PoolRef<Node<(K, V)>>,
}
impl<K, V> OrdMap<K, V> {
/// Construct an empty map.
#[must_use]
pub fn new() -> Self {
let pool = OrdMapPool::default();
let root = PoolRef::default(&pool.0);
OrdMap {
size: 0,
pool,
root,
}
}
/// Construct an empty map using a specific memory pool.
#[cfg(feature = "pool")]
#[must_use]
pub fn with_pool(pool: &OrdMapPool<K, V>) -> Self {
let root = PoolRef::default(&pool.0);
OrdMap {
size: 0,
pool: pool.clone(),
root,
}
}
/// Construct a map with a single mapping.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// let map = OrdMap::unit(123, "onetwothree");
/// assert_eq!(
/// map.get(&123),
/// Some(&"onetwothree")
/// );
/// ```
#[inline]
#[must_use]
pub fn unit(key: K, value: V) -> Self {
let pool = OrdMapPool::default();
let root = PoolRef::new(&pool.0, Node::unit((key, value)));
OrdMap {
size: 1,
pool,
root,
}
}
/// Test whether a map is empty.
///
/// Time: O(1)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// assert!(
/// !ordmap!{1 => 2}.is_empty()
/// );
/// assert!(
/// OrdMap::<i32, i32>::new().is_empty()
/// );
/// ```
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Test whether two maps refer to the same content in memory.
///
/// This is true if the two sides are references to the same map,
/// or if the two maps refer to the same root node.
///
/// This would return true if you're comparing a map to itself, or
/// if you're comparing a map to a fresh clone of itself.
///
/// Time: O(1)
pub fn ptr_eq(&self, other: &Self) -> bool {
std::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root)
}
/// Get the size of a map.
///
/// Time: O(1)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// assert_eq!(3, ordmap!{
/// 1 => 11,
/// 2 => 22,
/// 3 => 33
/// }.len());
/// ```
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.size
}
/// Get a reference to the memory pool used by this map.
///
/// Note that if you didn't specifically construct it with a pool, you'll
/// get back a reference to a pool of size 0.
#[cfg(feature = "pool")]
pub fn pool(&self) -> &OrdMapPool<K, V> {
&self.pool
}
/// Discard all elements from the map.
///
/// This leaves you with an empty map, and all elements that
/// were previously inside it are dropped.
///
/// Time: O(n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::OrdMap;
/// let mut map = ordmap![1=>1, 2=>2, 3=>3];
/// map.clear();
/// assert!(map.is_empty());
/// ```
pub fn clear(&mut self) {
if !self.is_empty() {
self.root = PoolRef::default(&self.pool.0);
self.size = 0;
}
}
}
impl<K, V> OrdMap<K, V>
where
K: Ord,
{
/// Get the largest key in a map, along with its value. If the map
/// is empty, return `None`.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// assert_eq!(Some(&(3, 33)), ordmap!{
/// 1 => 11,
/// 2 => 22,
/// 3 => 33
/// }.get_max());
/// ```
#[must_use]
pub fn get_max(&self) -> Option<&(K, V)> {
self.root.max()
}
/// Get the smallest key in a map, along with its value. If the
/// map is empty, return `None`.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// assert_eq!(Some(&(1, 11)), ordmap!{
/// 1 => 11,
/// 2 => 22,
/// 3 => 33
/// }.get_min());
/// ```
#[must_use]
pub fn get_min(&self) -> Option<&(K, V)> {
self.root.min()
}
/// Get an iterator over the key/value pairs of a map.
#[must_use]
pub fn iter(&self) -> Iter<'_, K, V> {
Iter {
it: RangedIter::new(&self.root, self.size, ..),
}
}
/// Create an iterator over a range of key/value pairs.
#[must_use]
pub fn range<R, BK>(&self, range: R) -> Iter<'_, K, V>
where
R: RangeBounds<BK>,
K: Borrow<BK>,
BK: Ord + ?Sized,
{
Iter {
it: RangedIter::new(&self.root, self.size, range),
}
}
/// Get an iterator over a map's keys.
#[must_use]
pub fn keys(&self) -> Keys<'_, K, V> {
Keys { it: self.iter() }
}
/// Get an iterator over a map's values.
#[must_use]
pub fn values(&self) -> Values<'_, K, V> {
Values { it: self.iter() }
}
/// Get an iterator over the differences between this map and
/// another, i.e. the set of entries to add, update, or remove to
/// this map in order to make it equal to the other map.
///
/// This function will avoid visiting nodes which are shared
/// between the two maps, meaning that even very large maps can be
/// compared quickly if most of their structure is shared.
///
/// Time: O(n) (where n is the number of unique elements across
/// the two maps, minus the number of elements belonging to nodes
/// shared between them)
#[must_use]
pub fn diff<'a>(&'a self, other: &'a Self) -> DiffIter<'a, K, V> {
DiffIter {
it: NodeDiffIter::new(&self.root, &other.root),
}
}
/// Get the value for a key from a map.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// let map = ordmap!{123 => "lol"};
/// assert_eq!(
/// map.get(&123),
/// Some(&"lol")
/// );
/// ```
#[must_use]
pub fn get<BK>(&self, key: &BK) -> Option<&V>
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
self.root.lookup(key).map(|(_, v)| v)
}
/// Get the key/value pair for a key from a map.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// let map = ordmap!{123 => "lol"};
/// assert_eq!(
/// map.get_key_value(&123),
/// Some((&123, &"lol"))
/// );
/// ```
#[must_use]
pub fn get_key_value<BK>(&self, key: &BK) -> Option<(&K, &V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
self.root.lookup(key).map(|&(ref k, ref v)| (k, v))
}
/// Get the closest smaller entry in a map to a given key
/// as a mutable reference.
///
/// If the map contains the given key, this is returned.
/// Otherwise, the closest key in the map smaller than the
/// given value is returned. If the smallest key in the map
/// is larger than the given key, `None` is returned.
///
/// # Examples
///
/// ```rust
/// # #[macro_use] extern crate im;
/// # use im::OrdMap;
/// let map = ordmap![1 => 1, 3 => 3, 5 => 5];
/// assert_eq!(Some((&3, &3)), map.get_prev(&4));
/// ```
#[must_use]
pub fn get_prev<BK>(&self, key: &BK) -> Option<(&K, &V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
self.root.lookup_prev(key).map(|(k, v)| (k, v))
}
/// Get the closest larger entry in a map to a given key
/// as a mutable reference.
///
/// If the set contains the given value, this is returned.
/// Otherwise, the closest value in the set larger than the
/// given value is returned. If the largest value in the set
/// is smaller than the given value, `None` is returned.
///
/// # Examples
///
/// ```rust
/// # #[macro_use] extern crate im;
/// # use im::OrdMap;
/// let map = ordmap![1 => 1, 3 => 3, 5 => 5];
/// assert_eq!(Some((&5, &5)), map.get_next(&4));
/// ```
#[must_use]
pub fn get_next<BK>(&self, key: &BK) -> Option<(&K, &V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
self.root.lookup_next(key).map(|(k, v)| (k, v))
}
/// Test for the presence of a key in a map.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// let map = ordmap!{123 => "lol"};
/// assert!(
/// map.contains_key(&123)
/// );
/// assert!(
/// !map.contains_key(&321)
/// );
/// ```
#[must_use]
pub fn contains_key<BK>(&self, k: &BK) -> bool
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
self.get(k).is_some()
}
/// Test whether a map is a submap of another map, meaning that
/// all keys in our map must also be in the other map, with the
/// same values.
///
/// Use the provided function to decide whether values are equal.
///
/// Time: O(n log n)
#[must_use]
pub fn is_submap_by<B, RM, F>(&self, other: RM, mut cmp: F) -> bool
where
F: FnMut(&V, &B) -> bool,
RM: Borrow<OrdMap<K, B>>,
{
self.iter()
.all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false))
}
/// Test whether a map is a proper submap of another map, meaning
/// that all keys in our map must also be in the other map, with
/// the same values. To be a proper submap, ours must also contain
/// fewer keys than the other map.
///
/// Use the provided function to decide whether values are equal.
///
/// Time: O(n log n)
#[must_use]
pub fn is_proper_submap_by<B, RM, F>(&self, other: RM, cmp: F) -> bool
where
F: FnMut(&V, &B) -> bool,
RM: Borrow<OrdMap<K, B>>,
{
self.len() != other.borrow().len() && self.is_submap_by(other, cmp)
}
/// Test whether a map is a submap of another map, meaning that
/// all keys in our map must also be in the other map, with the
/// same values.
///
/// Time: O(n log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// let map1 = ordmap!{1 => 1, 2 => 2};
/// let map2 = ordmap!{1 => 1, 2 => 2, 3 => 3};
/// assert!(map1.is_submap(map2));
/// ```
#[must_use]
pub fn is_submap<RM>(&self, other: RM) -> bool
where
V: PartialEq,
RM: Borrow<Self>,
{
self.is_submap_by(other.borrow(), PartialEq::eq)
}
/// Test whether a map is a proper submap of another map, meaning
/// that all keys in our map must also be in the other map, with
/// the same values. To be a proper submap, ours must also contain
/// fewer keys than the other map.
///
/// Time: O(n log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// let map1 = ordmap!{1 => 1, 2 => 2};
/// let map2 = ordmap!{1 => 1, 2 => 2, 3 => 3};
/// assert!(map1.is_proper_submap(map2));
///
/// let map3 = ordmap!{1 => 1, 2 => 2};
/// let map4 = ordmap!{1 => 1, 2 => 2};
/// assert!(!map3.is_proper_submap(map4));
/// ```
#[must_use]
pub fn is_proper_submap<RM>(&self, other: RM) -> bool
where
V: PartialEq,
RM: Borrow<Self>,
{
self.is_proper_submap_by(other.borrow(), PartialEq::eq)
}
}
impl<K, V> OrdMap<K, V>
where
K: Ord + Clone,
V: Clone,
{
/// Get a mutable reference to the value for a key from a map.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// let mut map = ordmap!{123 => "lol"};
/// if let Some(value) = map.get_mut(&123) {
/// *value = "omg";
/// }
/// assert_eq!(
/// map.get(&123),
/// Some(&"omg")
/// );
/// ```
#[must_use]
pub fn get_mut<BK>(&mut self, key: &BK) -> Option<&mut V>
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
root.lookup_mut(&self.pool.0, key).map(|(_, v)| v)
}
/// Get the closest smaller entry in a map to a given key
/// as a mutable reference.
///
/// If the map contains the given key, this is returned.
/// Otherwise, the closest key in the map smaller than the
/// given value is returned. If the smallest key in the map
/// is larger than the given key, `None` is returned.
///
/// # Examples
///
/// ```rust
/// # #[macro_use] extern crate im;
/// # use im::OrdMap;
/// let mut map = ordmap![1 => 1, 3 => 3, 5 => 5];
/// if let Some((key, value)) = map.get_prev_mut(&4) {
/// *value = 4;
/// }
/// assert_eq!(ordmap![1 => 1, 3 => 4, 5 => 5], map);
/// ```
#[must_use]
pub fn get_prev_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
let pool = &self.pool.0;
PoolRef::make_mut(pool, &mut self.root)
.lookup_prev_mut(pool, key)
.map(|(ref k, ref mut v)| (k, v))
}
/// Get the closest larger entry in a map to a given key
/// as a mutable reference.
///
/// If the set contains the given value, this is returned.
/// Otherwise, the closest value in the set larger than the
/// given value is returned. If the largest value in the set
/// is smaller than the given value, `None` is returned.
///
/// # Examples
///
/// ```rust
/// # #[macro_use] extern crate im;
/// # use im::OrdMap;
/// let mut map = ordmap![1 => 1, 3 => 3, 5 => 5];
/// if let Some((key, value)) = map.get_next_mut(&4) {
/// *value = 4;
/// }
/// assert_eq!(ordmap![1 => 1, 3 => 3, 5 => 4], map);
/// ```
#[must_use]
pub fn get_next_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
let pool = &self.pool.0;
PoolRef::make_mut(pool, &mut self.root)
.lookup_next_mut(pool, key)
.map(|(ref k, ref mut v)| (k, v))
}
/// Insert a key/value mapping into a map.
///
/// This is a copy-on-write operation, so that the parts of the
/// map's structure which are shared with other maps will be
/// safely copied before mutating.
///
/// If the map already has a mapping for the given key, the
/// previous value is overwritten.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// let mut map = ordmap!{};
/// map.insert(123, "123");
/// map.insert(456, "456");
/// assert_eq!(
/// map,
/// ordmap!{123 => "123", 456 => "456"}
/// );
/// ```
///
/// [insert]: #method.insert
#[inline]
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
let new_root = {
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
match root.insert(&self.pool.0, (key, value)) {
Insert::Replaced((_, old_value)) => return Some(old_value),
Insert::Added => {
self.size += 1;
return None;
}
Insert::Split(left, median, right) => PoolRef::new(
&self.pool.0,
Node::new_from_split(&self.pool.0, left, median, right),
),
}
};
self.size += 1;
self.root = new_root;
None
}
/// Remove a key/value mapping from a map if it exists.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// let mut map = ordmap!{123 => "123", 456 => "456"};
/// map.remove(&123);
/// map.remove(&456);
/// assert!(map.is_empty());
/// ```
///
/// [remove]: #method.remove
#[inline]
pub fn remove<BK>(&mut self, k: &BK) -> Option<V>
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
self.remove_with_key(k).map(|(_, v)| v)
}
/// Remove a key/value pair from a map, if it exists, and return
/// the removed key and value.
///
/// Time: O(log n)
pub fn remove_with_key<BK>(&mut self, k: &BK) -> Option<(K, V)>
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
let (new_root, removed_value) = {
let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
match root.remove(&self.pool.0, k) {
Remove::NoChange => return None,
Remove::Removed(pair) => {
self.size -= 1;
return Some(pair);
}
Remove::Update(pair, root) => (PoolRef::new(&self.pool.0, root), Some(pair)),
}
};
self.size -= 1;
self.root = new_root;
removed_value
}
/// Construct a new map by inserting a key/value mapping into a
/// map.
///
/// If the map already has a mapping for the given key, the
/// previous value is overwritten.
///
/// Time: O(log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// let map = ordmap!{};
/// assert_eq!(
/// map.update(123, "123"),
/// ordmap!{123 => "123"}
/// );
/// ```
#[must_use]
pub fn update(&self, key: K, value: V) -> Self {
let mut out = self.clone();
out.insert(key, value);
out
}
/// Construct a new map by inserting a key/value mapping into a
/// map.
///
/// If the map already has a mapping for the given key, we call
/// the provided function with the old value and the new value,
/// and insert the result as the new value.
///
/// Time: O(log n)
#[must_use]
pub fn update_with<F>(self, k: K, v: V, f: F) -> Self
where
F: FnOnce(V, V) -> V,
{
self.update_with_key(k, v, |_, v1, v2| f(v1, v2))
}
/// Construct a new map by inserting a key/value mapping into a
/// map.
///
/// If the map already has a mapping for the given key, we call
/// the provided function with the key, the old value and the new
/// value, and insert the result as the new value.
///
/// Time: O(log n)
#[must_use]
pub fn update_with_key<F>(self, k: K, v: V, f: F) -> Self
where
F: FnOnce(&K, V, V) -> V,
{
match self.extract_with_key(&k) {
None => self.update(k, v),
Some((_, v2, m)) => {
let out_v = f(&k, v2, v);
m.update(k, out_v)
}
}
}
/// Construct a new map by inserting a key/value mapping into a
/// map, returning the old value for the key as well as the new
/// map.
///
/// If the map already has a mapping for the given key, we call
/// the provided function with the key, the old value and the new
/// value, and insert the result as the new value.
///
/// Time: O(log n)
#[must_use]
pub fn update_lookup_with_key<F>(self, k: K, v: V, f: F) -> (Option<V>, Self)
where
F: FnOnce(&K, &V, V) -> V,
{
match self.extract_with_key(&k) {
None => (None, self.update(k, v)),
Some((_, v2, m)) => {
let out_v = f(&k, &v2, v);
(Some(v2), m.update(k, out_v))
}
}
}
/// Update the value for a given key by calling a function with
/// the current value and overwriting it with the function's
/// return value.
///
/// The function gets an [`Option<V>`][std::option::Option] and
/// returns the same, so that it can decide to delete a mapping
/// instead of updating the value, and decide what to do if the
/// key isn't in the map.
///
/// Time: O(log n)
///
/// [std::option::Option]: https://doc.rust-lang.org/std/option/enum.Option.html
#[must_use]
pub fn alter<F>(&self, f: F, k: K) -> Self
where
F: FnOnce(Option<V>) -> Option<V>,
{
let pop = self.extract_with_key(&k);
match (f(pop.as_ref().map(|&(_, ref v, _)| v.clone())), pop) {
(None, None) => self.clone(),
(Some(v), None) => self.update(k, v),
(None, Some((_, _, m))) => m,
(Some(v), Some((_, _, m))) => m.update(k, v),
}
}
/// Remove a key/value pair from a map, if it exists.
///
/// Time: O(log n)
#[must_use]
pub fn without<BK>(&self, k: &BK) -> Self
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
self.extract(k)
.map(|(_, m)| m)
.unwrap_or_else(|| self.clone())
}
/// Remove a key/value pair from a map, if it exists, and return
/// the removed value as well as the updated list.
///
/// Time: O(log n)
#[must_use]
pub fn extract<BK>(&self, k: &BK) -> Option<(V, Self)>
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
self.extract_with_key(k).map(|(_, v, m)| (v, m))
}
/// Remove a key/value pair from a map, if it exists, and return
/// the removed key and value as well as the updated list.
///
/// Time: O(log n)
#[must_use]
pub fn extract_with_key<BK>(&self, k: &BK) -> Option<(K, V, Self)>
where
BK: Ord + ?Sized,
K: Borrow<BK>,
{
let mut out = self.clone();
let result = out.remove_with_key(k);
result.map(|(k, v)| (k, v, out))
}
/// Construct the union of two maps, keeping the values in the
/// current map when keys exist in both maps.
///
/// Time: O(n log n)
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate im;
/// # use im::ordmap::OrdMap;
/// let map1 = ordmap!{1 => 1, 3 => 3};
/// let map2 = ordmap!{2 => 2, 3 => 4};
/// let expected = ordmap!{1 => 1, 2 => 2, 3 => 3};
/// assert_eq!(expected, map1.union(map2));
/// ```
#[inline]
#[must_use]
pub fn union(mut self, other: Self) -> Self {
for (k, v) in other {
self.entry(k).or_insert(v);
}
self
}
/// Construct the union of two maps, using a function to decide
/// what to do with the value when a key is in both maps.
///
/// The function is called when a value exists in both maps, and
/// receives the value from the current map as its first argument,
/// and the value from the other map as the second. It should
/// return the value to be inserted in the resulting map.
///
/// Time: O(n log n)
#[inline]