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
use super::RbWrap;
use core::{
    mem::MaybeUninit,
    num::NonZeroUsize,
    ops::{Deref, Range},
    ptr, slice,
};

#[cfg(feature = "alloc")]
use alloc::{rc::Rc, sync::Arc};

/// Basic ring buffer functionality.
///
/// Provides an access to raw underlying memory and `head`/`tail` counters.
///
/// *It is recommended not to use this trait directly. Use [`Producer`](`crate::Producer`) and [`Consumer`](`crate::Consumer`) instead.*
///
/// # Details
///
/// The ring buffer consists of an array (of `capacity` size) and two counters: `head` and `tail`.
/// When an item is extracted from the ring buffer it is taken from the `head` position and after that `head` is incremented.
/// New item is appended to the `tail` position and `tail` is incremented after that.
///
/// The `head` and `tail` counters are modulo `2 * capacity` (not just `capacity`).
/// It allows us to distinguish situations when the buffer is empty (`head == tail`) and when the buffer is full (`tail - head` modulo `2 * capacity` equals to `capacity`)
/// without using the space for an extra element in container.
/// And obviously we cannot store more than `capacity` items in the buffer, so `tail - head` modulo `2 * capacity` is not allowed to be greater than `capacity`.
pub trait RbBase<T> {
    /// Returns underlying raw ring buffer memory as slice.
    ///
    /// # Safety
    ///
    /// Modifications of this data must properly update `head` and `tail` positions.
    ///
    /// *Accessing raw data is extremely unsafe.*
    /// It is recommended to use [`Consumer::as_slices`](`crate::Consumer::as_slices`) and [`Producer::free_space_as_slices`](`crate::Producer::free_space_as_slices`) instead.
    #[allow(clippy::mut_from_ref)]
    unsafe fn data(&self) -> &mut [MaybeUninit<T>];

    /// Capacity of the ring buffer.
    ///
    /// It is constant during the whole ring buffer lifetime.
    fn capacity(&self) -> NonZeroUsize;

    /// Head position.
    fn head(&self) -> usize;

    /// Tail position.
    fn tail(&self) -> usize;

    /// Modulus for `head` and `tail` values.
    ///
    /// Equals to `2 * len`.
    #[inline]
    fn modulus(&self) -> NonZeroUsize {
        unsafe { NonZeroUsize::new_unchecked(2 * self.capacity().get()) }
    }

    /// The number of items stored in the buffer at the moment.
    fn occupied_len(&self) -> usize {
        let modulus = self.modulus();
        (modulus.get() + self.tail() - self.head()) % modulus
    }

    /// The number of vacant places in the buffer at the moment.
    fn vacant_len(&self) -> usize {
        let modulus = self.modulus();
        (self.capacity().get() + self.head() - self.tail()) % modulus
    }

    /// Checks if the occupied range is empty.
    fn is_empty(&self) -> bool {
        self.head() == self.tail()
    }

    /// Checks if the vacant range is empty.
    fn is_full(&self) -> bool {
        self.vacant_len() == 0
    }
}

/// Ring buffer read end.
///
/// Provides access to occupied memory and mechanism of item extraction.
///
/// *It is recommended not to use this trait directly. Use [`Producer`](`crate::Producer`) and [`Consumer`](`crate::Consumer`) instead.*
pub trait RbRead<T>: RbBase<T> {
    /// Sets the new **head** position.
    ///
    /// # Safety
    ///
    /// This call must cohere with ring buffer data modification.
    ///
    /// It is recommended to use `Self::advance_head` instead.
    unsafe fn set_head(&self, value: usize);

    /// Move **head** position by `count` items forward.
    ///
    /// # Safety
    ///
    /// First `count` items in occupied area must be **initialized** before this call.
    ///
    /// *In debug mode panics if `count` is greater than number of items in the ring buffer.*
    unsafe fn advance_head(&self, count: usize) {
        debug_assert!(count <= self.occupied_len());
        self.set_head((self.head() + count) % self.modulus());
    }

    /// Returns a pair of slices which contain, in order, the occupied cells in the ring buffer.
    ///
    /// All items in slices are guaranteed to be **initialized**.
    ///
    /// *The slices may not include items pushed to the buffer by the concurring producer right after this call.*
    fn occupied_ranges(&self) -> (Range<usize>, Range<usize>) {
        let head = self.head();
        let tail = self.tail();
        let len = self.capacity();

        let (head_div, head_mod) = (head / len, head % len);
        let (tail_div, tail_mod) = (tail / len, tail % len);

        if head_div == tail_div {
            (head_mod..tail_mod, 0..0)
        } else {
            (head_mod..len.get(), 0..tail_mod)
        }
    }

    /// Provides a direct mutable access to the ring buffer occupied memory.
    ///
    /// Returns a pair of slices of stored items, the second one may be empty.
    /// Elements with lower indices in slice are older. First slice contains older items that second one.
    ///
    /// # Safety
    ///
    /// All items are initialized. Elements must be removed starting from the beginning of first slice.
    /// When all items are removed from the first slice then items must be removed from the beginning of the second slice.
    ///
    /// *This method must be followed by [`Self::advance_head`] call with the number of items being removed previously as argument.*
    /// *No other mutating calls allowed before that.*
    unsafe fn occupied_slices(&self) -> (&mut [MaybeUninit<T>], &mut [MaybeUninit<T>]) {
        let ranges = self.occupied_ranges();
        let ptr = self.data().as_mut_ptr();
        (
            slice::from_raw_parts_mut(ptr.add(ranges.0.start), ranges.0.len()),
            slice::from_raw_parts_mut(ptr.add(ranges.1.start), ranges.1.len()),
        )
    }

    /// Removes items from the head of ring buffer and drops them.
    ///
    /// + If `count_or_all` is `Some(count)` then exactly `count` items will be removed.
    ///   *In debug mode panics if `count` is greater than number of items stored in the buffer.*
    /// + If `count_or_all` is `None` then all items in ring buffer will be removed.
    ///   *If there is concurring producer activity then the buffer may be not empty after this call.*
    ///
    /// Returns the number of removed items.
    ///
    /// # Safety
    ///
    /// Must not be called concurrently.
    unsafe fn skip(&self, count_or_all: Option<usize>) -> usize {
        let (left, right) = self.occupied_slices();
        let count = match count_or_all {
            Some(count) => {
                debug_assert!(count <= left.len() + right.len());
                count
            }
            None => left.len() + right.len(),
        };
        for elem in left.iter_mut().chain(right.iter_mut()).take(count) {
            ptr::drop_in_place(elem.as_mut_ptr());
        }
        self.advance_head(count);
        count
    }
}

/// Ring buffer write end.
///
/// Provides access to vacant memory and mechanism of item insertion.
///
/// *It is recommended not to use this trait directly. Use [`Producer`](`crate::Producer`) and [`Consumer`](`crate::Consumer`) instead.*
pub trait RbWrite<T>: RbBase<T> {
    /// Sets the new **tail** position.
    ///
    /// # Safety
    ///
    /// This call must cohere with ring buffer data modification.
    ///
    /// It is recommended to use `Self::advance_tail` instead.
    unsafe fn set_tail(&self, value: usize);

    /// Move **tail** position by `count` items forward.
    ///
    /// # Safety
    ///
    /// First `count` items in vacant area must be **de-initialized** (dropped) before this call.
    ///
    /// *In debug mode panics if `count` is greater than number of vacant places in the ring buffer.*
    unsafe fn advance_tail(&self, count: usize) {
        debug_assert!(count <= self.vacant_len());
        self.set_tail((self.tail() + count) % self.modulus());
    }

    /// Returns a pair of slices which contain, in order, the vacant cells in the ring buffer.
    ///
    /// All items in slices are guaranteed to be *un-initialized*.
    ///
    /// *The slices may not include cells freed by the concurring consumer right after this call.*
    fn vacant_ranges(&self) -> (Range<usize>, Range<usize>) {
        let head = self.head();
        let tail = self.tail();
        let len = self.capacity();

        let (head_div, head_mod) = (head / len, head % len);
        let (tail_div, tail_mod) = (tail / len, tail % len);

        if head_div == tail_div {
            (tail_mod..len.get(), 0..head_mod)
        } else {
            (tail_mod..head_mod, 0..0)
        }
    }

    /// Provides a direct access to the ring buffer vacant memory.
    /// Returns a pair of slices of uninitialized memory, the second one may be empty.
    ///
    /// # Safety
    ///
    /// Vacant memory is uninitialized. Initialized items must be put starting from the beginning of first slice.
    /// When first slice is fully filled then items must be put to the beginning of the second slice.
    ///
    /// *This method must be followed by [`Self::advance_tail`] call with the number of items being put previously as argument.*
    /// *No other mutating calls allowed before that.*
    unsafe fn vacant_slices(&self) -> (&mut [MaybeUninit<T>], &mut [MaybeUninit<T>]) {
        let ranges = self.vacant_ranges();
        let ptr = self.data().as_mut_ptr();
        (
            slice::from_raw_parts_mut(ptr.add(ranges.0.start), ranges.0.len()),
            slice::from_raw_parts_mut(ptr.add(ranges.1.start), ranges.1.len()),
        )
    }
}

/// An abstract ring buffer.
pub trait Rb<T>: RbRead<T> + RbWrite<T> {}

/// An abstract reference to the ring buffer.
pub trait RbRef: Deref<Target = Self::Rb> {
    type Rb;
}

impl<'a, B> RbRef for RbWrap<B> {
    type Rb = B;
}
impl<'a, B> RbRef for &'a B {
    type Rb = B;
}
#[cfg(feature = "alloc")]
impl<B> RbRef for Rc<B> {
    type Rb = B;
}
#[cfg(feature = "alloc")]
impl<B> RbRef for Arc<B> {
    type Rb = B;
}