refraction-types 0.1.3

Zero-dependency bounded ring buffer for networking workloads with predictable overwrite-on-full semantics, minimal allocations, and an ergonomic byte-oriented API.
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
use crate::{
    BOUNDED_RING_BUFFER_DEFAULT_SIZE,
    ring_iter::{IntoIter, Iter, IterMut},
};

#[derive(Debug, Clone)]
pub struct BoundedRingBuffer<T> {
    pub(crate) data: Vec<T>,
    pub(crate) get_idx: usize,
    pub(crate) put_idx: usize,
    pub(crate) capacity: usize,
    pub(crate) len: usize,
}

impl<T> BoundedRingBuffer<T>
where
    T: Copy + Default,
{
    /// Creates a buffer with the default capacity.
    #[must_use]
    pub fn new() -> Self {
        Self::with_capacity(BOUNDED_RING_BUFFER_DEFAULT_SIZE)
    }

    /// Creates a buffer with a fixed capacity.
    ///
    /// # Panics
    ///
    /// Panics if `cap` is `0`.
    #[must_use]
    pub fn with_capacity(cap: usize) -> Self {
        assert_ne!(cap, 0, "Capacity cannot be zero!");
        Self {
            data: vec![T::default(); cap],
            put_idx: 0,
            get_idx: 0,
            capacity: cap,
            len: 0,
        }
    }

    /// Returns the number of currently stored elements.
    #[must_use]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns the maximum number of elements the buffer can store.
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns the current read index.
    #[must_use]
    pub fn get_idx(&self) -> usize {
        self.get_idx
    }

    /// Returns the current write index.
    #[must_use]
    pub fn put_idx(&self) -> usize {
        self.put_idx
    }

    /// Returns `true` when the buffer has no readable elements.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.get_idx == self.put_idx && self.len == 0
    }

    /// Returns an iterator over readable elements in logical queue order.
    #[must_use]
    pub fn iter(&self) -> Iter<'_, T> {
        if self.is_empty() {
            return Iter([].iter().chain([].iter()));
        }

        let (first, second) = self.as_slice();

        let second_iter = match second {
            Some(slice) => slice.iter(),
            None => [].iter(),
        };

        Iter(first.iter().chain(second_iter))
    }

    /// Returns a mutable iterator over readable elements in logical queue order.
    #[must_use]
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        if self.is_empty() {
            return IterMut([].iter_mut().chain([].iter_mut()));
        }

        let (first, second) = self.as_mut_slice();

        let second_iter = match second {
            Some(slice) => slice.iter_mut(),
            None => [].iter_mut(),
        };

        IterMut(first.iter_mut().chain(second_iter))
    }

    // into_iter is implemented via IntoIterator trait below

    /// Discards `n` elements from the front of the buffer without copying them.
    ///
    /// If `n` exceeds the number of available elements, all elements are discarded.
    pub fn consume(&mut self, n: usize) {
        let n = n.min(self.len);
        self.get_idx = (self.get_idx + n) % self.capacity;
        self.len -= n;
    }

    /// Returns `true` when all capacity is occupied.
    #[must_use]
    pub fn full(&self) -> bool {
        self.get_idx == self.put_idx && self.len == self.capacity
    }

    /// Returns a shared reference to the element at the current write index.
    ///
    /// This does not modify buffer state.
    #[must_use]
    pub fn back(&self) -> Option<&T> {
        if self.is_empty() {
            None
        } else {
            Some(&self.data[(self.put_idx + self.capacity - 1) % self.capacity])
        }
    }

    /// Returns a mutable reference to the element at the current write index - 1.
    ///
    /// This does not modify indices or length.
    #[must_use]
    pub fn back_mut(&mut self) -> Option<&mut T> {
        if self.is_empty() {
            None
        } else {
            Some(&mut self.data[(self.put_idx + self.capacity - 1) % self.capacity])
        }
    }

    /// Returns a shared reference to the front readable element.
    #[must_use]
    pub fn front(&self) -> Option<&T> {
        if self.is_empty() {
            None
        } else {
            Some(&self.data[self.get_idx])
        }
    }

    /// Returns a mutable reference to the front readable element.
    #[must_use]
    pub fn front_mut(&mut self) -> Option<&mut T> {
        if self.is_empty() {
            None
        } else {
            let idx = self.get_idx;
            Some(&mut self.data[idx])
        }
    }

    /// Enqueues a single element.
    ///
    /// When the buffer is full, the oldest element is overwritten.
    pub fn enqueue(&mut self, data: T) {
        if self.full() {
            self.get_idx = (self.get_idx + 1) % self.capacity;
        } else {
            self.len += 1;
        }

        self.data[self.put_idx] = data;
        self.put_idx = (self.put_idx + 1) % self.capacity;
    }

    /// Dequeues and returns the front element, or `None` if empty.
    #[must_use]
    pub fn dequeue(&mut self) -> Option<T> {
        if self.is_empty() {
            return None;
        }

        let item = self.data[self.get_idx];
        self.get_idx = (self.get_idx + 1) % self.capacity;
        self.len -= 1;

        Some(item)
    }

    /// Advances the write cursor by `size` slots as if `size` items were written.
    ///
    /// If this exceeds available space, the oldest elements are dropped.
    pub fn advance(&mut self, size: usize) {
        let size = size.min(self.capacity);

        let new_put_idx = (self.put_idx + size) % self.capacity;
        let remaining_space = self.capacity - self.len;
        let offset = size.saturating_sub(remaining_space);
        let new_get_idx = (self.get_idx + offset) % self.capacity;

        self.get_idx = new_get_idx;
        self.put_idx = new_put_idx;
        self.len = (self.len + size).min(self.capacity);
    }

    /// Enqueues a slice of elements preserving order.
    ///
    /// This is the recommended high-throughput API for streaming workloads.
    ///
    /// If `data` is larger than capacity, only the last `capacity` elements are kept.
    pub fn enqueue_slice(&mut self, data: &[T]) {
        match data.len().cmp(&self.capacity) {
            std::cmp::Ordering::Less => {
                let new_put_idx = (self.put_idx + data.len()) % self.capacity;
                let remaining_space = self.capacity - self.len;
                let offset = data.len().saturating_sub(remaining_space);
                let new_get_idx = (self.get_idx + offset) % self.capacity;

                //we are wrapped now
                if new_put_idx < self.put_idx {
                    //copy from put to the end
                    let middle = self.capacity - self.put_idx;
                    self.data[self.put_idx..].copy_from_slice(&data[0..middle]);
                    self.data[..new_put_idx].copy_from_slice(&data[middle..]);
                } else {
                    self.data[self.put_idx..self.put_idx + data.len()].copy_from_slice(data);
                }

                self.get_idx = new_get_idx;
                self.put_idx = new_put_idx;
                self.len = (self.len + data.len()).min(self.capacity);
            }
            std::cmp::Ordering::Equal => {
                self.data.copy_from_slice(data);
                self.put_idx = 0;
                self.get_idx = 0;
                self.len = data.len();
            }
            std::cmp::Ordering::Greater => {
                let new_data_len = data.len();
                let start = new_data_len - self.capacity;
                let new_data = &data[start..new_data_len];
                self.enqueue_slice(new_data);
            }
        }
    }

    /// Dequeues up to `dequeue_size` elements into `out_buffer`.
    ///
    /// This is the recommended high-throughput API for draining buffered data.
    ///
    /// Returns the number of elements actually written to `out_buffer`.
    ///
    /// # Panics
    ///
    /// Panics if `out_buffer.len() < dequeue_size`.
    #[must_use]
    pub fn dequeue_slice(&mut self, out_buffer: &mut [T], dequeue_size: usize) -> usize {
        if self.is_empty() {
            return 0;
        }

        assert!(
            out_buffer.len() >= dequeue_size,
            "Dequeue size cannot be greater than out buffer"
        );

        match dequeue_size.cmp(&self.len) {
            std::cmp::Ordering::Less => {
                let new_get_idx = (self.get_idx + dequeue_size) % self.capacity;

                if new_get_idx < self.get_idx {
                    let middle = self.capacity - self.get_idx;
                    out_buffer[0..middle].copy_from_slice(&self.data[self.get_idx..]);
                    out_buffer[middle..dequeue_size].copy_from_slice(&self.data[..new_get_idx]);
                } else {
                    out_buffer[0..dequeue_size]
                        .copy_from_slice(&self.data[self.get_idx..new_get_idx]);
                }

                self.get_idx = new_get_idx;
                self.len -= dequeue_size;

                dequeue_size
            }
            std::cmp::Ordering::Equal => {
                if self.get_idx >= self.put_idx {
                    let middle = self.capacity - self.get_idx;
                    out_buffer[0..middle].copy_from_slice(&self.data[self.get_idx..]);
                    out_buffer[middle..dequeue_size].copy_from_slice(&self.data[..self.put_idx]);
                } else {
                    out_buffer[0..dequeue_size]
                        .copy_from_slice(&self.data[self.get_idx..self.put_idx]);
                }
                self.get_idx = self.put_idx;
                self.len = 0;
                dequeue_size
            }
            std::cmp::Ordering::Greater => {
                self.dequeue_slice(&mut out_buffer[0..self.len], self.len)
            }
        }
    }

    /// Returns a contiguous slice of `len` elements starting at `offset` from the read cursor,
    /// or `None` if the range wraps around the buffer boundary.
    ///
    /// Does **not** consume any elements.
    #[must_use]
    pub fn try_peek_slice(&self, offset: usize, len: usize) -> Option<&[T]> {
        if offset + len > self.len {
            return None;
        }
        let start = (self.get_idx + offset) % self.capacity;
        let end = start + len;
        if end <= self.capacity {
            Some(&self.data[start..end])
        } else {
            None
        }
    }

    /// Copies readable elements into `out` starting at logical `offset`.
    ///
    /// This method does not modify buffer state and can be used to inspect
    /// bytes before deciding whether to consume them.
    ///
    /// Returns the number of copied elements (`out.len()`) on success, or `0`
    /// if the requested range is out of bounds or the buffer is empty.
    #[must_use]
    pub fn copy_out(&self, offset: usize, out: &mut [T]) -> usize {
        if self.is_empty() {
            return 0;
        }

        if offset + out.len() > self.len {
            return 0;
        }

        let len = out.len();
        let start = (self.get_idx + offset) % self.capacity;
        let end = start + len;
        if end <= self.capacity {
            out.copy_from_slice(&self.data[start..end]);
        } else {
            let middle = self.capacity - start;
            let wrapped_end = end - self.capacity;
            out[..middle].copy_from_slice(&self.data[start..]);
            out[middle..].copy_from_slice(&self.data[..wrapped_end]);
        }

        out.len()
    }

    /// Returns readable data as one contiguous slice plus an optional wrapped slice.
    #[must_use]
    pub fn as_slice(&self) -> (&[T], Option<&[T]>) {
        if self.get_idx < self.put_idx {
            (&self.data[self.get_idx..self.put_idx], None)
        } else {
            (&self.data[self.get_idx..], Some(&self.data[..self.put_idx]))
        }
    }

    /// Returns mutable readable data as one contiguous slice plus an optional wrapped slice.
    #[must_use]
    pub fn as_mut_slice(&mut self) -> (&mut [T], Option<&mut [T]>) {
        if self.get_idx < self.put_idx {
            (&mut self.data[self.get_idx..self.put_idx], None)
        } else {
            let (left, right) = self.data.split_at_mut(self.get_idx);
            (right, Some(&mut left[..self.put_idx]))
        }
    }
}
impl<T> IntoIterator for BoundedRingBuffer<T>
where
    T: Copy + Default,
{
    type Item = T;
    type IntoIter = IntoIter<T>;

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

impl<'a, T> IntoIterator for &'a BoundedRingBuffer<T>
where
    T: Copy + Default,
{
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;

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

impl<'a, T> IntoIterator for &'a mut BoundedRingBuffer<T>
where
    T: Copy + Default,
{
    type Item = &'a mut T;
    type IntoIter = IterMut<'a, T>;

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