claudiofsr_lib 0.19.8

General-purpose library used by my programs
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
use std::{cmp::Ord, collections::HashSet, hash::Hash, iter::Peekable};

/// A trait for extracting unique elements from a vector.
///
/// This trait adds methods to `Vec<T>` for removing duplicate elements,
/// either while preserving the original order (`unique`) or after sorting (`unique_ordered`).
///
/// ### Type Parameters
///
/// * `T`: The type of elements in the vector.
///   The required trait bounds depend on the method being used.
///     - `unique`: Requires `Eq`, `Hash`, and `Clone`.
///     - `unique_ordered`: Requires `Eq` and `Ord`.
///
/// ### Examples
///
/// To deduplicate while keeping the original order:
///
/// ```
/// use claudiofsr_lib::UniqueElements;
///
/// let mut vec = vec![3, 2, 2, 3, 5, 3, 4, 2, 1, 5];
/// vec.unique();
/// assert_eq!(vec, vec![3, 2, 5, 4, 1]);
/// ```
///
/// To deduplicate after sorting:
///
/// ```
/// use claudiofsr_lib::UniqueElements;
///
/// let mut vec = vec![3, 2, 2, 3, 5, 3, 4, 2, 1, 5];
/// vec.unique_ordered();
/// assert_eq!(vec, vec![1, 2, 3, 4, 5]);
/// ```
pub trait UniqueElements<T> {
    /// Deduplicates elements in the vector while preserving the original order.
    fn unique(&mut self)
    where
        T: Eq + Hash + Clone;

    /// Deduplicates elements in the vector after sorting them.
    fn unique_ordered(&mut self)
    where
        T: Eq + Ord;
}

impl<T> UniqueElements<T> for Vec<T> {
    /// Deduplicates elements in a vector while preserving the original order.
    ///
    /// This method iterates through the vector and keeps only the first occurrence
    /// of each element, effectively removing duplicates and maintaining the order in which
    /// elements first appear. It uses a `HashSet` to efficiently track seen elements.
    fn unique(&mut self)
    where
        T: Eq + Hash + Clone,
    {
        // `HashSet` to keep track of elements we've already encountered.
        let mut seen = HashSet::new();

        // `retain` iterates through the vector and keeps elements based on the closure's return value.
        self.retain(|x| {
            // `seen.insert(x.clone())` attempts to insert a clone of the current element `x` into the `HashSet`.
            // - If `x` is already in the `HashSet`, `insert` returns `false`.
            // - If `x` is NOT in the `HashSet`, `insert` inserts it and returns `true`.
            // We want to keep the element only if it's the first time we're seeing it (i.e., `insert` returns `true`).
            seen.insert(x.clone()) // Keep element if it's the first time we see it
        });
    }

    /// Sorts the elements and then removes the duplicated elements.
    /// The final vector will contain only unique elements in sorted order.
    fn unique_ordered(&mut self)
    where
        T: Eq + Ord,
    {
        self.sort_unstable();
        self.dedup();
    }
}

/// Extension trait for iterators, providing additional functionality.
pub trait IteratorExt: Iterator + Sized {
    /// Returns an iterator that yields only the unique elements from the original iterator,
    /// preserving the order in which they first appear.
    ///
    /// ### Examples
    ///
    /// ```
    /// use claudiofsr_lib::IteratorExt;
    ///
    /// let numbers = vec![1, 3, 2, 2, 5, 2, 3, 4];
    /// let unique_numbers: Vec<_> = numbers
    ///     .into_iter()
    ///     .get_unique()
    ///     //.unique()
    ///     .collect();
    ///
    /// assert_eq!(unique_numbers, &[1, 3, 2, 5, 4]);
    /// ```
    ///
    /// ### Source
    ///
    /// Inspired by: "My favorite Rust design pattern"
    /// - <https://www.youtube.com/watch?v=qrf52BVaZM8>
    ///
    /// - <https://letsgetrusty.com/cheatsheet>
    fn get_unique(self) -> UniqueIterator<Self> {
        UniqueIterator::new(self)
    }

    /// Returns an iterator that skips the last element of the original iterator.
    ///
    /// ### Examples
    ///
    /// ```
    /// use claudiofsr_lib::IteratorExt;
    ///
    /// let iter = 1..=5;
    /// let data1: Vec<_> = iter.skip_last().collect();
    /// assert_eq!(data1, [1, 2, 3, 4]);
    ///
    /// let data2: Vec<_> = [1, 2, 3, 4, 5]
    ///     .into_iter()
    ///     .skip(1)
    ///     .skip_last()
    ///     .skip(1)
    ///     .collect();
    /// assert_eq!(data2, [3, 4]);
    ///
    /// let data3: Vec<_> = [1, 2, 3]
    ///     .into_iter()
    ///     .skip_last()
    ///     .skip_last()
    ///     .skip_last()
    ///     .collect();
    /// assert!(data3.is_empty());
    /// ```
    ///
    /// ### Source
    ///
    /// Inspired by: <https://users.rust-lang.org/t/iterator-skip-last>
    fn skip_last(self) -> SkipLastIterator<Self> {
        SkipLastIterator::new(self)
    }
}

// Implement the IteratorExt trait for all types that implement the Iterator trait.
// impl IteratorExt for std::vec::IntoIter<i32> {}
// impl IteratorExt for std::vec::IntoIter<i64> {}
// ...
impl<I: Iterator> IteratorExt for I {}

/// An iterator that yields only the unique elements from an underlying iterator,
/// preserving the order in which they first appear.
pub struct UniqueIterator<I: Iterator> {
    iter: I,
    seen: HashSet<I::Item>,
}

impl<I: Iterator> UniqueIterator<I> {
    /// Creates a new `UniqueIterator` from an existing iterator.
    fn new(iter: I) -> UniqueIterator<I> {
        UniqueIterator {
            iter,
            seen: HashSet::new(),
        }
    }
}

impl<I> Iterator for UniqueIterator<I>
where
    I: Iterator,
    I::Item: Eq + Hash + Clone,
{
    type Item = I::Item;

    /// Advances the iterator and returns the next value. Returns `None` when the end is reached.
    fn next(&mut self) -> Option<Self::Item> {
        // Find the next item in the iterator that hasn't been seen before.
        // If the iterator is exhausted, this will return `None`.
        self.iter.find(|item| self.seen.insert(item.clone()))
    }
}

/// An iterator that skips the last element of the underlying iterator.
pub struct SkipLastIterator<I: Iterator> {
    iter: Peekable<I>,
}

impl<I: Iterator> SkipLastIterator<I> {
    /// Creates a new `SkipLastIterator` from an existing iterator.
    fn new(iter: I) -> SkipLastIterator<I> {
        SkipLastIterator {
            iter: iter.peekable(),
        }
    }
}

impl<I: Iterator> Iterator for SkipLastIterator<I> {
    type Item = I::Item;

    /// Advances the iterator and returns the next value, skipping the last element.
    /// Returns `None` when the end is reached or the last element is encountered.
    fn next(&mut self) -> Option<I::Item> {
        // Get the next item from the iterator.
        let next_item = self.iter.next();

        // Check if there are more elements after the current one using `peek()`.
        // 'peek()' returns a reference to the next() value without advancing the iterator.
        match self.iter.peek() {
            Some(_) => {
                // If there's another item after `next_item`, return `next_item`.
                next_item
            }
            None => {
                // If there are no more elements after `next_item`, it must be the last item, so return `None`.
                None
            }
        }
    }
}

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

    #[test]
    fn test_get_unique() {
        let numbers = vec![1, 3, 2, 2, 5, 2, 3, 4];
        let unique_numbers: Vec<_> = numbers.into_iter().get_unique().collect();
        assert_eq!(unique_numbers, &[1, 3, 2, 5, 4]);
    }

    #[test]
    fn test_get_unique_empty() {
        let numbers: Vec<i32> = vec![];
        let unique_numbers: Vec<_> = numbers.into_iter().get_unique().collect();
        assert_eq!(unique_numbers, &[]);
    }

    #[test]
    fn test_get_unique_all_same() {
        let numbers = vec![1, 1, 1, 1, 1];
        let unique_numbers: Vec<_> = numbers.into_iter().get_unique().collect();
        assert_eq!(unique_numbers, &[1]);
    }

    #[test]
    fn test_get_unique_strings() {
        let strings = vec!["a", "b", "b", "c", "a", "d", "c", "b", "e"];
        let unique_strings: Vec<_> = strings.into_iter().get_unique().collect();
        assert_eq!(unique_strings, &["a", "b", "c", "d", "e"]);
    }

    #[test]
    fn test_skip_last() {
        let iter = 1..=5;
        let data1: Vec<_> = iter.skip_last().collect();
        assert_eq!(data1, [1, 2, 3, 4]);
    }

    #[test]
    fn test_skip_last_empty() {
        let iter: Vec<i32> = vec![];
        let data1: Vec<_> = iter.into_iter().skip_last().collect();
        assert_eq!(data1, []);
    }

    #[test]
    fn test_skip_last_one_element() {
        let iter = vec![1];
        let data1: Vec<_> = iter.into_iter().skip_last().collect();
        assert_eq!(data1, []);
    }

    #[test]
    fn test_skip_last_multiple_skips() {
        let data2: Vec<_> = [1, 2, 3, 4, 5]
            .into_iter()
            .skip(1)
            .skip_last()
            .skip(1)
            .collect();
        assert_eq!(data2, [3, 4]);
    }

    #[test]
    fn test_skip_last_chained_skips() {
        let data3: Vec<_> = [1, 2, 3]
            .into_iter()
            .skip_last()
            .skip_last()
            .skip_last()
            .collect();
        assert!(data3.is_empty());
    }

    #[test]
    fn test_skip_last_strings() {
        let strings = vec!["a", "b", "c", "d", "e"];
        let skipped_strings: Vec<_> = strings.into_iter().skip_last().collect();
        assert_eq!(skipped_strings, &["a", "b", "c", "d"]);
    }
}

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

    // cargo test -- --help
    // cargo test -- --nocapture
    // cargo test -- --show-output
    // cargo test -- --show-output test_unique

    #[test]
    fn test_unique() {
        let mut vec = vec![1, 2, 2, 3, 1, 4, 3, 2, 5];
        vec.unique();
        assert_eq!(vec, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_unique_empty() {
        let mut vec: Vec<i32> = vec![];
        vec.unique();
        assert_eq!(vec, Vec::<i32>::new());
        assert_eq!(vec, vec![] as Vec<i32>); // Alternative mode
    }

    #[test]
    fn test_unique_all_same() {
        let mut vec = vec![1, 1, 1, 1, 1];
        vec.unique();
        assert_eq!(vec, vec![1]);
    }

    #[test]
    fn test_unique_strings() {
        let mut vec = vec!["a", "b", "b", "c", "a", "d", "c", "b", "e"];
        vec.unique();
        assert_eq!(vec, vec!["a", "b", "c", "d", "e"]);
    }

    #[test]
    fn test_unique_ordered() {
        let mut vec = vec![1, 2, 2, 3, 1, 4, 3, 2, 5];
        vec.unique_ordered();
        assert_eq!(vec, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_unique_ordered_empty() {
        let mut vec: Vec<i32> = vec![];
        vec.unique_ordered();
        assert_eq!(vec, Vec::<i32>::new());
    }

    #[test]
    fn test_unique_ordered_all_same() {
        let mut vec = vec![1, 1, 1, 1, 1];
        vec.unique_ordered();
        assert_eq!(vec, vec![1]);
    }

    #[test]
    fn test_unique_ordered_strings() {
        let mut vec = vec!["a", "b", "b", "c", "a", "d", "c", "b", "e"];
        vec.unique_ordered();
        assert_eq!(vec, vec!["a", "b", "c", "d", "e"]);
    }

    #[test]
    fn test_unique_mixed_types() {
        let mut vec: Vec<String> = vec![
            "a".to_string(),
            "b".to_string(),
            "b".to_string(),
            "c".to_string(),
            "a".to_string(),
        ];
        vec.unique();
        assert_eq!(vec, vec!["a".to_string(), "b".to_string(), "c".to_string()]);
    }

    #[test]
    fn test_unique_ordered_mixed_types() {
        let mut vec: Vec<String> = vec![
            "a".to_string(),
            "b".to_string(),
            "b".to_string(),
            "c".to_string(),
            "a".to_string(),
        ];
        vec.unique_ordered();
        assert_eq!(vec, vec!["a".to_string(), "b".to_string(), "c".to_string()]);
    }

    #[test]
    fn test_unique_numbers() {
        let mut vec = vec![5, 4, 3, 2, 1, 1, 2, 3, 4, 5];
        vec.unique();
        assert_eq!(vec, vec![5, 4, 3, 2, 1]);
    }

    #[test]
    fn test_unique_ordered_numbers() {
        let mut vec = vec![5, 4, 3, 2, 1, 1, 2, 3, 4, 5];
        vec.unique_ordered();
        assert_eq!(vec, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_unique_already_unique() {
        let mut vec = vec![1, 2, 3, 4, 5];
        vec.unique();
        assert_eq!(vec, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_unique_ordered_already_unique() {
        let mut vec = vec![1, 2, 3, 4, 5];
        vec.unique_ordered();
        assert_eq!(vec, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_unique_negative_numbers() {
        let mut vec = vec![-1, -2, -2, -3, -1, -4, -3, -2, -5];
        vec.unique();
        assert_eq!(vec, vec![-1, -2, -3, -4, -5]);
    }

    #[test]
    fn test_unique_ordered_negative_numbers() {
        let mut vec = vec![-1, -2, -2, -3, -1, -4, -3, -2, -5];
        vec.unique_ordered();
        assert_eq!(vec, vec![-5, -4, -3, -2, -1]);
    }

    #[test]
    fn test_unique_mixed_positive_negative() {
        let mut vec = vec![-1, 2, -2, 3, -1, 4, -3, 2, -5];
        vec.unique();
        assert_eq!(vec, vec![-1, 2, -2, 3, 4, -3, -5]);
    }

    #[test]
    fn test_unique_ordered_mixed_positive_negative() {
        let mut vec = vec![-1, 2, -2, 3, -1, 4, -3, 2, -5];
        vec.unique_ordered();
        assert_eq!(vec, vec![-5, -3, -2, -1, 2, 3, 4]);
    }

    // Test structs
    #[derive(Debug, Hash, PartialEq, Eq, Clone)]
    struct MyStruct {
        value: i32,
    }

    impl Ord for MyStruct {
        fn cmp(&self, other: &Self) -> std::cmp::Ordering {
            self.value.cmp(&other.value)
        }
    }

    impl PartialOrd for MyStruct {
        fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
            Some(self.cmp(other))
        }
    }

    #[test]
    fn test_unique_structs() {
        let mut vec = vec![
            MyStruct { value: 1 },
            MyStruct { value: 2 },
            MyStruct { value: 2 },
            MyStruct { value: 3 },
            MyStruct { value: 1 },
        ];
        vec.unique();
        assert_eq!(
            vec,
            vec![
                MyStruct { value: 1 },
                MyStruct { value: 2 },
                MyStruct { value: 3 },
            ]
        );
    }

    #[test]
    fn test_unique_ordered_structs() {
        let mut vec = vec![
            MyStruct { value: 3 },
            MyStruct { value: 1 },
            MyStruct { value: 2 },
            MyStruct { value: 2 },
            MyStruct { value: 1 },
        ];
        vec.unique_ordered();
        assert_eq!(
            vec,
            vec![
                MyStruct { value: 1 },
                MyStruct { value: 2 },
                MyStruct { value: 3 },
            ]
        );
    }
}