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
//! Limited chunk buffer.

use rayon;

/// Limited buffer builder. Creates buffers using provided buffer parameters.
pub trait ChunkBufferBuilder<T: Send>: Default {
    /// Building buffer type
    type Buffer: ChunkBuffer<T>;

    /// Creates a new [`ChunkBuffer`] trait instance.
    fn build(&self) -> Self::Buffer;
}

/// Base limited buffer interface. Provides methods for pushing data to the buffer and checking buffer state.
pub trait ChunkBuffer<T: Send>: IntoIterator<Item = T> + rayon::slice::ParallelSliceMut<T> + Send {
    /// Adds a new element to the buffer.
    ///
    /// # Arguments
    /// * `item` - Item to be added to the buffer
    fn push(&mut self, item: T);

    /// Returns the buffer length.
    fn len(&self) -> usize;

    /// Checks if the buffer reached the limit.
    fn is_full(&self) -> bool;
}

/// [`LimitedBuffer`] builder.
pub struct LimitedBufferBuilder {
    buffer_limit: usize,
    preallocate: bool,
}

impl LimitedBufferBuilder {
    /// Creates a new instance of a builder.
    ///
    /// # Arguments
    /// * `buffer_limit` - Buffer size limit in element count
    /// * `preallocate` - If buffer should be preallocated
    pub fn new(buffer_limit: usize, preallocate: bool) -> Self {
        LimitedBufferBuilder {
            buffer_limit,
            preallocate,
        }
    }
}

impl<T: Send> ChunkBufferBuilder<T> for LimitedBufferBuilder {
    type Buffer = LimitedBuffer<T>;

    fn build(&self) -> Self::Buffer {
        if self.preallocate {
            LimitedBuffer::new(self.buffer_limit)
        } else {
            LimitedBuffer::with_capacity(self.buffer_limit)
        }
    }
}

impl Default for LimitedBufferBuilder {
    fn default() -> Self {
        LimitedBufferBuilder {
            buffer_limit: usize::MAX,
            preallocate: false,
        }
    }
}

/// Buffer limited by elements count.
pub struct LimitedBuffer<T> {
    limit: usize,
    inner: Vec<T>,
}

impl<T> LimitedBuffer<T> {
    /// Creates a new buffer instance.
    ///
    /// # Arguments
    /// * `limit` - Buffer elements count limit
    pub fn new(limit: usize) -> Self {
        LimitedBuffer {
            limit,
            inner: Vec::new(),
        }
    }

    /// Creates a new buffer instance with provided capacity.
    ///
    /// # Arguments
    /// * `limit` - Buffer elements count limit
    pub fn with_capacity(limit: usize) -> Self {
        LimitedBuffer {
            limit,
            inner: Vec::with_capacity(limit),
        }
    }
}

impl<T: Send> ChunkBuffer<T> for LimitedBuffer<T> {
    fn push(&mut self, item: T) {
        self.inner.push(item);
    }

    fn len(&self) -> usize {
        self.inner.len()
    }

    fn is_full(&self) -> bool {
        self.inner.len() >= self.limit
    }
}

impl<T> IntoIterator for LimitedBuffer<T> {
    type Item = T;
    type IntoIter = <Vec<T> as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.inner.into_iter()
    }
}

impl<T: Send> rayon::slice::ParallelSliceMut<T> for LimitedBuffer<T> {
    fn as_parallel_slice_mut(&mut self) -> &mut [T] {
        self.inner.as_mut_slice()
    }
}

#[cfg(test)]
mod test {
    use super::{ChunkBuffer, ChunkBufferBuilder, LimitedBufferBuilder};

    #[test]
    fn test_limited_buffer() {
        let builder = LimitedBufferBuilder::new(2, true);
        let mut buffer = builder.build();

        buffer.push(0);
        assert_eq!(buffer.is_full(), false);
        buffer.push(1);
        assert_eq!(buffer.is_full(), true);

        let data = Vec::from_iter(buffer);
        assert_eq!(data, vec![0, 1]);
    }
}

#[cfg(feature = "memory-limit")]
pub mod mem {
    use deepsize;
    use rayon;

    use super::{ChunkBuffer, ChunkBufferBuilder};

    /// [`MemoryLimitedBuffer`] builder.
    pub struct MemoryLimitedBufferBuilder {
        buffer_limit: u64,
    }

    impl MemoryLimitedBufferBuilder {
        /// Creates a new instance of a builder.
        ///
        /// # Arguments
        /// * `buffer_limit` - Buffer size limit in bytes
        pub fn new(buffer_limit: u64) -> Self {
            MemoryLimitedBufferBuilder { buffer_limit }
        }
    }

    impl<T: Send> ChunkBufferBuilder<T> for MemoryLimitedBufferBuilder
    where
        T: deepsize::DeepSizeOf,
    {
        type Buffer = MemoryLimitedBuffer<T>;

        fn build(&self) -> Self::Buffer {
            MemoryLimitedBuffer::new(self.buffer_limit)
        }
    }

    impl Default for MemoryLimitedBufferBuilder {
        fn default() -> Self {
            MemoryLimitedBufferBuilder { buffer_limit: u64::MAX }
        }
    }

    /// Buffer limited by consumed memory.
    pub struct MemoryLimitedBuffer<T> {
        limit: u64,
        current_size: u64,
        inner: Vec<T>,
    }

    impl<T> MemoryLimitedBuffer<T> {
        /// Creates a new instance of a buffer.
        ///
        /// # Arguments
        /// * `limit` - Buffer size limit in bytes
        pub fn new(limit: u64) -> Self {
            MemoryLimitedBuffer {
                limit,
                current_size: 0,
                inner: Vec::new(),
            }
        }

        /// Returns buffer size in bytes.
        pub fn mem_size(&self) -> u64 {
            self.current_size
        }
    }

    impl<T: Send> ChunkBuffer<T> for MemoryLimitedBuffer<T>
    where
        T: deepsize::DeepSizeOf,
    {
        fn push(&mut self, item: T) {
            self.current_size += item.deep_size_of() as u64;
            self.inner.push(item);
        }

        fn len(&self) -> usize {
            self.inner.len()
        }

        fn is_full(&self) -> bool {
            self.current_size >= self.limit
        }
    }

    impl<T> IntoIterator for MemoryLimitedBuffer<T> {
        type Item = T;
        type IntoIter = <Vec<T> as IntoIterator>::IntoIter;

        fn into_iter(self) -> Self::IntoIter {
            self.inner.into_iter()
        }
    }

    impl<T: Send> rayon::slice::ParallelSliceMut<T> for MemoryLimitedBuffer<T> {
        fn as_parallel_slice_mut(&mut self) -> &mut [T] {
            self.inner.as_mut_slice()
        }
    }

    #[cfg(test)]
    mod test {
        use deepsize;

        use super::{ChunkBuffer, ChunkBufferBuilder, MemoryLimitedBufferBuilder};

        #[derive(Debug, Clone, PartialEq, Eq, deepsize::DeepSizeOf)]
        struct MyType {
            number: i64,
            string: String,
        }

        #[test]
        fn test_memory_limited_buffer() {
            let builder = MemoryLimitedBufferBuilder::new(76);
            let mut buffer = builder.build();

            let item1 = MyType {
                number: 0,               // 8 bytes
                string: "hello!".into(), // 8 + 8 + 8 + 6 = 30 bytes
            };
            buffer.push(item1.clone());
            assert_eq!(buffer.mem_size(), 38);
            assert_eq!(buffer.is_full(), false);

            let item2 = MyType {
                number: 1,               // 8 bytes
                string: "world!".into(), // 8 + 8 + 8 + 6 = 30 bytes
            };
            buffer.push(item2.clone());
            assert_eq!(buffer.mem_size(), 76);
            assert_eq!(buffer.is_full(), true);

            let actual_data = Vec::from_iter(buffer);
            let expected_data = vec![item1, item2];
            assert_eq!(actual_data, expected_data);
        }
    }
}