seq-map 0.0.15

Sequential Map
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
/*
 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/piot/seq-map
 * Licensed under the MIT License. See LICENSE in the project root for license information.
 */

use std::{
    borrow::Borrow,
    collections::HashMap,
    error::Error,
    fmt::{self, Debug, Display, Formatter},
    hash::{Hash, Hasher},
    ops::Index,
};

/// A deterministic map that preserves insertion order.
///
/// Internally, it uses a [`HashMap`] for quick key lookups and a [`Vec`] to maintain the order
/// of inserted key-value pairs.
#[derive(Clone)]
pub struct SeqMap<K, V> {
    key_to_index: HashMap<K, usize>, // Maps keys to their index in `entries`
    entries: Vec<(K, V)>,            // Stores key-value pairs in insertion order
}

impl<K, V> Hash for SeqMap<K, V>
where
    K: Hash,
    V: Hash,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        for (key, value) in &self.entries {
            key.hash(state);
            value.hash(state);
        }
    }
}

impl<K, V> PartialEq for SeqMap<K, V>
where
    K: Eq,
    V: Eq,
{
    fn eq(&self, other: &Self) -> bool {
        if self.entries.len() != other.entries.len() {
            return false;
        }
        self.entries
            .iter()
            .zip(other.entries.iter())
            .all(|(a, b)| a == b)
    }
}

impl<K, V> Eq for SeqMap<K, V>
where
    K: Eq,
    V: Eq,
{
}

impl<K, V> Display for SeqMap<K, V>
where
    K: Eq + Hash + Display,
    V: Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "SeqMap({})", self.entries.len())?;
        for (key, value) in &self.entries {
            write!(f, "\n{key}: {value}")?;
        }
        Ok(())
    }
}

impl<K, V> Debug for SeqMap<K, V>
where
    K: Eq + Hash + Debug,
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "SeqMap(")?;
        let mut first = true;
        for (key, value) in &self.entries {
            if !first {
                write!(f, ", ")?;
            }
            first = false;
            write!(f, "{key:?}: {value:?}")?;
        }
        write!(f, ")")
    }
}

/// Errors that can occur when manipulating a `SeqMap`.
#[derive(Debug)]
pub enum SeqMapError {
    /// Occurs when attempting to insert a key that already exists in the map.
    KeyAlreadyExists,
}

impl Display for SeqMapError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            SeqMapError::KeyAlreadyExists => write!(f, "The key already exists in the SeqMap."),
        }
    }
}

impl Error for SeqMapError {}

impl<K, V> SeqMap<K, V>
where
    K: Eq + Hash + Clone, // Clone is because we add it to two containers
{
    /// Creates a new, empty `SeqMap`.
    ///
    /// # Examples
    ///
    /// ```
    /// use seq_map::SeqMap;
    /// let map: SeqMap<String, i32> = SeqMap::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            key_to_index: HashMap::new(),
            entries: Vec::new(),
        }
    }

    /// Inserts a key-value pair into the map.
    ///
    /// Returns an error if the key already exists.
    ///
    /// # Errors
    ///
    /// Returns `SeqMapError::KeyAlreadyExists` if the key is already present.
    ///
    /// # Examples
    ///
    /// ```
    /// use seq_map::SeqMap;
    /// let mut map = SeqMap::new();
    /// map.insert("key".to_string(), 42).unwrap();
    /// assert!(map.insert("key".to_string(), 43).is_err());
    /// ```
    pub fn insert(&mut self, key: K, value: V) -> Result<(), SeqMapError> {
        #[allow(clippy::map_entry)]
        if self.key_to_index.contains_key(&key) {
            Err(SeqMapError::KeyAlreadyExists)
        } else {
            self.entries.push((key.clone(), value));
            self.key_to_index.insert(key, self.entries.len() - 1);
            Ok(())
        }
    }

    /// Checks if the map contains a key.
    pub fn contains_key<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        self.key_to_index.contains_key(key)
    }

    /// Returns a mutable reference to the value corresponding to the key.
    ///
    /// Returns `None` if the key does not exist.
    ///
    /// # Examples
    ///
    /// ```
    /// use seq_map::SeqMap;
    /// let mut map = SeqMap::new();
    /// map.insert("key".to_string(), 42).unwrap();
    /// if let Some(value) = map.get_mut(&"key".to_string()) {
    ///     *value = 100;
    /// }
    /// assert_eq!(map[&"key".to_string()], 100);
    /// ```
    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        self.key_to_index
            .get(key)
            .map(|&index| &mut self.entries[index].1)
    }

    /// Returns the number of key-value pairs in the map.
    ///
    /// # Examples
    ///
    /// ```
    /// use seq_map::SeqMap;
    /// let mut map = SeqMap::new();
    /// assert_eq!(map.len(), 0);
    /// map.insert("key", 42).unwrap();
    /// assert_eq!(map.len(), 1);
    /// ```
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` if the map contains no elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use seq_map::SeqMap;
    /// let map: SeqMap<String, i32> = SeqMap::new();
    /// assert!(map.is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Returns an iterator over the keys of the map in insertion order.
    ///
    /// # Examples
    ///
    /// ```
    /// use seq_map::SeqMap;
    /// let mut map = SeqMap::new();
    /// map.insert("a".to_string(), 1).unwrap();
    /// map.insert("b".to_string(), 2).unwrap();
    /// let keys: Vec<_> = map.keys().cloned().collect();
    /// assert_eq!(keys, vec!["a", "b"]);
    /// ```
    pub fn keys(&self) -> impl Iterator<Item = &K> {
        self.entries.iter().map(|(k, _)| k)
    }

    /// Returns an iterator over the values of the map in insertion order.
    ///
    /// # Examples
    ///
    /// ```
    /// use seq_map::SeqMap;
    /// let mut map = SeqMap::new();
    /// map.insert("a".to_string(), 1).unwrap();
    /// map.insert("b".to_string(), 2).unwrap();
    /// let values: Vec<_> = map.values().cloned().collect();
    /// assert_eq!(values, vec![1, 2]);
    /// ```
    pub fn values(&self) -> impl Iterator<Item = &V> {
        self.entries.iter().map(|(_, v)| v)
    }

    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
        self.entries.iter_mut().map(|(_, v)| v)
    }

    pub fn get_index<Q>(&self, key: &Q) -> Option<usize>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        self.key_to_index.get(key).copied()
    }

    pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
        self.entries.iter().map(|(k, v)| (k, v))
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&K, &mut V)> {
        self.entries.iter_mut().map(|(k, v)| (&*k, v))
    }

    /// Retrieves a reference to the value corresponding to the key.
    ///
    /// This method performs a faster lookup using the internal `HashMap`.
    ///
    /// For a slower but simpler lookup, see [`slow_get`](Self::slow_get).
    ///
    /// # Examples
    ///
    /// ```
    /// use seq_map::SeqMap;
    /// let mut map = SeqMap::new();
    /// map.insert("key".to_string(), 42).unwrap();
    /// assert_eq!(map.get(&"key".to_string()), Some(&42));
    /// ```
    pub fn get<Q>(&self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        self.key_to_index
            .get(key)
            .map(|&index| &self.entries[index].1)
    }

    /// Removes all elements from the map
    pub fn clear(&mut self) {
        self.key_to_index.clear();
        self.entries.clear();
    }

    /// Removes a key from the map, returning the value if it existed
    pub fn remove(&mut self, key: &K) -> Option<V> {
        if let Some(&index) = self.key_to_index.get(key) {
            self.key_to_index.remove(key);
            // Update indices for all elements after the removed one
            for k in self.entries[index + 1..].iter().map(|(k, _)| k) {
                if let Some(idx) = self.key_to_index.get_mut(k) {
                    *idx -= 1;
                }
            }
            Some(self.entries.remove(index).1)
        } else {
            None
        }
    }

    /// Removes all elements from the map and returns them as an iterator
    pub fn drain(&mut self) -> impl Iterator<Item = (K, V)> + '_ {
        self.key_to_index.clear();
        self.entries.drain(..)
    }
}

/// An entry into a `SeqMap` which may be either vacant or occupied.
pub enum Entry<'a, K, V>
where
    K: Eq + Hash + Clone,
{
    Occupied(OccupiedEntry<'a, K, V>),
    Vacant(VacantEntry<'a, K, V>),
}

/// A view into an occupied entry in a `SeqMap`.
pub struct OccupiedEntry<'a, K, V>
where
    K: Eq + Hash + Clone,
{
    map: &'a mut SeqMap<K, V>,
    index: usize,
}

/// A view into a vacant entry in a `SeqMap`.
pub struct VacantEntry<'a, K, V>
where
    K: Eq + Hash + Clone,
{
    map: &'a mut SeqMap<K, V>,
    key: Option<K>,
}

impl<'a, K, V> Entry<'a, K, V>
where
    K: Eq + Hash + Clone,
{
    /// Inserts the value if the entry is vacant, and returns a mutable reference to the value.
    pub fn or_insert(&mut self, default: V) -> &mut V {
        match self {
            Entry::Occupied(o) => o.get_mut(),
            Entry::Vacant(v) => v.insert(default),
        }
    }

    /// Inserts the value computed by `f` if vacant, and returns a mutable reference.
    pub fn or_insert_with<F: FnOnce() -> V>(&mut self, f: F) -> &mut V {
        match self {
            Entry::Occupied(o) => o.get_mut(),
            Entry::Vacant(v) => v.insert(f()),
        }
    }

    /// Inserts `Default::default()` if vacant. Requires `V: Default`.
    pub fn or_default(&mut self) -> &mut V
    where
        V: Default,
    {
        match self {
            Entry::Occupied(o) => o.get_mut(),
            Entry::Vacant(v) => v.insert(V::default()),
        }
    }

    /// If the entry is occupied, apply the closure to its value. Returns self for chaining.
    pub fn and_modify<F: FnOnce(&mut V)>(&mut self, f: F) -> &mut Self {
        match self {
            Entry::Occupied(o) => {
                f(o.get_mut());
            }
            Entry::Vacant(_) => {}
        }
        self
    }
}

impl<'a, K, V> OccupiedEntry<'a, K, V>
where
    K: Eq + Hash + Clone,
{
    /// Gets a reference to the value in the occupied entry.
    pub fn get(&self) -> &V {
        &self.map.entries[self.index].1
    }

    /// Gets a mutable reference to the value in the occupied entry.
    pub fn get_mut(&mut self) -> &mut V {
        &mut self.map.entries[self.index].1
    }

    /// Replaces the value in the occupied entry and returns the old value.
    pub fn insert(&mut self, value: V) -> V {
        std::mem::replace(&mut self.map.entries[self.index].1, value)
    }

    /// Removes the entry and returns the value.
    pub fn remove(&mut self) -> V {
        // Clone the key to remove mapping; K: Clone is required by SeqMap impls
        let key = self.map.entries[self.index].0.clone();
        self.map.key_to_index.remove(&key);
        for k in self.map.entries[self.index + 1..].iter().map(|(k, _)| k) {
            if let Some(idx) = self.map.key_to_index.get_mut(k) {
                *idx -= 1;
            }
        }
        self.map.entries.remove(self.index).1
    }
}

impl<'a, K, V> VacantEntry<'a, K, V>
where
    K: Eq + Hash + Clone,
{
    /// Inserts the provided value into the map and returns a mutable reference to it.
    pub fn insert(&mut self, value: V) -> &mut V {
        let key = self.key.take().expect("vacant entry key missing");
        let index = self.map.entries.len();
        self.map.entries.push((key.clone(), value));
        self.map.key_to_index.insert(key, index);
        &mut self.map.entries[index].1
    }

    /// Returns a reference to the key for this vacant entry.
    pub fn key(&self) -> &K {
        self.key.as_ref().expect("vacant entry key missing")
    }
}

impl<K, V> Index<&K> for SeqMap<K, V>
where
    K: Eq + Hash + Clone,
    V: Clone,
{
    type Output = V;

    /// Allows accessing values using the indexing syntax (`map[&key]`).
    ///
    /// # Panics
    ///
    /// Panics if the key is not present in the map.
    ///
    /// # Examples
    ///
    /// ```
    /// use seq_map::SeqMap;
    /// let mut map = SeqMap::new();
    /// map.insert("key".to_string(), 42).unwrap();
    /// assert_eq!(map[&"key".to_string()], 42);
    /// ```
    fn index(&self, key: &K) -> &Self::Output {
        self.get(key).expect("Key not found in SeqMap")
    }
}

impl<K, V> From<&[(K, V)]> for SeqMap<K, V>
where
    K: Eq + Hash + Clone,
    V: Clone,
{
    /// Creates a `SeqMap` from a slice of key-value pairs.
    ///
    /// If duplicate keys are present in the slice, the first occurrence is kept, and subsequent
    /// duplicates are ignored.
    ///
    /// # Examples
    ///
    /// ```
    /// use seq_map::SeqMap;
    /// let pairs = vec![
    ///     ("a".to_string(), 1),
    ///     ("b".to_string(), 2),
    /// ];
    /// let map: SeqMap<_, _> = SeqMap::from(&pairs[..]);
    /// assert_eq!(map.len(), 2);
    /// ```
    fn from(slice: &[(K, V)]) -> Self {
        let mut map = SeqMap::new();
        for (key, value) in slice {
            // Ignore errors to keep the first occurrence
            let _ = map.insert(key.clone(), value.clone());
        }
        map
    }
}

/// Creates a `SeqMap` from an iterator of key-value pairs.
///
/// If duplicate keys are present in the iterator, the first occurrence is kept,
/// and subsequent duplicates are silently ignored.
impl<K: Hash, V> FromIterator<(K, V)> for SeqMap<K, V>
where
    K: Eq + Clone,
    V: Clone,
{
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
        let mut map = SeqMap::new();
        for (k, v) in iter {
            let _ = map.insert(k, v); // Intentionally ignore errors for this trait
        }
        map
    }
}

impl<'a, K, V> IntoIterator for &'a SeqMap<K, V>
where
    K: Eq + Hash + Clone,
{
    type Item = (&'a K, &'a V);
    type IntoIter = std::iter::Map<std::slice::Iter<'a, (K, V)>, fn(&'a (K, V)) -> (&'a K, &'a V)>;

    /// Returns an iterator over references to the key-value pairs in insertion order.
    ///
    /// This implementation allows you to iterate over references to the keys and values
    /// without consuming the `SeqMap`. It's useful for scenarios where you want to inspect
    /// the contents of the map without modifying it.
    ///
    /// # Examples
    ///
    /// ## Iterating Over References
    ///
    /// ```rust
    /// use seq_map::SeqMap;
    ///
    /// let mut map = SeqMap::new();
    /// map.insert("a".to_string(), 1).unwrap();
    /// map.insert("b".to_string(), 2).unwrap();
    /// map.insert("c".to_string(), 3).unwrap();
    ///
    /// for (key, value) in &map {
    ///     println!("{}: {}", key, value);
    /// }
    /// ```
    ///
    /// ## Collecting into a Vector of References
    ///
    /// ```rust
    /// use seq_map::SeqMap;
    ///
    /// let mut map = SeqMap::new();
    /// map.insert("x".to_string(), 100).unwrap();
    /// map.insert("y".to_string(), 200).unwrap();
    ///
    /// let entries: Vec<_> = (&map).into_iter().collect();
    /// assert_eq!(
    ///     entries,
    ///     vec![
    ///         (&"x".to_string(), &100),
    ///         (&"y".to_string(), &200),
    ///     ]
    /// );
    /// ```
    fn into_iter(self) -> Self::IntoIter {
        self.entries.iter().map(|(k, v)| (k, v))
    }
}

impl<K, V> Default for SeqMap<K, V> {
    /// Creates a new, empty `SeqMap`.
    ///
    /// # Examples
    ///
    /// ```
    /// use seq_map::SeqMap;
    /// let map: SeqMap<String, i32> = SeqMap::default();
    /// ```
    fn default() -> Self {
        Self {
            key_to_index: HashMap::default(),
            entries: Vec::default(),
        }
    }
}

// Mutable reference iterator
impl<'a, K, V> IntoIterator for &'a mut SeqMap<K, V>
where
    K: Eq + Hash + Clone,
{
    type Item = (&'a K, &'a mut V);
    type IntoIter =
        std::iter::Map<std::slice::IterMut<'a, (K, V)>, fn(&'a mut (K, V)) -> (&'a K, &'a mut V)>;

    fn into_iter(self) -> Self::IntoIter {
        self.entries.iter_mut().map(|(k, v)| (&*k, v))
    }
}

// Consuming iterator
impl<K, V> IntoIterator for SeqMap<K, V>
where
    K: Eq + Hash + Clone,
{
    type Item = (K, V);
    type IntoIter = std::vec::IntoIter<(K, V)>;

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

impl<K, V> SeqMap<K, V>
where
    K: Eq + Hash + Clone,
{
    /// Provides entry API.
    pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
        if let Some(&index) = self.key_to_index.get(&key) {
            Entry::Occupied(OccupiedEntry { map: self, index })
        } else {
            Entry::Vacant(VacantEntry {
                map: self,
                key: Some(key),
            })
        }
    }
    pub fn into_keys(self) -> impl Iterator<Item = K> {
        self.entries.into_iter().map(|(k, _)| k)
    }

    pub fn into_values(self) -> impl Iterator<Item = V> {
        self.entries.into_iter().map(|(_, v)| v)
    }
}

impl<K, V> Extend<(K, V)> for SeqMap<K, V>
where
    K: Eq + Hash + Clone,
{
    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
        for (k, v) in iter {
            let _ = self.insert(k, v);
        }
    }
}

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

    #[test]
    fn test_clear_and_drain() {
        let mut map = SeqMap::new();
        map.insert("a", 1).unwrap();
        map.insert("b", 2).unwrap();

        let mut other_map = SeqMap::new();
        for (k, v) in map.drain() {
            other_map.insert(k, v).unwrap();
        }
        assert!(map.is_empty());
        assert_eq!(other_map.len(), 2);

        other_map.clear();
        assert!(other_map.is_empty());
        assert_eq!(other_map.key_to_index.len(), 0);
        assert_eq!(other_map.entries.len(), 0);
    }
}