mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
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
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
//! [`VecMap`] and [`VecSet`]: ordered maps and sets kept as sorted vectors,
//! for small maps.
//!
//! They iterate in key order, as [`BTreeMap`](std::collections::BTreeMap)
//! and [`BTreeSet`](std::collections::BTreeSet) do, and have the part of
//! their API mln-rs uses. A `BTreeMap` is a lot of code for each key and
//! value type it is used with; these are a binary search over a slice and a
//! `Vec` insert or remove. The keys are a vector of their own, so the search
//! is one function for each key type, whatever the values. Insert and remove
//! move the entries after the position, so a map that grows large by inserts
//! in no particular order is still better off as a `BTreeMap`. An insert past
//! the last key is a push.

use std::borrow::Borrow;
use std::fmt;
use std::ops::Index;
#[cfg(test)]
use std::ops::{Bound, RangeBounds};

/// The position of `key` in the sorted `keys`, or where it would go.
fn search<K: Borrow<Q>, Q: Ord + ?Sized>(keys: &[K], key: &Q) -> Result<usize, usize> {
    // An insert past the last key is the common case of building a map in
    // order, so check that first.
    match keys.last() {
        None => return Err(0),
        Some(last) if last.borrow() < key => return Err(keys.len()),
        _ => {}
    }
    keys.binary_search_by(|k| k.borrow().cmp(key))
}

/// The positions in the sorted `keys` that `range` spans.
#[cfg(test)]
fn range_bounds<K: Borrow<Q>, Q: Ord + ?Sized, R: RangeBounds<Q>>(keys: &[K], range: &R) -> std::ops::Range<usize> {
    let start = match range.start_bound() {
        Bound::Included(q) => keys.partition_point(|k| k.borrow() < q),
        Bound::Excluded(q) => keys.partition_point(|k| k.borrow() <= q),
        Bound::Unbounded => 0,
    };
    let end = match range.end_bound() {
        Bound::Included(q) => keys.partition_point(|k| k.borrow() <= q),
        Bound::Excluded(q) => keys.partition_point(|k| k.borrow() < q),
        Bound::Unbounded => keys.len(),
    };
    // BTreeMap panics on a range that ends before it starts.
    assert!(start <= end, "range start is greater than range end");
    start..end
}

/// An ordered map kept as sorted vectors of keys and of values (module docs).
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct VecMap<K, V> {
    keys: Vec<K>,
    values: Vec<V>,
}

/// [`VecMap::iter`].
pub(crate) type Iter<'a, K, V> = std::iter::Zip<std::slice::Iter<'a, K>, std::slice::Iter<'a, V>>;
/// [`VecMap::iter_mut`].
pub(crate) type IterMut<'a, K, V> = std::iter::Zip<std::slice::Iter<'a, K>, std::slice::IterMut<'a, V>>;
/// [`VecMap::into_iter`].
pub type IntoIter<K, V> = std::iter::Zip<std::vec::IntoIter<K>, std::vec::IntoIter<V>>;

impl<K, V> Default for VecMap<K, V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for VecMap<K, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_map().entries(self.iter()).finish()
    }
}

impl<K, V> VecMap<K, V> {
    #[must_use]
    pub const fn new() -> Self {
        VecMap { keys: Vec::new(), values: Vec::new() }
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.keys.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.keys.is_empty()
    }

    pub fn clear(&mut self) {
        self.keys.clear();
        self.values.clear();
    }

    pub fn iter(&self) -> Iter<'_, K, V> {
        self.keys.iter().zip(self.values.iter())
    }

    pub(crate) fn iter_mut(&mut self) -> IterMut<'_, K, V> {
        self.keys.iter().zip(self.values.iter_mut())
    }

    pub fn keys(&self) -> std::slice::Iter<'_, K> {
        self.keys.iter()
    }

    pub fn values(&self) -> std::slice::Iter<'_, V> {
        self.values.iter()
    }

    /// The entry at `index` in key order.
    #[must_use]
    pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
        Some((self.keys.get(index)?, self.values.get(index)?))
    }

    /// The entry at `index` in key order.
    pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
        Some((self.keys.get(index)?, self.values.get_mut(index)?))
    }

    pub fn values_mut(&mut self) -> std::slice::IterMut<'_, V> {
        self.values.iter_mut()
    }

    #[cfg(test)]
    #[must_use]
    pub(crate) fn first_key_value(&self) -> Option<(&K, &V)> {
        Some((self.keys.first()?, self.values.first()?))
    }

    #[cfg(test)]
    #[must_use]
    pub(crate) fn last_key_value(&self) -> Option<(&K, &V)> {
        Some((self.keys.last()?, self.values.last()?))
    }

    /// Keeps the entries for which `f` returns true, visiting them in key
    /// order.
    pub fn retain(&mut self, mut f: impl FnMut(&K, &mut V) -> bool) {
        let mut kept = 0;
        for i in 0..self.keys.len() {
            if f(&self.keys[i], &mut self.values[i]) {
                self.keys.swap(kept, i);
                self.values.swap(kept, i);
                kept += 1;
            }
        }
        self.keys.truncate(kept);
        self.values.truncate(kept);
    }
}

impl<K: Ord, V> VecMap<K, V> {
    fn search<Q: Ord + ?Sized>(&self, key: &Q) -> Result<usize, usize>
    where
        K: Borrow<Q>,
    {
        search(&self.keys, key)
    }

    pub fn get<Q: Ord + ?Sized>(&self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
    {
        self.search(key).ok().map(|i| &self.values[i])
    }

    pub fn get_mut<Q: Ord + ?Sized>(&mut self, key: &Q) -> Option<&mut V>
    where
        K: Borrow<Q>,
    {
        self.search(key).ok().map(|i| &mut self.values[i])
    }

    /// The position of `key`'s entry in key order, which stays its position
    /// until an entry is inserted or removed.
    #[must_use]
    pub fn index_of<Q: Ord + ?Sized>(&self, key: &Q) -> Option<usize>
    where
        K: Borrow<Q>,
    {
        self.search(key).ok()
    }

    pub fn contains_key<Q: Ord + ?Sized>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
    {
        self.search(key).is_ok()
    }

    /// Like `BTreeMap::insert`, keeps the key already in the map when there
    /// is one.
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        match self.search(&key) {
            Ok(i) => Some(std::mem::replace(&mut self.values[i], value)),
            Err(i) => {
                self.insert_at(i, key, value);
                None
            }
        }
    }

    fn insert_at(&mut self, i: usize, key: K, value: V) {
        if i == self.keys.len() {
            self.keys.push(key);
            self.values.push(value);
        } else {
            self.keys.insert(i, key);
            self.values.insert(i, value);
        }
    }

    pub fn remove<Q: Ord + ?Sized>(&mut self, key: &Q) -> Option<V>
    where
        K: Borrow<Q>,
    {
        self.remove_entry(key).map(|(_, v)| v)
    }

    pub(crate) fn remove_entry<Q: Ord + ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
    where
        K: Borrow<Q>,
    {
        let i = self.search(key).ok()?;
        Some((self.keys.remove(i), self.values.remove(i)))
    }

    /// The value of `key`, which is `value()`, under `key.to_owned()`, where
    /// the map has none. Unlike [`entry`](Self::entry), it makes an owned
    /// key only for an entry it inserts.
    pub fn get_or_insert_with<Q>(&mut self, key: &Q, value: impl FnOnce() -> V) -> &mut V
    where
        K: Borrow<Q>,
        Q: Ord + ToOwned<Owned = K> + ?Sized,
    {
        let i = match self.search(key) {
            Ok(i) => i,
            Err(i) => {
                self.insert_at(i, key.to_owned(), value());
                i
            }
        };
        &mut self.values[i]
    }

    pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
        match self.search(&key) {
            Ok(index) => Entry::Occupied(OccupiedEntry { map: self, index }),
            Err(index) => Entry::Vacant(VacantEntry { map: self, index, key }),
        }
    }

    /// The entries whose keys are in `range`, in key order.
    #[cfg(test)]
    pub(crate) fn range<Q: Ord + ?Sized, R: RangeBounds<Q>>(&self, range: R) -> Iter<'_, K, V>
    where
        K: Borrow<Q>,
    {
        let r = range_bounds(&self.keys, &range);
        self.keys[r.clone()].iter().zip(self.values[r].iter())
    }

    /// Moves every entry of `other` into this map, `other`'s value winning
    /// for a key both have, as `BTreeMap::append` does.
    #[cfg(test)]
    pub(crate) fn append(&mut self, other: &mut Self) {
        let keys = std::mem::take(&mut other.keys);
        let values = std::mem::take(&mut other.values);
        self.extend(keys.into_iter().zip(values));
    }
}

impl<K: Ord, V> Extend<(K, V)> for VecMap<K, V> {
    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        let (additional, _) = iter.size_hint();
        self.keys.reserve(additional);
        self.values.reserve(additional);
        for (k, v) in iter {
            self.insert(k, v);
        }
    }
}

impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for VecMap<K, V> {
    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
        self.extend(iter.into_iter().map(|(k, v)| (*k, *v)));
    }
}

/// [`VecMap::entry`].
pub enum Entry<'a, K, V> {
    Occupied(OccupiedEntry<'a, K, V>),
    Vacant(VacantEntry<'a, K, V>),
}

/// An [`Entry`] whose key is in the map.
pub struct OccupiedEntry<'a, K, V> {
    map: &'a mut VecMap<K, V>,
    index: usize,
}

/// An [`Entry`] whose key is not in the map.
pub struct VacantEntry<'a, K, V> {
    map: &'a mut VecMap<K, V>,
    index: usize,
    key: K,
}

impl<'a, K: Ord, V> Entry<'a, K, V> {
    pub fn or_insert_with(self, f: impl FnOnce() -> V) -> &'a mut V {
        match self {
            Entry::Occupied(e) => e.into_mut(),
            Entry::Vacant(e) => e.insert(f()),
        }
    }

    pub fn or_insert(self, value: V) -> &'a mut V {
        self.or_insert_with(|| value)
    }

    pub fn or_default(self) -> &'a mut V
    where
        V: Default,
    {
        self.or_insert_with(V::default)
    }
}

impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
    pub(crate) fn get_mut(&mut self) -> &mut V {
        &mut self.map.values[self.index]
    }

    #[must_use]
    pub(crate) fn into_mut(self) -> &'a mut V {
        &mut self.map.values[self.index]
    }

    pub fn insert(&mut self, value: V) -> V {
        std::mem::replace(self.get_mut(), value)
    }
}

impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
    pub fn insert(self, value: V) -> &'a mut V {
        self.map.insert_at(self.index, self.key, value);
        &mut self.map.values[self.index]
    }
}

impl<K: Ord, V> FromIterator<(K, V)> for VecMap<K, V> {
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        let mut map = VecMap::new();
        map.extend(iter);
        map
    }
}

impl<K: Ord, V, const N: usize> From<[(K, V); N]> for VecMap<K, V> {
    fn from(entries: [(K, V); N]) -> Self {
        entries.into_iter().collect()
    }
}

impl<K, V> IntoIterator for VecMap<K, V> {
    type Item = (K, V);
    type IntoIter = IntoIter<K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.keys.into_iter().zip(self.values)
    }
}

impl<'a, K, V> IntoIterator for &'a VecMap<K, V> {
    type Item = (&'a K, &'a V);
    type IntoIter = Iter<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, K, V> IntoIterator for &'a mut VecMap<K, V> {
    type Item = (&'a K, &'a mut V);
    type IntoIter = IterMut<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

/// Panics when `key` is not in the map, as `BTreeMap`'s `Index` does.
impl<K: Ord + Borrow<Q>, Q: Ord + ?Sized, V> Index<&Q> for VecMap<K, V> {
    type Output = V;

    /// Panics on a missing key, as `BTreeMap`'s `Index` does (with its
    /// message): the panic site those lookups had inside std, now here.
    fn index(&self, key: &Q) -> &V {
        self.get(key).expect("no entry found for key")
    }
}

impl<K: mln_wire::Wire + Ord, V: mln_wire::Wire> mln_wire::Wire for VecMap<K, V> {
    fn write(&self, w: &mut mln_wire::Writer) {
        self.len().write(w);
        for (k, v) in self {
            k.write(w);
            v.write(w);
        }
    }

    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
        let len = r.length()?;
        let mut map = VecMap::new();
        for _ in 0..len {
            let k = K::read(r)?;
            map.insert(k, V::read(r)?);
        }
        Some(map)
    }
}

/// An ordered set kept as a sorted vector (module docs).
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VecSet<T> {
    items: Vec<T>,
}

impl<T> Default for VecSet<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: fmt::Debug> fmt::Debug for VecSet<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.iter()).finish()
    }
}

impl<T> VecSet<T> {
    #[must_use]
    pub const fn new() -> Self {
        VecSet { items: Vec::new() }
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.items.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    pub fn clear(&mut self) {
        self.items.clear();
    }

    pub fn iter(&self) -> std::slice::Iter<'_, T> {
        self.items.iter()
    }

    #[cfg(test)]
    #[must_use]
    pub(crate) fn first(&self) -> Option<&T> {
        self.items.first()
    }
}

impl<T: Ord> VecSet<T> {
    pub fn contains<Q: Ord + ?Sized>(&self, value: &Q) -> bool
    where
        T: Borrow<Q>,
    {
        search(&self.items, value).is_ok()
    }

    /// Like `BTreeSet::insert`, keeps the item already in the set when there
    /// is one, and returns whether `value` was new.
    pub fn insert(&mut self, value: T) -> bool {
        match search(&self.items, &value) {
            Ok(_) => false,
            Err(i) if i == self.items.len() => {
                self.items.push(value);
                true
            }
            Err(i) => {
                self.items.insert(i, value);
                true
            }
        }
    }

    pub fn remove<Q: Ord + ?Sized>(&mut self, value: &Q) -> bool
    where
        T: Borrow<Q>,
    {
        self.take(value).is_some()
    }

    pub(crate) fn take<Q: Ord + ?Sized>(&mut self, value: &Q) -> Option<T>
    where
        T: Borrow<Q>,
    {
        let i = search(&self.items, value).ok()?;
        Some(self.items.remove(i))
    }

    /// The items in `range`, in order.
    #[cfg(test)]
    pub(crate) fn range<Q: Ord + ?Sized, R: RangeBounds<Q>>(&self, range: R) -> std::slice::Iter<'_, T>
    where
        T: Borrow<Q>,
    {
        self.items[range_bounds(&self.items, &range)].iter()
    }

    /// The items of this set that are not in `other`, in order.
    #[cfg(test)]
    pub(crate) fn difference<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = &'a T> + 'a {
        self.iter().filter(move |item| !other.contains(*item))
    }

    /// The items in both sets, in order.
    #[cfg(test)]
    pub(crate) fn intersection<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = &'a T> + 'a {
        self.iter().filter(move |item| other.contains(*item))
    }

    #[cfg(test)]
    #[must_use]
    pub(crate) fn is_disjoint(&self, other: &Self) -> bool {
        self.intersection(other).next().is_none()
    }
}

impl<T: Ord> Extend<T> for VecSet<T> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        for item in iter {
            self.insert(item);
        }
    }
}

impl<'a, T: Ord + Copy + 'a> Extend<&'a T> for VecSet<T> {
    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
        self.extend(iter.into_iter().copied());
    }
}

impl<T: Ord> FromIterator<T> for VecSet<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut set = VecSet::new();
        set.extend(iter);
        set
    }
}

impl<T: Ord, const N: usize> From<[T; N]> for VecSet<T> {
    fn from(items: [T; N]) -> Self {
        items.into_iter().collect()
    }
}

impl<T> IntoIterator for VecSet<T> {
    type Item = T;
    type IntoIter = std::vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.items.into_iter()
    }
}

impl<'a, T> IntoIterator for &'a VecSet<T> {
    type Item = &'a T;
    type IntoIter = std::slice::Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<T: mln_wire::Wire + Ord> mln_wire::Wire for VecSet<T> {
    fn write(&self, w: &mut mln_wire::Writer) {
        mln_wire::write_seq(w, &self.items);
    }

    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
        Some(mln_wire::read_seq::<T>(r)?.into_iter().collect())
    }
}

#[cfg(test)]
mod tests {
    use std::collections::{BTreeMap, BTreeSet};

    use super::*;

    // A small deterministic generator, so the tests need no dependency.
    fn keys(n: usize, seed: u64) -> Vec<u32> {
        let mut x = seed;
        (0..n)
            .map(|_| {
                x ^= x << 13;
                x ^= x >> 7;
                x ^= x << 17;
                (x % 64) as u32
            })
            .collect()
    }

    #[test]
    fn map_matches_btree_map() {
        for seed in 1..20 {
            let mut vec_map = VecMap::new();
            let mut btree_map = BTreeMap::new();
            for (i, k) in keys(200, seed).into_iter().enumerate() {
                match i % 5 {
                    0..=2 => assert_eq!(vec_map.insert(k, i), btree_map.insert(k, i)),
                    3 => assert_eq!(vec_map.remove(&k), btree_map.remove(&k)),
                    _ => {
                        *vec_map.entry(k).or_insert(0) += i;
                        *btree_map.entry(k).or_insert(0) += i;
                    }
                }
                assert_eq!(vec_map.get(&k), btree_map.get(&k));
            }
            assert!(vec_map.iter().eq(btree_map.iter()));
            assert!(vec_map.range(10..40).eq(btree_map.range(10..40)));
            assert!(vec_map.range(..=20).eq(btree_map.range(..=20)));
            assert!(
                vec_map
                    .range((Bound::Excluded(5), Bound::Unbounded))
                    .eq(btree_map.range((Bound::Excluded(5), Bound::Unbounded)))
            );
            vec_map.retain(|k, v| !(k + *v as u32).is_multiple_of(3));
            btree_map.retain(|k, v| !(k + *v as u32).is_multiple_of(3));
            assert!(vec_map.iter().eq(btree_map.iter()));
            assert_eq!(vec_map.first_key_value(), btree_map.first_key_value());
            assert_eq!(vec_map.last_key_value(), btree_map.last_key_value());
            let mut other: VecMap<u32, usize> = keys(30, seed + 100).into_iter().map(|k| (k, 7)).collect();
            let mut btree_other: BTreeMap<u32, usize> = keys(30, seed + 100).into_iter().map(|k| (k, 7)).collect();
            vec_map.append(&mut other);
            btree_map.append(&mut btree_other);
            assert!(other.is_empty());
            assert!(vec_map.into_iter().eq(btree_map));
        }
    }

    #[test]
    fn set_matches_btree_set() {
        for seed in 1..20 {
            let mut vec_set = VecSet::new();
            let mut btree_set = BTreeSet::new();
            for (i, k) in keys(200, seed).into_iter().enumerate() {
                if i % 3 == 2 {
                    assert_eq!(vec_set.remove(&k), btree_set.remove(&k));
                } else {
                    assert_eq!(vec_set.insert(k), btree_set.insert(k));
                }
                assert_eq!(vec_set.contains(&k), btree_set.contains(&k));
            }
            assert!(vec_set.iter().eq(btree_set.iter()));
            assert!(vec_set.range(10..40).eq(btree_set.range(10..40)));
            let other: VecSet<u32> = keys(30, seed + 100).into_iter().collect();
            let btree_other: BTreeSet<u32> = keys(30, seed + 100).into_iter().collect();
            assert!(vec_set.difference(&other).eq(btree_set.difference(&btree_other)));
            assert!(vec_set.intersection(&other).eq(btree_set.intersection(&btree_other)));
            assert_eq!(vec_set.is_disjoint(&other), btree_set.is_disjoint(&btree_other));
        }
    }

    #[test]
    fn index_finds_the_value() {
        let map: VecMap<String, u32> = [("b".to_owned(), 2), ("a".to_owned(), 1)].into();
        assert_eq!(map["a"], 1);
        assert_eq!(map["b"], 2);
    }

    #[test]
    fn get_or_insert_with_inserts_only_a_missing_key() {
        let mut map: VecMap<String, u32> = [("b".to_owned(), 2)].into();
        *map.get_or_insert_with("b", || unreachable!()) += 1;
        *map.get_or_insert_with("a", || 10) += 1;
        assert!(map.iter().eq([(&"a".to_owned(), &11), (&"b".to_owned(), &3)]));
    }

    #[test]
    #[should_panic(expected = "no entry found for key")]
    fn index_panics_on_a_missing_key() {
        let map: VecMap<String, u32> = [("a".to_owned(), 1)].into();
        let _ = map["c"];
    }

    #[test]
    fn insert_keeps_the_first_key() {
        // Keys that compare equal but differ: BTreeMap keeps the first.
        #[derive(Debug)]
        struct K(u32, &'static str);
        impl PartialEq for K {
            fn eq(&self, other: &Self) -> bool {
                self.0 == other.0
            }
        }
        impl Eq for K {}
        impl PartialOrd for K {
            fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
                Some(self.cmp(other))
            }
        }
        impl Ord for K {
            fn cmp(&self, other: &Self) -> std::cmp::Ordering {
                self.0.cmp(&other.0)
            }
        }
        let mut map = VecMap::new();
        map.insert(K(1, "first"), 1);
        assert_eq!(map.insert(K(1, "second"), 2), Some(1));
        assert_eq!(map.first_key_value().map(|(k, v)| (k.1, *v)), Some(("first", 2)));
        let mut set = VecSet::new();
        assert!(set.insert(K(1, "first")));
        assert!(!set.insert(K(1, "second")));
        assert_eq!(set.first().map(|k| k.1), Some("first"));
    }
}