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
//! Simple deduplication of equal consecutive items.

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::impls::offsets::{OffsetContainer, OffsetOptimized};
use crate::{Push, Region, ReserveItems};

/// A region to deduplicate consecutive equal items.
///
/// # Examples
///
/// The following example shows that two inserts can result in the same index.
/// ```
/// use flatcontainer::impls::deduplicate::CollapseSequence;
/// use flatcontainer::{Push, StringRegion};
/// let mut r = <CollapseSequence<StringRegion>>::default();
///
/// assert_eq!(r.push("abc"), r.push("abc"));
/// ```
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CollapseSequence<R: Region> {
    /// Inner region.
    inner: R,
    /// The index of the last pushed item.
    last_index: Option<R::Index>,
}

impl<R: Region + Clone> Clone for CollapseSequence<R> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            last_index: self.last_index,
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.inner.clone_from(&source.inner);
        self.last_index = source.last_index;
    }
}

impl<R: Region> Default for CollapseSequence<R> {
    fn default() -> Self {
        Self {
            inner: R::default(),
            last_index: None,
        }
    }
}

impl<R: Region> Region for CollapseSequence<R> {
    type Owned = R::Owned;
    type ReadItem<'a> = R::ReadItem<'a> where Self: 'a;
    type Index = R::Index;

    fn merge_regions<'a>(regions: impl Iterator<Item = &'a Self> + Clone) -> Self
    where
        Self: 'a,
    {
        Self {
            inner: R::merge_regions(regions.map(|r| &r.inner)),
            last_index: None,
        }
    }

    fn index(&self, index: Self::Index) -> Self::ReadItem<'_> {
        self.inner.index(index)
    }

    fn reserve_regions<'a, I>(&mut self, regions: I)
    where
        Self: 'a,
        I: Iterator<Item = &'a Self> + Clone,
    {
        self.inner.reserve_regions(regions.map(|r| &r.inner));
    }

    fn clear(&mut self) {
        self.inner.clear();
        self.last_index = None;
    }

    fn heap_size<F: FnMut(usize, usize)>(&self, callback: F) {
        self.inner.heap_size(callback);
    }

    fn reborrow<'b, 'a: 'b>(item: Self::ReadItem<'a>) -> Self::ReadItem<'b>
    where
        Self: 'a,
    {
        R::reborrow(item)
    }
}

impl<R, T> Push<T> for CollapseSequence<R>
where
    R: Region + Push<T>,
    for<'a> T: PartialEq<R::ReadItem<'a>>,
{
    fn push(&mut self, item: T) -> <CollapseSequence<R> as Region>::Index {
        if let Some(last_index) = self.last_index {
            if item == self.inner.index(last_index) {
                return last_index;
            }
        }
        let index = self.inner.push(item);
        self.last_index = Some(index);
        index
    }
}

/// Transform an index of `(usize, usize)` to a sequence of `0..`. Requires the pairs to
/// be dense, i.e., `(i, j)` is followed by `(j, k)`.
///
/// Defers to region `R` for storing items, and uses offset container `O` to
/// remeber indices. By default, `O` is `Vec<usize>`.
///
/// # Examples
///
/// The following example shows that two inserts into a copy region have a collapsible index:
/// ```
/// use flatcontainer::impls::deduplicate::{CollapseSequence, ConsecutiveOffsetPairs};
/// use flatcontainer::{Push, OwnedRegion, Region, StringRegion};
/// let mut r = <ConsecutiveOffsetPairs<OwnedRegion<u8>>>::default();
///
/// let index: usize = r.push(&b"abc");
/// assert_eq!(b"abc", r.index(index));
/// ```
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ConsecutiveOffsetPairs<R, O = OffsetOptimized> {
    /// Wrapped region
    inner: R,
    /// Storage for offsets. Always stores element 0.
    offsets: O,
    /// The most recent end of the index pair of region `R`.
    last_index: usize,
}

impl<R: Clone, O: Clone> Clone for ConsecutiveOffsetPairs<R, O> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            offsets: self.offsets.clone(),
            last_index: self.last_index,
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.inner.clone_from(&source.inner);
        self.offsets.clone_from(&source.offsets);
        self.last_index = source.last_index;
    }
}

impl<R, O> Default for ConsecutiveOffsetPairs<R, O>
where
    R: Default,
    O: OffsetContainer<usize>,
{
    #[inline]
    fn default() -> Self {
        let mut d = Self {
            inner: Default::default(),
            offsets: Default::default(),
            last_index: 0,
        };
        d.offsets.push(0);
        d
    }
}

impl<R, O> Region for ConsecutiveOffsetPairs<R, O>
where
    R: Region<Index = (usize, usize)>,
    O: OffsetContainer<usize>,
{
    type Owned = R::Owned;
    type ReadItem<'a> = R::ReadItem<'a>
    where
        Self: 'a;

    type Index = usize;

    #[inline]
    fn merge_regions<'a>(regions: impl Iterator<Item = &'a Self> + Clone) -> Self
    where
        Self: 'a,
    {
        let mut offsets = O::default();
        offsets.push(0);
        Self {
            inner: R::merge_regions(regions.map(|r| &r.inner)),
            offsets,
            last_index: 0,
        }
    }

    #[inline]
    fn index(&self, index: Self::Index) -> Self::ReadItem<'_> {
        self.inner
            .index((self.offsets.index(index), self.offsets.index(index + 1)))
    }

    #[inline]
    fn reserve_regions<'a, I>(&mut self, regions: I)
    where
        Self: 'a,
        I: Iterator<Item = &'a Self> + Clone,
    {
        self.inner.reserve_regions(regions.map(|r| &r.inner));
    }

    #[inline]
    fn clear(&mut self) {
        self.last_index = 0;
        self.inner.clear();
        self.offsets.clear();
        self.offsets.push(0);
    }

    #[inline]
    fn heap_size<F: FnMut(usize, usize)>(&self, mut callback: F) {
        self.offsets.heap_size(&mut callback);
        self.inner.heap_size(callback);
    }

    #[inline]
    fn reborrow<'b, 'a: 'b>(item: Self::ReadItem<'a>) -> Self::ReadItem<'b>
    where
        Self: 'a,
    {
        R::reborrow(item)
    }
}

impl<R, O, T> Push<T> for ConsecutiveOffsetPairs<R, O>
where
    R: Region<Index = (usize, usize)> + Push<T>,
    O: OffsetContainer<usize>,
{
    #[inline]
    fn push(&mut self, item: T) -> <ConsecutiveOffsetPairs<R, O> as Region>::Index {
        let index = self.inner.push(item);
        debug_assert_eq!(index.0, self.last_index);
        self.last_index = index.1;
        self.offsets.push(index.1);
        self.offsets.len() - 2
    }
}

impl<R, O, T> ReserveItems<T> for ConsecutiveOffsetPairs<R, O>
where
    R: Region<Index = (usize, usize)> + ReserveItems<T>,
    O: OffsetContainer<usize>,
{
    fn reserve_items<I>(&mut self, items: I)
    where
        I: Iterator<Item = T> + Clone,
    {
        self.inner.reserve_items(items);
    }
}

#[cfg(test)]
mod tests {
    use crate::impls::deduplicate::{CollapseSequence, ConsecutiveOffsetPairs};
    use crate::impls::offsets::OffsetOptimized;
    use crate::{FlatStack, Push, StringRegion};

    #[test]
    fn test_dedup_flatstack() {
        let mut fs = FlatStack::<CollapseSequence<StringRegion>>::default();

        fs.copy("abc");
        fs.copy("abc");

        assert_eq!(2, fs.len());

        println!("{fs:?}");
    }

    #[test]
    fn test_dedup_region() {
        let mut r = CollapseSequence::<StringRegion>::default();

        assert_eq!(r.push("abc"), r.push("abc"));

        println!("{r:?}");
    }

    #[test]
    fn test_offset_optimized() {
        let mut r =
            CollapseSequence::<ConsecutiveOffsetPairs<StringRegion, OffsetOptimized>>::default();

        for _ in 0..1000 {
            let _ = r.push("abc");
        }

        println!("{r:?}");
    }
}