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
//!
//! # CircularBuffer
//!
//! A zero dependencies, zero run-time allocation, circular buffer.
//!
//! This crates provide a simple circular buffer that does not do any allocation at run time. The
//! main focus of this crate is correctess and performances.
//!
//! The circular buffer never wait, if the buffer is full, it overwrite the first element.
//!
//! The API is extremelly simple, you create the buffer specify how many elements the buffer can
//! hold. Then you can start pushing elements into it.
//!
//! ```
//! use rbl_circular_buffer::*;
//!
//! let mut buffer = CircularBuffer::new(3);
//! assert_eq!(0, buffer.len());
//!
//! buffer.push(1);
//! assert_eq!(1, buffer.len());
//!
//! buffer.push(2);
//! assert_eq!(2, buffer.len());
//!
//! buffer.push(3);
//! assert_eq!(3, buffer.len());
//!
//! // now the buffer is full, we can insert the next element, but it will overwrite the first one
//! buffer.push(4);
//! assert_eq!(3, buffer.len());
//!
//! let v: Vec<u32> = buffer.collect();
//! assert_eq!(vec![2,3,4], v);
//! ```
//! There are two ways to read the elements from the buffer.
//! 1. `CircularBuffer` implement the `Iterator` trait, you can loop over it.
//! 2. `CircularBuffer` provided the `.fill()` method.
//!
//! ## Using the iterator
//!
//! The iterator will consume the elements in the buffer.
//!
//! ```
//! use rbl_circular_buffer::*;
//!
//! let mut buffer = CircularBuffer::new(3);
//! buffer.push(1);
//! buffer.push(2);
//! buffer.push(3);
//!
//! let mut sum = 0;
//! for element in &mut buffer {
//!     sum += element;
//! }
//! assert_eq!(1 + 2 + 3, sum);
//! assert_eq!(0, buffer.len());
//! ```
//!
//! ## Filling a vector
//!
//! In demanding application, the iterator can be a bad choice.
//!
//! Think about communication between threads, each thread can have a reference to the
//! `CircularBuffer` and take a lock while reading from it. If the reading operation are not fast
//! enough, or simply if there are too many elements, the lock will be hold for a long period of
//! time. The alternative is to fill a vector.
//!
//! ```
//! use rbl_circular_buffer::*;
//!
//! // let's make a bigger vector
//! let mut buffer = CircularBuffer::new(5);
//! for i in 1..=5 {
//!     buffer.push(i);
//! }
//!
//! // with this vector we will remove the first 3 elements
//! let mut v = Vec::with_capacity(3);
//!
//! buffer.fill(&mut v);
//! assert_eq!(vec![1, 2, 3], v);
//!
//! // in the vector there are still 4 and 5
//! assert_eq!(2, buffer.len());
//!
//! buffer.push(6);
//! buffer.push(7);
//! buffer.push(8);
//!
//! // the fill avoid any allocation even in the vector to fill.
//! // if we remove one element, and refill, we will push only one element.
//! // this because `.fill()` does not allocate any memory.
//!
//! v.remove(0);
//!
//! buffer.fill(&mut v);
//!
//! assert_eq!(vec![2, 3, 4], v);
//! assert_eq!(4, buffer.len())
//! ```
//!

use std::convert::TryInto;

#[cfg(test)]
mod tests;

#[derive(Copy)]
pub struct CircularBuffer<T> {
    buffer: *mut T,
    // writing pointer
    w: usize,
    // reading pointer
    r: usize,
    size: usize,
    full: bool,
}

impl<T> CircularBuffer<T> {
    /// Create a new CircularBuffer of size `size`.
    ///
    /// It allocate an array of exactly size element, if the allocation fail, the method panic.
    ///
    /// Negligible amount of space used by the CircularBuffer beside the array itself.
    pub fn new(size: usize) -> Self {
        let size = size;
        let type_size = std::mem::size_of::<T>();
        let vector_size = type_size.checked_mul(size).unwrap();
        let aligment = std::mem::align_of::<T>();

        let layout = std::alloc::Layout::from_size_align(vector_size, aligment).unwrap();
        let ptr = unsafe { std::alloc::alloc_zeroed(layout) };

        CircularBuffer {
            buffer: ptr.cast(),
            w: 0,
            r: 0,
            size,
            full: false,
        }
    }

    /// Returns the amount of elements in the CircularBuffer in O(1)
    pub fn len(&self) -> usize {
        if self.full {
            return self.size;
        }
        if self.w > self.r {
            self.w - self.r
        } else if self.w == self.r {
            0
        } else {
            self.size - self.r + self.w
        }
    }

    fn next_inc(&self, i: usize) -> usize {
        (i + 1) % self.size
    }

    fn w_inc(&mut self) {
        self.w = self.next_inc(self.w);
    }

    fn r_inc(&mut self) {
        self.r = self.next_inc(self.r);
    }

    fn r_inc_of(&mut self, n: usize) {
        self.r = (self.r + n) % self.size;
    }

    fn write(&mut self, value: T) {
        let w_index = self.w;
        self.w_inc();
        unsafe {
            self.buffer.add(w_index).write(value);
        }
    }

    fn read(&mut self) -> T {
        let r_index = self.r;
        self.r_inc();
        unsafe {
            let ptr = self.buffer.add(r_index);
            ptr.read()
        }
    }

    fn drop(&mut self) {
        unsafe {
            let ptr = self.buffer.offset(self.w.try_into().unwrap());
            std::ptr::drop_in_place(ptr);
        }
    }

    /// Push a new element into the CircularBuffer in O(1) does not do any allocation.
    ///
    /// If the CircularBuffer is full, the first element of the CircularBuffer is overwritten.
    pub fn push(&mut self, value: T) -> usize {
        if self.full {
            // pointer to w must first be free, and the overwritten
            self.drop();
            self.r_inc();
        }
        self.write(value);
        if self.w == self.r {
            self.full = true;
            0
        } else {
            self.size - self.len()
        }
    }

    /// Main method to read elements out of the CircularBuffer.
    ///
    /// The return vector get filled, with as many as possible elements from the CircularBuffer.
    ///
    /// The available elements in the CircularBuffer are the same returned by the method `len`. The elements
    /// that the vector can accepts are given by `return_vector.capacity() - return_vector.len()`
    ///
    /// The method avoids allocating memory.
    ///
    /// Hence if the vector is already full, no elements are pushed into the vector.
    ///
    /// If the CircularBuffer is empty, no elements are pushed into the vector.
    ///
    /// If the vector can accept more elements that are prensent in the CircularBuffer, the vector
    /// get filled as much as possible and the CircularBuffer will remain empty.
    ///
    /// If the vector cannot accept all the element in the CircularBuffer, the vector get filled
    /// while the CircularBuffer will be left with some elements inside.
    ///
    /// The operation runs in O(n) with `n` number of elements pushed into the vector.
    pub fn fill(&mut self, return_vector: &mut Vec<T>) -> usize {
        let mut i = 0;
        while return_vector.capacity() - return_vector.len() > 0 {
            match self.next() {
                Some(element) => {
                    return_vector.push(element);
                    i += 1;
                }
                None => return i,
            }
        }
        i
    }

    fn split_in_ranges(&self) -> (std::ops::Range<usize>, Option<std::ops::Range<usize>>) {
        if self.r < self.w {
            (self.r..self.w, None)
        } else if self.r == self.w {
            if self.full {
                (self.r..self.size, Some(0..self.w))
            } else {
                (self.r..self.r, None)
            }
        } else {
            (self.r..self.size, Some(0..self.w))
        }
    }

    fn fill_vector_from_split(&mut self, range: std::ops::Range<usize>, vec: &mut Vec<T>) -> usize {
        let sink_capacity = vec.capacity() - vec.len();
        if sink_capacity == 0 {
            return 0;
        }
        if range.len() == 0 {
            return 0;
        }
        let to_push = if range.len() <= sink_capacity {
            range
        } else {
            let mut r = range;
            r.end = r.start + sink_capacity;
            r
        };

        unsafe {
            let ptr = vec.as_mut_ptr().add(vec.len());
            std::ptr::copy_nonoverlapping(self.buffer.add(to_push.start), ptr, to_push.len());
            vec.set_len(vec.len() + to_push.len());
        }

        self.r_inc_of(to_push.len());
        self.full = false;
        return to_push.len();
    }

    /// The `_fast_fill` method is supposed to be a faster alternative to the `fill` one.
    /// However, benchmarks failed to show any difference in performance.
    /// If the benchmark showed any difference, it was the `_fast_fill` method being a little slower.
    ///
    /// The `_fast_fill` method is more complex that the `fill` method, so I suggest to rely on the
    /// simpler `fill`. However both methods passed the same properties tests, so they should be
    /// equally correct.
    ///
    /// The `_fast_fill` is implemented using raw pointer and memcopy. While the `fill` method
    /// pull elements using the iterator and simply push them to the back of the vector.
    pub fn _fast_fill(&mut self, return_vector: &mut Vec<T>) -> usize {
        if self.len() == 0 {
            return 0;
        }
        let sink_capacity = return_vector.capacity() - return_vector.len();
        if sink_capacity == 0 {
            return 0;
        }
        let mut total_pushed = 0;
        let (r1, r2) = self.split_in_ranges();
        total_pushed += self.fill_vector_from_split(r1, return_vector);
        if total_pushed == sink_capacity {
            return total_pushed;
        }
        if let Some(r2) = r2 {
            total_pushed += self.fill_vector_from_split(r2, return_vector)
        }
        total_pushed
    }
}

impl<T: Clone> Clone for CircularBuffer<T> {
    fn clone(&self) -> Self {
        let mut new = CircularBuffer::new(self.size);
        new.w = self.w;
        new.r = self.r;
        new.size = self.size; // useless
        new.full = self.full;

        let (r1, r2) = self.split_in_ranges();
        for i in r1 {
            unsafe {
                let r_ptr = self.buffer.add(i);
                let e0 = r_ptr.read();
                let e1 = e0.clone();
                std::mem::forget(e0);
                let w_buffer = new.buffer as *mut T;
                let w_ptr = w_buffer.add(i);
                w_ptr.write(e1);
            }
        }
        if let Some(r2) = r2 {
            for i in r2 {
                unsafe {
                    let r_ptr = self.buffer.add(i);
                    let e0 = r_ptr.read();
                    let e1 = e0.clone();
                    std::mem::forget(e0);
                    let w_buffer = new.buffer as *mut T;
                    let w_ptr = w_buffer.add(i);
                    w_ptr.write(e1);
                }
            }
        }

        new
    }
}

/// Create an iterator, elements from the iterator are consumed and are not present anymore in the
/// buffer.
impl<T> std::iter::Iterator for CircularBuffer<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        match self.len() {
            0 => None,
            _ => {
                self.full = false;
                Some(self.read())
            }
        }
    }
    /// The size_hint is correct, it is not an hint but it is the correct value.
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.len(), Some(self.len()))
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for CircularBuffer<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.len() == 0 {
            return write!(f, "CircularBuffer(<empty>)");
        }
        write!(f, "CircularBuffer(")?;
        let mut fake_read = self.r;
        let read = fake_read.try_into().unwrap();
        let element = unsafe {
            let ptr = self.buffer.offset(read);
            ptr.read()
        };
        std::fmt::Debug::fmt(&element, f)?;
        std::mem::forget(element);
        fake_read = self.next_inc(fake_read);
        while fake_read != self.w {
            write!(f, ", ")?;
            let read = fake_read.try_into().unwrap();
            let element = unsafe {
                let ptr = self.buffer.offset(read);
                ptr.read()
            };
            std::fmt::Debug::fmt(&element, f)?;
            std::mem::forget(element);
            fake_read = self.next_inc(fake_read);
        }
        write!(
            f,
            ") w: {:?}, r: {:?}, size: {:?}, full: {:?}",
            self.w, self.r, self.size, self.full
        )
    }
}

impl<T: std::fmt::Display> std::fmt::Display for CircularBuffer<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.len() == 0 {
            return write!(f, "CircularBuffer(<empty>)");
        }
        write!(f, "CircularBuffer(")?;
        let mut fake_read = self.r;
        let read = fake_read.try_into().unwrap();
        let element = unsafe {
            let ptr = self.buffer.offset(read);
            ptr.read()
        };
        std::fmt::Display::fmt(&element, f)?;
        std::mem::forget(element);
        fake_read = self.next_inc(fake_read);
        while fake_read != self.w {
            write!(f, ", ")?;
            let read = fake_read.try_into().unwrap();
            let element = unsafe {
                let ptr = self.buffer.offset(read);
                ptr.read()
            };
            std::fmt::Display::fmt(&element, f)?;
            std::mem::forget(element);
            fake_read = self.next_inc(fake_read);
        }
        write!(f, ")")
    }
}