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
//! Non-empty hash map implementation.

#[cfg(feature = "serde_support")]
mod deserialize;
mod entry;
mod into_iter;
#[cfg(feature = "serde_support")]
mod serialize;

pub use self::entry::Entry;
pub use self::into_iter::IntoIter;
use indexmap::IndexMap;
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hash};
use std::iter::Extend;
use std::mem::replace;
use std::{borrow, fmt, iter};
use {estimated_size, Error};

/// A wrapper around [`::indexmap::IndexMap`] that is guaranteed to have at least one element by the
/// Rust's type system: it consists of a **first** element and an indexed map (which could be
/// empty) **rest** elements.
#[derive(Clone)]
pub struct NonEmptyIndexMap<K, V, S = RandomState> {
    first: (K, V),
    rest: IndexMap<K, V, S>,
}

/// A helper enum to easily obtain indexed entries.
#[derive(Clone, Copy)]
enum Index {
    First,
    Rest(usize),
}

impl<K, V> NonEmptyIndexMap<K, V, RandomState> {
    /// Creates a map with a default hasher.
    pub fn new(key: K, value: V) -> Self {
        NonEmptyIndexMap {
            first: (key, value),
            rest: IndexMap::new(),
        }
    }

    /// Creates a map with a given capacity.
    pub fn with_capacity(key: K, value: V, capacity: usize) -> Self {
        NonEmptyIndexMap {
            first: (key, value),
            rest: IndexMap::with_capacity(if capacity == 0 { 0 } else { capacity - 1 }),
        }
    }

    /// Creates a map from an item (a key and a value pair) standart hash map.
    pub fn from_item_and_iterator(key: K, value: V, i: impl IntoIterator<Item = (K, V)>) -> Self
    where
        K: Hash + Eq,
    {
        NonEmptyIndexMap {
            first: (key, value),
            rest: i.into_iter().collect(),
        }
    }

    /// Creates a map from a given iterator with a default hasher.
    pub fn from_iterator(i: impl IntoIterator<Item = (K, V)>) -> Result<Self, Error>
    where
        K: Hash + Eq,
    {
        let mut iter = i.into_iter();
        let first = iter.next().ok_or(Error::EmptyCollection)?;
        Ok(NonEmptyIndexMap {
            first,
            rest: iter.collect(),
        })
    }
}

#[cfg_attr(feature = "cargo-clippy", allow(len_without_is_empty))]
impl<K, V, S> NonEmptyIndexMap<K, V, S>
where
    K: Eq + Hash,
    S: BuildHasher,
{
    /// Creates a map with a given hasher.
    pub fn with_hasher(key: K, value: V, hash_builder: S) -> Self {
        NonEmptyIndexMap {
            first: (key, value),
            rest: IndexMap::with_hasher(hash_builder),
        }
    }

    /// Creates a map with a given capacity and a given hasher.
    pub fn with_capacity_and_hasher(key: K, value: V, capacity: usize, hash_builder: S) -> Self {
        NonEmptyIndexMap {
            first: (key, value),
            rest: IndexMap::with_capacity_and_hasher(
                if capacity == 0 { 0 } else { capacity - 1 },
                hash_builder,
            ),
        }
    }

    /// Iterates over key-value pairs of the map in an immutable way.
    pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
        iter::once((&self.first.0, &self.first.1)).chain(self.rest.iter())
    }

    /// Iterates over key-value pairs of the map in a mutable way.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&K, &mut V)> {
        iter::once((&self.first.0, &mut self.first.1)).chain(self.rest.iter_mut())
    }

    /// Creates a map from a given iterator with a given hasher.
    pub fn from_iter_with_hasher(
        i: impl IntoIterator<Item = (K, V)>,
        hasher: S,
    ) -> Result<Self, Error> {
        let mut iter = i.into_iter();
        let first = iter.next().ok_or(Error::EmptyCollection)?;
        let mut rest = match estimated_size(&iter) {
            None => IndexMap::with_hasher(hasher),
            Some(len) => IndexMap::with_capacity_and_hasher(len, hasher),
        };
        rest.extend(iter);
        Ok(NonEmptyIndexMap { first, rest })
    }

    /// Gets a value associated with a given key, if any.
    pub fn get<Q>(&self, key: &Q) -> Option<&V>
    where
        K: borrow::Borrow<Q>,
        Q: Eq + Hash + ?Sized,
    {
        if self.first.0.borrow() == key {
            Some(&self.first.1)
        } else {
            self.rest.get(key)
        }
    }

    /// Checks whether a given key exists in the map.
    pub fn contains<Q>(&self, key: &Q) -> bool
    where
        K: borrow::Borrow<Q>,
        Q: Eq + Hash + ?Sized,
    {
        if self.first.0.borrow() == key {
            true
        } else {
            self.rest.contains_key(key)
        }
    }

    /// Gets a value associated with a given key, if any.
    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
    where
        K: borrow::Borrow<Q>,
        Q: Eq + Hash + ?Sized,
    {
        if self.first.0.borrow() == key {
            Some(&mut self.first.1)
        } else {
            self.rest.get_mut(key)
        }
    }

    /// Removes and returns an element associated with a given key, if any.
    ///
    /// An attempt to remove the last element will cause an [`Error`] to be returned.
    pub fn remove_entry<Q>(&mut self, key: &Q) -> Result<Option<(K, V)>, Error>
    where
        K: borrow::Borrow<Q>,
        Q: Eq + Hash + ?Sized,
    {
        if self.first.0.borrow() == key {
            let intermediate_element = self.rest.pop().ok_or(Error::EmptyCollection)?;
            Ok(Some(replace(&mut self.first, intermediate_element)))
        } else {
            Ok(self
                .rest
                .swap_remove_full(key)
                .map(|(_index, key, value)| (key, value)))
        }
    }

    /// Removes and element associated with a given key and return its value, if any.
    ///
    /// An attempt to remove the last element will cause an [`Error`] to be returned.
    pub fn remove<Q>(&mut self, key: &Q) -> Result<Option<V>, Error>
    where
        K: borrow::Borrow<Q>,
        Q: Eq + Hash + ?Sized,
    {
        self.remove_entry(key).map(|x| x.map(|(_key, value)| value))
    }

    /// Inserts a key-value pair into the map. If the map have already had an element associated
    /// with a given key, the associated value is updated and the old one is returned.
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        if self.first.0 == key {
            Some(replace(&mut self.first.1, value))
        } else {
            self.rest.insert(key, value)
        }
    }

    /// Returns the number of elements in the map.
    pub fn len(&self) -> usize {
        self.rest.len() + 1
    }

    /// Returns an entry that corresponds to a given key.
    pub fn entry(&mut self, key: K) -> Entry<K, V, S> {
        match self.get_index(&key) {
            Some(index) => Entry::Occupied(entry::Occupied {
                key,
                index,
                map: self,
            }),
            None => Entry::Vacant(entry::Vacant { key, map: self }),
        }
    }

    fn get_entry(&self, index: Index) -> &V {
        match index {
            Index::First => &self.first.1,
            Index::Rest(idx) => {
                self.rest
                    .get_index(idx)
                    .expect("The entry exists for sure")
                    .1
            }
        }
    }

    fn get_index<Q>(&mut self, key: &Q) -> Option<Index>
    where
        K: borrow::Borrow<Q>,
        Q: Eq + Hash + ?Sized,
    {
        if self.first.0.borrow() == key {
            Some(Index::First)
        } else {
            self.rest
                .get_full(key)
                .map(|(index, _, _)| Index::Rest(index))
        }
    }

    fn get_entry_mut(&mut self, index: Index) -> &mut V {
        match index {
            Index::First => &mut self.first.1,
            Index::Rest(idx) => {
                self.rest
                    .get_index_mut(idx)
                    .expect("The entry exists for sure")
                    .1
            }
        }
    }

    /// Gets an immutable reference to the **firs** element (only the *value*).
    pub fn get_first(&self) -> (&K, &V) {
        (&self.first.0, &self.first.1)
    }

    /// Gets a mutable reference to the **firs** element (only the *value*).
    pub fn get_first_mut(&mut self) -> (&mut K, &mut V) {
        (&mut self.first.0, &mut self.first.1)
    }

    /// Gets an immutable reference to the **rest** indexed map of elements.
    pub fn get_rest(&self) -> &IndexMap<K, V, S> {
        &self.rest
    }

    /// Gets a mutable reference to the **rest** indexed map of elements.
    pub fn get_rest_mut(&mut self) -> &mut IndexMap<K, V, S> {
        &mut self.rest
    }
}

impl<K: Eq + Hash, V, S: BuildHasher> Into<IndexMap<K, V, S>> for NonEmptyIndexMap<K, V, S> {
    fn into(self) -> IndexMap<K, V, S> {
        let mut map = self.rest;
        map.insert(self.first.0, self.first.1);
        map
    }
}

impl<K, V, S> fmt::Debug for NonEmptyIndexMap<K, V, S>
where
    K: Eq + Hash + fmt::Debug,
    V: fmt::Debug,
    S: BuildHasher,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_map().entries(self.iter()).finish()
    }
}

impl<K, V, S> Extend<(K, V)> for NonEmptyIndexMap<K, V, S>
where
    K: Eq + Hash,
    S: BuildHasher,
{
    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
        self.rest.extend(iter)
    }
}

impl<K, V, S> IntoIterator for NonEmptyIndexMap<K, V, S>
where
    K: Eq + Hash,
    S: BuildHasher,
{
    type Item = (K, V);
    type IntoIter = IntoIter<K, V>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter {
            iter: iter::once(self.first).chain(self.rest),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn insert_and_get() {
        let mut map = NonEmptyIndexMap::new(0, 1);
        assert_eq!(Some(&1), map.get(&0));
        assert_eq!(None, map.get(&10));

        assert_eq!(None, map.insert(10, 20));
        assert_eq!(Some(&20), map.get(&10));

        // Key `10` already exists in the map.
        assert_eq!(Some(20), map.insert(10, 40));
        assert_eq!(Some(&40), map.get(&10));
    }

    #[test]
    fn insert_and_contains() {
        let mut map = NonEmptyIndexMap::new(0, 1);
        assert!(map.contains(&0));
        assert!(!map.contains(&10));

        assert_eq!(None, map.insert(10, 20));
        assert!(map.contains(&10));

        // Key `10` already exists in the map.
        assert_eq!(Some(20), map.insert(10, 40));
        assert!(map.contains(&10));
    }

    #[test]
    fn remove_entry() {
        let mut map = NonEmptyIndexMap::from_iterator(vec![(1, 2), (3, 4), (5, 6)]).unwrap();
        assert_eq!(Ok(Some((1, 2))), map.remove_entry(&1));
        assert_eq!(None, map.get(&1));

        assert_eq!(Ok(Some((3, 4))), map.remove_entry(&3));
        assert_eq!(None, map.get(&3));

        // Entry `&3` doesn't exist anymore.
        assert_eq!(Ok(None), map.remove_entry(&3));

        // Trying to remove the last element is an error.
        assert_eq!(Err(Error::EmptyCollection), map.remove_entry(&5));
    }

    #[test]
    fn into_std_hashmap() {
        let mut map = NonEmptyIndexMap::new(1, 2);
        assert_eq!(None, map.insert(3, 4));
        assert_eq!(None, map.insert(5, 6));
        assert_eq!(None, map.insert(7, 8));

        let std_map: IndexMap<_, _> = map.into();
        assert_eq!(4, std_map.len());
        assert_eq!(Some(&2), std_map.get(&1));
        assert_eq!(Some(&4), std_map.get(&3));
        assert_eq!(Some(&6), std_map.get(&5));
        assert_eq!(Some(&8), std_map.get(&7));
    }

    #[test]
    fn from_item_and_iterator() {
        let original = vec![(1u8, 2u8), (3, 4), (5, 6)];
        let converted = NonEmptyIndexMap::from_item_and_iterator(7, 8, original);
        let std_map: IndexMap<_, _> = converted.into();
        assert_eq!(4, std_map.len());
        assert_eq!(Some(&2), std_map.get(&1));
        assert_eq!(Some(&4), std_map.get(&3));
        assert_eq!(Some(&6), std_map.get(&5));
        assert_eq!(Some(&8), std_map.get(&7));
    }

    #[test]
    fn into_iter() {
        let original: IndexMap<_, _> = vec![(1u8, 2u8), (3, 4), (10, 12)].into_iter().collect();
        let map = NonEmptyIndexMap::from_iterator(original.clone())
            .map_err(|_| ())
            .unwrap();
        let converted: IndexMap<_, _> = map.into_iter().collect();
        assert_eq!(converted, original);
    }

    #[test]
    fn len() {
        let map = NonEmptyIndexMap::new(1, 2);
        assert_eq!(1, map.len());

        let map = NonEmptyIndexMap::from_iterator(vec![(1, 2), (3, 4), (5, 6)]).unwrap();
        assert_eq!(3, map.len());
    }

    #[test]
    fn get_unsized() {
        let map = NonEmptyIndexMap::new("Lol".to_string(), "wut");
        assert_eq!(Some(&"wut"), map.get("Lol"));
    }
}