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
use super::{Container, Rb, RbBase, RbRead, RbWrite, SharedStorage};
use crate::{consumer::Consumer, producer::Producer};
use core::{
mem::{ManuallyDrop, MaybeUninit},
num::NonZeroUsize,
ptr,
sync::atomic::{AtomicUsize, Ordering},
};
use crossbeam_utils::CachePadded;
#[cfg(feature = "alloc")]
use alloc::sync::Arc;
#[cfg_attr(
feature = "std",
doc = r##"
```
use std::{thread, vec::Vec};
use ringbuf::SharedRb;
let (mut prod, mut cons) = SharedRb::<i32, Vec<_>>::new(256).split();
thread::spawn(move || {
prod.push(123).unwrap();
})
.join();
thread::spawn(move || {
assert_eq!(cons.pop().unwrap(), 123);
})
.join();
```
"##
)]
pub struct SharedRb<T, C: Container<T>> {
storage: SharedStorage<T, C>,
head: CachePadded<AtomicUsize>,
tail: CachePadded<AtomicUsize>,
}
impl<T, C: Container<T>> RbBase<T> for SharedRb<T, C> {
#[inline]
unsafe fn slices(
&self,
head: usize,
tail: usize,
) -> (&mut [MaybeUninit<T>], &mut [MaybeUninit<T>]) {
self.storage.as_mut_slices(head, tail)
}
#[inline]
fn capacity_nonzero(&self) -> NonZeroUsize {
self.storage.len()
}
#[inline]
fn head(&self) -> usize {
self.head.load(Ordering::Acquire)
}
#[inline]
fn tail(&self) -> usize {
self.tail.load(Ordering::Acquire)
}
}
impl<T, C: Container<T>> RbRead<T> for SharedRb<T, C> {
#[inline]
unsafe fn set_head(&self, value: usize) {
self.head.store(value, Ordering::Release)
}
}
impl<T, C: Container<T>> RbWrite<T> for SharedRb<T, C> {
#[inline]
unsafe fn set_tail(&self, value: usize) {
self.tail.store(value, Ordering::Release)
}
}
impl<T, C: Container<T>> Rb<T> for SharedRb<T, C> {}
impl<T, C: Container<T>> Drop for SharedRb<T, C> {
fn drop(&mut self) {
self.clear();
}
}
impl<T, C: Container<T>> SharedRb<T, C> {
pub unsafe fn from_raw_parts(container: C, head: usize, tail: usize) -> Self {
Self {
storage: SharedStorage::new(container),
head: CachePadded::new(AtomicUsize::new(head)),
tail: CachePadded::new(AtomicUsize::new(tail)),
}
}
pub unsafe fn into_raw_parts(self) -> (C, usize, usize) {
let (head, tail) = (self.head(), self.tail());
let self_ = ManuallyDrop::new(self);
(ptr::read(&self_.storage).into_inner(), head, tail)
}
#[cfg(feature = "alloc")]
pub fn split(self) -> (Producer<T, Arc<Self>>, Consumer<T, Arc<Self>>)
where
Self: Sized,
{
let arc = Arc::new(self);
unsafe { (Producer::new(arc.clone()), Consumer::new(arc)) }
}
pub fn split_ref(&mut self) -> (Producer<T, &Self>, Consumer<T, &Self>)
where
Self: Sized,
{
unsafe { (Producer::new(self), Consumer::new(self)) }
}
}