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
use super::{macros::rb_impl_init, utils::ranges};
#[cfg(feature = "alloc")]
use crate::traits::Split;
use crate::{
    storage::Storage,
    traits::{
        consumer::{impl_consumer_traits, Consumer},
        producer::{impl_producer_traits, Producer},
        Observer, RingBuffer, SplitRef,
    },
    wrap::{Cons, Prod},
};
#[cfg(feature = "alloc")]
use alloc::{boxed::Box, rc::Rc};
use core::{
    cell::Cell,
    mem::{ManuallyDrop, MaybeUninit},
    num::NonZeroUsize,
    ptr,
};

struct End {
    index: Cell<usize>,
    held: Cell<bool>,
}

impl End {
    fn new(index: usize) -> Self {
        Self {
            index: Cell::new(index),
            held: Cell::new(false),
        }
    }
}

/// Ring buffer for single-threaded use only.
///
/// Slightly faster than multi-threaded version because it doesn't synchronize cache.
pub struct LocalRb<S: Storage + ?Sized> {
    read: End,
    write: End,
    storage: S,
}

impl<S: Storage> LocalRb<S> {
    /// Constructs ring buffer from storage and indices.
    ///
    /// # Safety
    ///
    /// The items in storage inside `read..write` range must be initialized, items outside this range must be uninitialized.
    /// `read` and `write` positions must be valid (see implementation details).
    pub unsafe fn from_raw_parts(storage: S, read: usize, write: usize) -> Self {
        assert!(!storage.is_empty());
        Self {
            storage,
            read: End::new(read),
            write: End::new(write),
        }
    }
    /// Destructures ring buffer into underlying storage and `read` and `write` indices.
    ///
    /// # Safety
    ///
    /// Initialized contents of the storage must be properly dropped.
    pub unsafe fn into_raw_parts(self) -> (S, usize, usize) {
        let this = ManuallyDrop::new(self);
        (ptr::read(&this.storage), this.read_index(), this.write_index())
    }
}

impl<S: Storage + ?Sized> Observer for LocalRb<S> {
    type Item = S::Item;

    #[inline]
    fn capacity(&self) -> NonZeroUsize {
        unsafe { NonZeroUsize::new_unchecked(self.storage.len()) }
    }

    #[inline]
    fn read_index(&self) -> usize {
        self.read.index.get()
    }
    #[inline]
    fn write_index(&self) -> usize {
        self.write.index.get()
    }

    unsafe fn unsafe_slices(&self, start: usize, end: usize) -> (&[MaybeUninit<S::Item>], &[MaybeUninit<S::Item>]) {
        let (first, second) = ranges(self.capacity(), start, end);
        (self.storage.slice(first), self.storage.slice(second))
    }
    unsafe fn unsafe_slices_mut(&self, start: usize, end: usize) -> (&mut [MaybeUninit<S::Item>], &mut [MaybeUninit<S::Item>]) {
        let (first, second) = ranges(self.capacity(), start, end);
        (self.storage.slice_mut(first), self.storage.slice_mut(second))
    }

    #[inline]
    fn read_is_held(&self) -> bool {
        self.read.held.get()
    }
    #[inline]
    fn write_is_held(&self) -> bool {
        self.write.held.get()
    }
}

impl<S: Storage + ?Sized> Producer for LocalRb<S> {
    #[inline]
    unsafe fn set_write_index(&self, value: usize) {
        self.write.index.set(value);
    }
}

impl<S: Storage + ?Sized> Consumer for LocalRb<S> {
    #[inline]
    unsafe fn set_read_index(&self, value: usize) {
        self.read.index.set(value);
    }
}

impl<S: Storage + ?Sized> RingBuffer for LocalRb<S> {
    #[inline]
    unsafe fn hold_read(&self, flag: bool) -> bool {
        self.read.held.replace(flag)
    }
    #[inline]
    unsafe fn hold_write(&self, flag: bool) -> bool {
        self.write.held.replace(flag)
    }
}

impl<S: Storage + ?Sized> Drop for LocalRb<S> {
    fn drop(&mut self) {
        self.clear();
    }
}

#[cfg(feature = "alloc")]
impl<S: Storage> Split for LocalRb<S> {
    type Prod = Prod<Rc<Self>>;
    type Cons = Cons<Rc<Self>>;

    fn split(self) -> (Self::Prod, Self::Cons) {
        Rc::new(self).split()
    }
}
#[cfg(feature = "alloc")]
impl<S: Storage + ?Sized> Split for Rc<LocalRb<S>> {
    type Prod = Prod<Self>;
    type Cons = Cons<Self>;

    fn split(self) -> (Self::Prod, Self::Cons) {
        (Prod::new(self.clone()), Cons::new(self))
    }
}
#[cfg(feature = "alloc")]
impl<S: Storage + ?Sized> Split for Box<LocalRb<S>> {
    type Prod = Prod<Rc<LocalRb<S>>>;
    type Cons = Cons<Rc<LocalRb<S>>>;

    fn split(self) -> (Self::Prod, Self::Cons) {
        Rc::<LocalRb<S>>::from(self).split()
    }
}
impl<S: Storage + ?Sized> SplitRef for LocalRb<S> {
    type RefProd<'a> = Prod<&'a Self> where Self: 'a;
    type RefCons<'a> = Cons<&'a Self> where Self: 'a;

    fn split_ref(&mut self) -> (Self::RefProd<'_>, Self::RefCons<'_>) {
        (Prod::new(self), Cons::new(self))
    }
}

rb_impl_init!(LocalRb);

impl_producer_traits!(LocalRb<S: Storage>);
impl_consumer_traits!(LocalRb<S: Storage>);

impl<S: Storage + ?Sized> AsRef<Self> for LocalRb<S> {
    fn as_ref(&self) -> &Self {
        self
    }
}
impl<S: Storage + ?Sized> AsMut<Self> for LocalRb<S> {
    fn as_mut(&mut self) -> &mut Self {
        self
    }
}