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
//! This crate provides a couple of iterator adapters for deduplication of elements from a source iterator, inspired by the dedup methods
//! in `Vec`.
//!
//! # `dedup`
//! The `DedupAdapter` is an iterator adapter that removes consecutive repeated elements from the source iterator.
//! The `dedup` trait method returns a `Dedup` iterator struct.
//! ## Example
//! ```rust
//! use dedup_iter::DedupAdapter;
//!
//! assert_eq!("abcdefe", "aabbccdddeeeeffffeee".chars().dedup().collect::<String>());
//! ```
//!
//! # `dedup_by`
//! The `DedupByAdapter` is an iterator adapter that removes consecutive repeated elements from the source iterator
//! using a function to determine equality.
//! The `dedup_by` trait method returns a `DedupBy` iterator struct.
//! ## Examples
//! ```rust
//! use std::ascii::AsciiExt;
//! use dedup_iter::DedupByAdapter;
//!
//! assert_eq!(
//!        "This string had way too much redundant whitespace!",
//!        "This  string   had      way too     much redundant \n whitespace!".chars()
//!         .dedup_by(|a, b| a.is_whitespace() && b.is_whitespace() )
//!         .collect::<String>()
//!        );
//! ```

//! # `dedup_by_key`
//! The `DedupByKeyAdapter` is an iterator adapter that removes consecutive repeated elements from the source iterator
//! using a key to determine equality.
//! The `dedup_by_key` trait method returns a `DedupByKey` iterator struct.
//! ## Examples
//! ```rust
//! use dedup_iter::DedupByKeyAdapter;
//!
//! assert_eq!(
//!        "abcdefe",
//!        "aabbccdddeeeeffffeee".chars()
//!         .dedup_by_key(|a| *a as usize)
//!         .collect::<String>()
//!        );
//! ```

/// An iterator that removes elements that are the same as previous one.
///
/// This struct is created by the `dedup` method of trait `DedupAdapter`, implemented on Iterator.
/// To use the `dedup` method, `use dedup_iter::DedupAdapter`.
pub struct Dedup<I>
where
    I: Iterator,
{
    iter: I,
    current_item: Option<I::Item>,
}

/// An iterator that removes elements that are the same as previous one, according the provided function.
///
/// This struct is created by the `dedup_by` method of trait `DedupByAdapter`, implemented on Iterator.
/// To use the `dedup_by` method, `use dedup_iter::DedupByAdapter`.
pub struct DedupBy<I, F>
where
    I: Iterator,
{
    iter: I,
    current_item: Option<I::Item>,
    same_bucket: F,
}

/// An iterator that removes elements that have a key that is the same as the key of previous element.
/// The client provided function computes the key.
///
/// This struct is created by the `dedup_by_key` method of trait `DedupByKeyAdapter`, implemented on Iterator.
/// To use the `dedup_by_key` method, `use dedup_iter::DedupByKeyAdapter`.
pub struct DedupByKey<I, F, K> {
    iter: I,
    current_key: Option<K>,
    key: F,
}

impl<I> Iterator for Dedup<I>
where
    I: Iterator,
    I::Item: PartialEq + Clone,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<I::Item> {
        for x in self.iter.by_ref() {
            let item = Some(x.clone());
            if self.current_item != item {
                self.current_item = item;
                return Some(x);
            }
        }
        None
    }
}

impl<I, F> Iterator for DedupBy<I, F>
where
    I: Iterator,
    I::Item: Clone,
    F: Fn(&I::Item, &I::Item) -> bool,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<I::Item> {
        for x in self.iter.by_ref() {
            let item = Some(x.clone());
            let different = match self.current_item {
                None => true,
                Some(ref current_item) => !(self.same_bucket)(current_item, &x), 
            };
            if different {
                self.current_item = item;
                return Some(x);
            }
        }
        None
    }
}

impl<I, F, K> Iterator for DedupByKey<I, F, K>
where
    I: Iterator,
    F: Fn(&I::Item) -> K,
    K: PartialEq,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<I::Item> {
        for x in self.iter.by_ref() {
            let key = (self.key)(&x);
            let different = match self.current_key {
                None => true,
                Some(ref current_key) => key != *current_key,
            };
            if different {
                self.current_key = Some(key);
                return Some(x);
            }
        }
        None
    }
}

/// Provides the `dedup` method on `Iterator`s.
pub trait DedupAdapter: Iterator {
    fn dedup(self) -> Dedup<Self>
    where
        Self: Sized,
    {
        Dedup {
            iter: self,
            current_item: None,
        }
    }
}

/// Provides the `dedup_by` method on `Iterator`s.
pub trait DedupByAdapter<F>: Iterator {
    fn dedup_by(self, same_bucket: F) -> DedupBy<Self, F>
    where
        Self: Sized,
        F: Fn(&Self::Item, &Self::Item) -> bool,
    {
        DedupBy {
            iter: self,
            current_item: None,
            same_bucket: same_bucket,
        }

    }
}

/// Provides the `dedup_by_key` method on `Iterator`s.
pub trait DedupByKeyAdapter<F, K>: Iterator {
    fn dedup_by_key(self, key: F) -> DedupByKey<Self, F, K>
    where
        Self: Sized,
        F: Fn(&Self::Item) -> K,
    {
        DedupByKey {
            iter: self,
            current_key: None,
            key: key,
        }

    }
}

impl<I> DedupAdapter for I
where
    I: Iterator,
{
}

impl<I, F> DedupByAdapter<F> for I
where
    I: Iterator,
{
}

impl<I, F, K> DedupByKeyAdapter<F, K> for I
where
    I: Iterator,
{
}

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

    #[test]
    fn remove_duplicate_chars() {
        let t = "Thiss sisssssling ssstring";
        let v = t.chars().dedup().collect::<String>();
        assert_eq!(&v, "This sisling string");
    }

    #[test]
    fn remove_duplicate_whitespace() {
        let t = "Hierr zzitt ikk    well      goedd!";
        let v = t.chars()
            .dedup_by(|a, b| a.is_whitespace() && b.is_whitespace())
            .collect::<String>();
        assert_eq!(&v, "Hierr zzitt ikk well goedd!");
    }

    #[test]
    fn almost_acronym() {
        let t = "First In, Last Out";
        let v = t.chars()
            .dedup_by_key(|a| a.is_whitespace())
            .collect::<String>();
        assert_eq!(&v, "F I L O");
    }

    #[test]
    fn dedup_iter_empty() {
        let t = Vec::<u8>::new();
        let c = t.iter().dedup().count();
        assert_eq!(c, 0);
    }

    #[test]
    fn dedup_iter_numbers() {
        let t = vec![10, 20, 20, 21, 30, 20];
        let v = t.iter().dedup().collect::<Vec<_>>();
        assert_eq!(v, vec![&10, &20, &21, &30, &20]);
    }

    #[test]
    fn dedup_by_eq() {
        let t = "Hierr zzitt ikk    well      goedd!";
        let v = t.chars().dedup_by(|a, b| *a == *b).collect::<String>();
        assert_eq!(&v, "Hier zit ik wel goed!");
    }

    #[test]
    fn dedup_by_key() {
        #[derive(Debug, PartialEq)]
        struct Person<'a> {
            id: u64,
            name: &'a str,
        };
        let t = vec![
            Person {
                id: 0,
                name: "Bilbo",
            },
            Person {
                id: 0,
                name: "Bilbo",
            },
        ];
        let v = t.iter()
            .dedup_by_key(|person| person.id)
            .collect::<Vec<_>>();
        assert_eq!(
            v,
            vec![
                &Person {
                    id: 0,
                    name: "Bilbo",
                },
            ]
        );
    }

    #[test]
    fn dedup_by_always_same() {
        let t = "abdefghijklmopqrstuvwxyz";
        let v = t.chars().dedup_by(|_, _| true).collect::<String>();
        assert_eq!(&v, "a");
    }

    #[test]
    fn dedup_by_key_always_same() {
        let t = "abdefghijklmopqrstuvwxyz";
        let v = t.chars().dedup_by_key(|_| 0).collect::<String>();
        assert_eq!(&v, "a");
    }
}