unique_id_lookup 0.2.11

Associative Array specifically designed for integer keys. Significant performance boost over conventional hash maps.
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
use std::collections::HashMap;

/// An associative array specifically designed for integer keys.
///
/// # Examples
///
/// ```
/// use unique_id_lookup::UniqueIdLookup;
/// let mut lookup: UniqueIdLookup<char> = UniqueIdLookup::new();
/// lookup.insert(5, 'a');
/// assert_eq!(lookup.get(5).unwrap(), 'a');
/// ```
pub struct UniqueIdLookup<T> {
    buf: Vec<Option<T>>,
    offset: usize,
}

/// Will be retired soon.
pub struct UniqueIdLookupIterator<'a, T> {
    lookup: &'a UniqueIdLookup<T>,
    index: usize,
}

/// An iterator over the ID-value pairs visiting all occupied entries.
pub struct UniqueIdLookupIteratorOccupied<'a, T> {
    lookup: &'a UniqueIdLookup<T>,
    index: usize,
}

/// An iterator over the values (only occupied entries have a value).
pub struct UniqueIdLookupIteratorValues<'a, T> {
    lookup: &'a UniqueIdLookup<T>,
    index: usize,
}

/// An iterator over the IDs visiting all vacant entries.
pub struct UniqueIdLookupIteratorVacantIDs<'a, T> {
    lookup: &'a UniqueIdLookup<T>,
    index: usize,
}

impl<T> UniqueIdLookup<T> {
    const RESULT_NONE: Option<T> = None;

    /// Creates an empty `UniqueIdLookup`.
    ///
    /// The map is initially created with a capacity of 0, so it will not allocate until it
    /// is first inserted into.
    ///
    /// # Examples
    ///
    /// ```
    /// use unique_id_lookup::UniqueIdLookup;
    /// let mut lookup: UniqueIdLookup<i16> = UniqueIdLookup::new();
    /// ```
    pub const fn new() -> Self {
        UniqueIdLookup {
            buf: Vec::new(),
            offset: 0,
        }
    }

    /// Creates an empty `UniqueIdLookup` with at least the specified capacity.
    #[deprecated(since = "0.2.4", note = "Will be removed in v0.3. Use `with_capacity_and_offset()` instead.")]
    pub fn with_capacity(capacity: usize) -> Self {
        UniqueIdLookup::with_capacity_and_offset(capacity, 0)
    }

    /// Creates an empty `UniqueIdLookup` with at least the specified capacity and `offset` (the minimum ID).
    /// 
    /// If `capacity` and `offset` are set correctly this leads to more space efficiency and
    /// a constant time complexity of `insert()`.
    pub fn with_capacity_and_offset(capacity: usize, offset: usize) -> Self {
        UniqueIdLookup {
            buf: Vec::with_capacity(capacity),
            offset,
        }
    }

    /// Creates an empty `UniqueIdLookup` capacity to hold all values between min_id and max_id.
    /// 
    /// # Examples
    ///
    /// ```
    /// use unique_id_lookup::UniqueIdLookup;
    /// let min_id = 10;
    /// let max_id = 30;
    /// let lookup: UniqueIdLookup<i16> = UniqueIdLookup::with_min_max_id(min_id, max_id);
    /// assert_eq!(lookup.get_offset(), min_id);
    /// assert_eq!(lookup.capacity(), 1 + max_id - min_id);
    /// ```
    pub fn with_min_max_id<I: Into<usize> + Copy>(min_id: I, max_id: I) -> Self {
        let capacity = 1 + max_id.into() - min_id.into();
        UniqueIdLookup::with_capacity_and_offset(capacity, min_id.into())
    }

    #[deprecated(since = "0.2.10", note = "Will be removed in v0.3. Use `from()` instead.")]
    pub fn from_hash_map<I: Into<usize> + Ord + Copy>(map: HashMap<I, T>) -> Self {
        Self::from(map)
    }

    /// Inserts a ID-value pair into the map.
    /// 
    /// The method always inserts (replaces it the key is present already).
    ///
    /// # Examples
    ///
    /// ```
    /// use unique_id_lookup::UniqueIdLookup;
    /// let mut lookup: UniqueIdLookup<char> = UniqueIdLookup::new();
    /// lookup.insert(1, 'a');
    /// assert_eq!(lookup.get(1).unwrap(), 'a');
    /// lookup.insert(1, 'b');
    /// assert_eq!(lookup.get(1).unwrap(), 'b');
    /// ```
    ///
    /// # Complexity
    ///
    /// Can have constant time complexity if the map is pre-allocated using with_capacity_and_offset().
    pub fn insert(&mut self, id: usize, value: T) -> &mut T {
        if !self.buf.is_empty() {
            if id < self.offset {
                let nbr_prepend_elements = self.offset - id;
                for _i in 0..(nbr_prepend_elements - 1) {
                    self.buf.insert(0, None);
                }
                self.buf.insert(0, Some(value));
                self.offset = id;
                return self.buf[0].as_mut().unwrap();
            } else {
                let index = id - self.offset;
                if index < self.buf.len() {
                    self.buf[index] = Some(value);
                } else {
                    self.buf.resize_with(index + 1, || None);
                    self.buf[index] = Some(value);
                }
                return self.buf[index].as_mut().unwrap();
            }
        } else {
            // empty
            if self.capacity() == 0 || id < self.offset {
                self.offset = id;
                self.buf.push(Some(value));
                return self.buf[0].as_mut().unwrap();
            } else {
                let index = id - self.offset;
                self.buf.resize_with(index + 1, || None);
                self.buf[index] = Some(value);
                return self.buf[index].as_mut().unwrap();
            }
        }
    }


    /// Only inserts a ID-value pair into the map if not present, and does nothing otherwise.
    /// 
    /// # Examples
    ///
    /// ```
    /// use unique_id_lookup::UniqueIdLookup;
    /// let mut lookup: UniqueIdLookup<char> = UniqueIdLookup::new();
    /// lookup.insert_if_absent(1, 'a');
    /// assert_eq!(lookup.get(1).unwrap(), 'a');
    /// lookup.insert_if_absent(1, 'b');
    /// assert_eq!(lookup.get(1).unwrap(), 'a');
    /// ```
    ///
    /// # Complexity
    ///
    /// Can have constant time complexity if the map is pre-allocated using with_capacity_and_offset().
    pub fn insert_if_absent(&mut self, id: usize, value: T) -> &mut T {
        if self.contains_id(id) {
            return self.get_mut(id).unwrap();
        }
        return self.insert(id, value);
    }

    /// Returns `true` if the map contains a value for the specified ID.
    ///
    /// # Examples
    ///
    /// ```
    /// use unique_id_lookup::UniqueIdLookup;
    /// let mut lookup: UniqueIdLookup<i16> = UniqueIdLookup::new();
    /// lookup.insert(5, 17);
    /// assert_eq!(lookup.contains_id(0), false);
    /// assert_eq!(lookup.contains_id(5), true);
    /// ```
    #[inline]
    pub fn contains_id(&self, id: usize) -> bool {
        if id < self.offset {
            return false;
        }
        let index = id - self.offset;
        if index >= self.buf.len() {
            return false;
        }
        let value = &self.buf[index];
        value.is_some()
    }

    /// Returns a reference to an element or `None` if the ID was not found.
    ///
    /// # Panics
    ///
    /// Panics if `id` is out of bounds of the underlying vector.
    ///     
    /// # Examples
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use unique_id_lookup::UniqueIdLookup;
    /// let hash_map: HashMap<u16, char> = HashMap::from([(5, 'c')]);
    /// let lookup = UniqueIdLookup::from_hash_map(hash_map);
    /// let c = lookup.get(5).unwrap();
    /// ```
    #[inline]
    pub fn get(&self, id: usize) -> &Option<T> {
        let index = id - self.offset;
        &self.buf[index]
    }

    /// Same as .get() but returns None outside of the bounds of the underlying vector.
    #[inline]
    pub fn get_or_none(&self, id: usize) -> &Option<T> {
        if id < self.offset {
            return &UniqueIdLookup::RESULT_NONE;
        }
        let index = id - self.offset;
        if index >= self.buf.len() {
            return &UniqueIdLookup::RESULT_NONE;
        }
        &self.buf[index]
    }

    /// Returns a mutable reference to an element or `None` if the ID was not found.    
    #[inline]
    pub fn get_mut(&mut self, id: usize) -> Option<&mut T> {
        let index = id - self.offset;
        self.buf.get_mut(index)?.as_mut()
    }

    /// Removes and returns the element with ID `id`. Essentially this is just marking the element as vacant.
    ///
    /// # Panics
    ///
    /// Panics if `id` is out of bounds of the underlying vector.
    ///
    /// # Complexity
    ///
    /// Constant time complexity
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use unique_id_lookup::UniqueIdLookup;
    /// let hash_map: HashMap<u16, char> = HashMap::from([(5, 'c'), (6, 'd')]);
    /// let mut lookup = UniqueIdLookup::from_hash_map(hash_map);
    /// assert_eq!(lookup.len_occupied(), 2);
    /// assert_eq!(lookup.remove(5).unwrap(), 'c');
    /// assert_eq!(lookup.len_occupied(), 1);
    /// assert!(lookup.get(5).is_none());
    /// ```
    #[inline]
    pub fn remove(&mut self, id: usize) -> Option<T> {
        let index = id - self.offset;
        let mut removed_value: Option<T> = None;
        std::mem::swap(&mut self.buf[index], &mut removed_value);
        removed_value
    }

    /// An iterator visiting all elements that have a value.
    #[deprecated(since = "0.2.4", note = "Will be removed in v0.3. Use `iter_occupied()` instead.")]
    pub fn iter(&self) -> UniqueIdLookupIterator<T> {
        UniqueIdLookupIterator {
            lookup: self,
            index: 0,
        }
    }

    /// Returns an iterator over the ID-value pairs visiting all occupied entries.
    /// 
    /// The iterator element type is the tuple (usize, &'a T)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use unique_id_lookup::UniqueIdLookup;
    /// let arr: [(usize, char); 3] = [(5, 'c'), (6, 'd'), (8, 'f')];
    /// let lookup = UniqueIdLookup::from(arr);
    /// for (id, payload) in lookup.iter_occupied() {
    ///     let tup = (id, *payload);
    ///     assert!(arr.contains(&tup));            
    /// }
    /// ```
    pub fn iter_occupied(&self) -> UniqueIdLookupIteratorOccupied<T> {
        UniqueIdLookupIteratorOccupied {
            lookup: self,
            index: 0,
        }
    }

    /// Returns an iterator over the values (only occupied entries have a value).
    /// 
    /// The iterator element type is &'a T.
    ///
    /// # Examples
    ///
    /// ```
    /// use unique_id_lookup::UniqueIdLookup;
    /// let arr: [(usize, char); 3] = [(5, 'c'), (6, 'd'), (8, 'f')];
    /// let lookup = UniqueIdLookup::from(arr);
    /// for payload in lookup.values() {
    ///     assert!(['c', 'd', 'f'].contains(&payload));
    /// }
    /// ```    
    pub fn values(&self) -> UniqueIdLookupIteratorValues<T> {
        UniqueIdLookupIteratorValues {
            lookup: self,
            index: 0,
        }
    }

    /// An iterator visiting all vacant IDs.
    ///
    /// # Examples
    ///
    /// ```
    /// use unique_id_lookup::UniqueIdLookup;
    /// let arr: [(usize, char); 4] = [(5, 'c'), (6, 'd'), (8, 'f'), (10, 'h')];
    /// let lookup = UniqueIdLookup::from(arr);
    /// for id in lookup.iter_vacant_ids() {
    ///     assert_eq!([7, 9].contains(&id), true);
    /// }
    /// ```
    pub fn iter_vacant_ids(&self) -> UniqueIdLookupIteratorVacantIDs<T> {
        UniqueIdLookupIteratorVacantIDs {
            lookup: self,
            index: 0,
        }
    }

    /// Returns the offset to the underlying (dynamic) array. Mainly important for testing.
    #[inline]
    pub const fn get_offset(&self) -> usize {
        self.offset
    }

    #[inline]
    pub fn capacity(&self) -> usize {
        self.buf.capacity()
    }

    /// Returns the number of elements in the underlying (dynamic) array.
    #[inline]
    pub fn range_len(&self) -> usize {
        self.buf.len()
    }

    /// Returns the number of elements in the underlying (dynamic) array that actually have a value.
    #[deprecated(since = "0.2.4", note = "Will be removed in v0.3. Use `len_occupied()` instead  (just a name change).")]
    pub fn len(&self) -> usize {
        self.len_occupied()
    }

    /// Returns the number of occupied entries.
    ///
    /// # Complexity
    ///
    /// Takes linear (in `self.buf.len()`) time.
    pub fn len_occupied(&self) -> usize {
        self.buf.iter().filter(|payload| payload.is_some()).count()
    }

    /// Returns the fraction of accupied elements to all elements in the underlying vector.
    /// 
    /// UniqueIdLookup is a good choice if the density is close to 1.
    /// 
    /// ```
    /// use std::collections::HashMap;
    /// use unique_id_lookup::UniqueIdLookup;
    /// let hash_map: HashMap<u16, char> = HashMap::from([(1, 'a'), (4, 'd')]);
    /// let mut lookup = UniqueIdLookup::from_hash_map(hash_map);
    /// assert_eq!(lookup.occupation_density(), 0.5);
    /// ```
    pub fn occupation_density(&self) -> f64 {
        if self.buf.is_empty() {
            return f64::NAN;
        }
        self.len_occupied() as f64 / self.buf.len() as f64
    }    

    /// Returns false if at least one occupied entry exists.
    pub fn is_occupied_empty(&self) -> bool {
        for e in self.buf.iter() {
            if e.is_some() {
                return false;
            }
        }
        true
    }

    #[deprecated(since = "0.2.4", note = "Will be removed in v0.3. Use `is_occupied_empty()` instead (just a name change).")]
    pub fn is_empty(&self) -> bool {
        self.is_occupied_empty()
    }

    /// Returns a flatten vector with all occupied entires consuming the collection itself.
    /// 
    /// # Examples
    ///
    /// ```
    /// use unique_id_lookup::UniqueIdLookup;
    /// let arr: [(usize, char); 4] = [(5, 'c'), (6, 'd'), (8, 'f'), (10, 'h')];
    /// let lookup = UniqueIdLookup::from(arr);
    /// assert_eq!(lookup.into_occupied_vec(), vec!['c', 'd', 'f', 'h']);
    /// ```
    pub fn into_occupied_vec(self) -> Vec<T> {
        let nbr_occupied = self.len_occupied();
        let mut result = Vec::with_capacity(nbr_occupied);
        for item in self.buf.into_iter().flatten() {
            result.push(item);
        }
        result
    }    

    /// Shrinks the capacity of the underlying vector as much as possible. 
    /// 
    /// This includes removing vacant ememnts on both sides. Hence the offset might be changed.
    /// 
    /// # Examples
    ///
    /// ```
    /// use unique_id_lookup::UniqueIdLookup;
    /// let mut lookup = UniqueIdLookup::with_capacity_and_offset(10, 5);
    /// assert_eq!(lookup.get_offset(), 5);
    /// lookup.insert(8, 8);
    /// lookup.insert(12, 12);
    /// assert_eq!(lookup.get_offset(), 5);
    /// 
    /// lookup.shrink_to_fit_and_trim_vacant();
    /// assert_eq!(lookup.len_occupied(), 2);
    /// assert_eq!(lookup.capacity(), 5);
    /// assert_eq!(lookup.get_offset(), 8);
    /// assert_eq!(lookup.get(8).unwrap(), 8);
    /// assert_eq!(lookup.get(12).unwrap(), 12);
    /// ```
    pub fn shrink_to_fit_and_trim_vacant(&mut self) {
        if let Some(index_r) = self.buf.iter().rposition(Option::is_some) {
            self.buf.truncate(index_r + 1);
            let mut new_offset = self.offset;
            while !self.buf.is_empty() && self.buf[0].is_none() {
                self.buf.remove(0);
                new_offset += 1;
            }
            self.offset = new_offset;
        } else {
            self.buf.clear();
            self.offset = 0;
        }
        self.buf.shrink_to_fit()        
    }

}


/// Implement From trait for HashMap conversion
/// Creates a `UniqueIdLookup<T>` from a `HashMap<I, T>`.
/// 
/// The ID-Type `I` has to implement the trait `Into<usize>`.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use unique_id_lookup::UniqueIdLookup;
/// let hash_map: HashMap<u16, char> = HashMap::from([(65, 'A'), (66, 'B')]);
/// let lookup_from = UniqueIdLookup::from(hash_map);
/// assert_eq!(lookup_from.get(66).unwrap(), 'B');
/// 
/// let hash_map: HashMap<u16, char> = HashMap::from([(67, 'C'), (68, 'D')]);
/// let lookup_into: UniqueIdLookup<char> = hash_map.into();
/// assert_eq!(lookup_into.get(68).unwrap(), 'D');
/// ```
impl<T, I> From<HashMap<I, T>> for UniqueIdLookup<T>
where 
    I: Into<usize> + Ord + Copy,
{
    fn from(hash_map: HashMap<I, T>) -> Self {
        if hash_map.is_empty() {
            return Self::new();
        }

        let (min_id, max_id) = hash_map.keys()
            .map(|&k| k.into())
            .fold((usize::MAX, 0), |(min, max), id| {
                (min.min(id), max.max(id))
            });

        let mut lookup = Self::with_min_max_id(min_id, max_id);
        for (id, value) in hash_map {
            lookup.insert(id.into(), value);
        }
        lookup
    }
}

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

/// Will be retired soon.
impl<'a, T> Iterator for UniqueIdLookupIterator<'a, T> {
    type Item = (usize, &'a Option<T>);

    fn next(&mut self) -> Option<Self::Item> {
        while self.index < self.lookup.buf.len() {
            let payload = &self.lookup.buf[self.index];
            if payload.is_none() {
                self.index += 1;
                continue;
            }
            let id = self.index + self.lookup.offset;
            let result = Some((id, payload));
            self.index += 1;
            return result;
        }
        None
    }
}




impl<'a, T> Iterator for UniqueIdLookupIteratorValues<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        while self.index < self.lookup.buf.len() {
            let payload = &self.lookup.buf[self.index];
            if payload.is_none() {
                self.index += 1;
                continue;
            }
            let result = Some(payload.as_ref().unwrap());
            self.index += 1;
            return result;
        }
        None
    }
}

impl<'a, T> Iterator for UniqueIdLookupIteratorOccupied<'a, T> {
    type Item = (usize, &'a T);

    fn next(&mut self) -> Option<Self::Item> {
        while self.index < self.lookup.buf.len() {
            let payload = &self.lookup.buf[self.index];
            if payload.is_none() {
                self.index += 1;
                continue;
            }
            let id = self.index + self.lookup.offset;
            let result = Some((id, payload.as_ref().unwrap()));
            self.index += 1;
            return result;
        }
        None
    }
}

impl<'a, T> Iterator for UniqueIdLookupIteratorVacantIDs<'a, T> {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        while self.index < self.lookup.buf.len() {
            let payload = &self.lookup.buf[self.index];
            if payload.is_some() {
                self.index += 1;
                continue;
            }
            let id = self.index + self.lookup.offset;
            let result = Some(id);
            self.index += 1;
            return result;
        }
        None
    }
}

impl<I, T, const N: usize> From<[(I, T); N]> for UniqueIdLookup<T>
where
    I: Into<usize> + Ord + Copy,
{
    /// Converts a array `[(I, T); N]` into a `UniqueIdLookup<T>`.
    ///
    /// # Examples
    ///
    /// ```
    /// use unique_id_lookup::UniqueIdLookup;
    ///
    /// let arr: [(usize, char); 3] = [(5, 'c'), (7, 'e'), (8, 'f')];
    /// let lookup = UniqueIdLookup::from(arr);
    /// assert_eq!(lookup.len_occupied(), 3);
    /// assert_eq!(lookup.get(5).unwrap(), 'c');
    /// ```    
    fn from(arr: [(I, T); N]) -> Self {
        if arr.is_empty() {
            return UniqueIdLookup::new();
        }
        let mut min_id = usize::MAX;
        let mut max_id = 0usize;
        for &(id, _) in &arr {
            let id_usize = id.into();
            min_id = min_id.min(id_usize);
            max_id = max_id.max(id_usize);
        }
        let mut lookup = UniqueIdLookup::with_min_max_id(min_id, max_id);
        for (id, v) in arr.into_iter() {
            lookup.insert(id.into(), v);
        }
        lookup
    }
}