-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathring_buf.rs
More file actions
318 lines (295 loc) · 9.49 KB
/
ring_buf.rs
File metadata and controls
318 lines (295 loc) · 9.49 KB
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
#![allow(clippy::undocumented_unsafe_blocks)]
#![cfg_attr(not(RUSTC_LINT_REASONS_IS_STABLE), feature(lint_reasons))]
#![cfg_attr(not(RUSTC_RAW_REF_OP_IS_STABLE), feature(raw_ref_op))]
#![cfg_attr(feature = "alloc", feature(allocator_api))]
#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::sync::Arc;
use core::{convert::Infallible, marker::PhantomPinned, mem::MaybeUninit, pin::Pin, ptr};
use pin_init::*;
#[cfg(feature = "std")]
use std::sync::Arc;
#[cfg(all(not(feature = "std"), feature = "alloc"))]
extern crate alloc;
#[allow(unused_attributes)]
#[path = "../examples/error.rs"]
mod error;
use error::Error;
#[pin_data(PinnedDrop)]
pub struct RingBuffer<T, const SIZE: usize> {
buffer: [MaybeUninit<T>; SIZE],
head: *mut T,
tail: *mut T,
#[pin]
_pin: PhantomPinned,
}
#[pinned_drop]
impl<T, const SIZE: usize> PinnedDrop for RingBuffer<T, SIZE> {
fn drop(self: Pin<&mut Self>) {
// SAFETY: We do not move `this`.
let this = unsafe { self.get_unchecked_mut() };
while !ptr::eq(this.tail, this.head) {
unsafe { this.tail.drop_in_place() };
this.tail = unsafe { this.advance(this.tail) };
}
}
}
impl<T, const SIZE: usize> RingBuffer<T, SIZE> {
pub fn new() -> impl PinInit<Self> {
assert!(SIZE > 0);
pin_init!(&this in Self {
// SAFETY: The elements of the array can be uninitialized.
buffer <- unsafe { init_from_closure(|_| Ok::<_, Infallible>(())) },
// SAFETY: `this` is a valid pointer.
head: unsafe { (&raw mut (*this.as_ptr()).buffer).cast::<T>() },
tail: unsafe { (&raw mut (*this.as_ptr()).buffer).cast::<T>() },
_pin: PhantomPinned,
})
}
pub fn push(self: Pin<&mut Self>, value: impl Init<T>) -> bool {
match self.try_push(value) {
Ok(res) => res,
Err(i) => match i {},
}
}
pub fn try_push<E>(self: Pin<&mut Self>, value: impl Init<T, E>) -> Result<bool, E> {
// SAFETY: We do not move `this`.
let this = unsafe { self.get_unchecked_mut() };
let next_head = unsafe { this.advance(this.head) };
// `head` and `tail` point into the same buffer.
if ptr::eq(next_head, this.tail) {
// We cannot advance `head`, since `next_head` would point to the same slot as `tail`,
// which is currently live.
return Ok(false);
}
// SAFETY: `head` always points to the next free slot.
unsafe { value.__init(this.head)? };
this.head = next_head;
Ok(true)
}
pub fn pop(self: Pin<&mut Self>) -> Option<T> {
// SAFETY: We do not move `this`.
let this = unsafe { self.get_unchecked_mut() };
if ptr::eq(this.head, this.tail) {
return None;
}
// SAFETY: `tail` always points to a valid element, or is the same as `head`.
let value = unsafe { this.tail.read() };
this.tail = unsafe { this.advance(this.tail) };
Some(value)
}
pub fn pop_no_stack(self: Pin<&mut Self>) -> Option<impl Init<T> + '_> {
// SAFETY: We do not move `this`.
let this = unsafe { self.get_unchecked_mut() };
if ptr::eq(this.head, this.tail) {
return None;
}
let remove_init = |slot| {
// SAFETY: `tail` always points to a valid element, or is the same as `head`.
unsafe { ptr::copy_nonoverlapping(this.tail, slot, 1) };
this.tail = unsafe { this.advance(this.tail) };
Ok(())
};
// SAFETY: the above initializer is correct.
Some(unsafe { init_from_closure(remove_init) })
}
/// # Safety
///
/// TODO
unsafe fn advance(&mut self, ptr: *mut T) -> *mut T {
// SAFETY: ptr's offset from buffer is < SIZE
let ptr = unsafe { ptr.add(1) };
let origin: *mut _ = &raw mut (self.buffer);
let origin = origin.cast::<T>();
let offset = unsafe { ptr.offset_from(origin) };
if offset >= SIZE as isize {
origin
} else {
ptr
}
}
}
#[test]
fn on_stack() -> Result<(), Infallible> {
stack_pin_init!(let buf = RingBuffer::<u8, 64>::new());
if let Some(elem) = buf.as_mut().pop() {
panic!("found in empty buffer!: {elem}");
}
assert!(buf.as_mut().push(10));
assert!(buf.as_mut().push(42));
assert_eq!(buf.as_mut().pop(), Some(10));
assert_eq!(buf.as_mut().pop(), Some(42));
assert_eq!(buf.as_mut().pop(), None);
assert!(buf.as_mut().push(42));
assert!(buf.as_mut().push(24));
assert_eq!(buf.as_mut().pop(), Some(42));
assert!(buf.as_mut().push(25));
assert_eq!(buf.as_mut().pop(), Some(24));
assert_eq!(buf.as_mut().pop(), Some(25));
assert_eq!(buf.as_mut().pop(), None);
for i in 0..63 {
assert!(buf.as_mut().push(i));
}
assert!(!buf.as_mut().push(42));
for i in 0..63 {
if let Some(value) = buf.as_mut().pop_no_stack() {
stack_pin_init!(let value = value);
assert_eq!(*value, i);
} else {
panic!("Expected more values");
}
}
assert_eq!(buf.as_mut().pop(), None);
Ok(())
}
#[derive(PartialEq, Eq, Debug)]
pub struct EvenU64 {
info: String,
data: u64,
}
impl EvenU64 {
#[allow(clippy::manual_is_multiple_of)]
pub fn new2(value: u64) -> impl Init<Self, Error> {
init!(Self {
info: "Hello world!".to_owned(),
data: if value % 2 == 0 {
value
} else {
return Err(Error);
},
}? Error)
}
#[allow(clippy::manual_is_multiple_of)]
pub fn new(value: u64) -> impl Init<Self, ()> {
init!(Self {
info: "Hello world!".to_owned(),
data: if value % 2 == 0 {
value
} else {
return Err(());
},
}?())
}
}
#[test]
fn even_stack() {
stack_try_pin_init!(let val = EvenU64::new(0));
assert_eq!(
val.as_deref_mut(),
Ok(&mut EvenU64 {
info: "Hello world!".to_owned(),
data: 0
})
);
stack_try_pin_init!(let val = EvenU64::new(1));
assert_eq!(val, Err(()));
}
#[test]
#[cfg(any(feature = "std", feature = "alloc"))]
fn even_failing() {
assert!(matches!(Box::try_pin_init(EvenU64::new2(3)), Err(Error)));
assert!(matches!(Box::try_init(EvenU64::new2(3)), Err(Error)));
assert!(matches!(Arc::try_pin_init(EvenU64::new2(5)), Err(Error)));
assert!(matches!(Box::try_init(EvenU64::new2(3)), Err(Error)));
assert!(matches!(Arc::try_init(EvenU64::new2(5)), Err(Error)));
}
#[test]
#[cfg(any(feature = "std", feature = "alloc"))]
fn with_failing_inner() {
let mut buf = Box::pin_init(RingBuffer::<EvenU64, 4>::new()).unwrap();
assert_eq!(buf.as_mut().try_push(EvenU64::new(0)), Ok(true));
assert_eq!(buf.as_mut().try_push(EvenU64::new(1)), Err(()));
assert_eq!(buf.as_mut().try_push(EvenU64::new(2)), Ok(true));
assert_eq!(buf.as_mut().try_push(EvenU64::new(3)), Err(()));
assert_eq!(buf.as_mut().try_push(EvenU64::new(4)), Ok(true));
assert_eq!(buf.as_mut().try_push(EvenU64::new(5)), Ok(false));
assert_eq!(buf.as_mut().try_push(EvenU64::new(6)), Ok(false));
assert_eq!(
buf.as_mut().pop(),
Some(EvenU64 {
info: "Hello world!".to_owned(),
data: 0
})
);
assert_eq!(
buf.as_mut().pop(),
Some(EvenU64 {
info: "Hello world!".to_owned(),
data: 2
})
);
assert_eq!(
buf.as_mut().pop(),
Some(EvenU64 {
info: "Hello world!".to_owned(),
data: 4
})
);
assert_eq!(buf.as_mut().pop(), None);
}
#[allow(dead_code)]
#[derive(Debug)]
struct BigStruct {
buf: [u8; 1024 * 1024],
oth: MaybeUninit<u8>,
}
#[test]
#[cfg(any(feature = "std", feature = "alloc"))]
#[cfg_attr(miri, ignore)]
fn big_struct() {
let x = Arc::init(init!(BigStruct {
buf <- init_zeroed(),
oth <- init_zeroed(),
}));
println!("{x:?}");
let x = Box::init(init!(BigStruct {
buf <- init_zeroed(),
oth <- init_zeroed(),
}));
println!("{x:?}");
}
#[test]
#[cfg(any(feature = "std", feature = "alloc"))]
#[cfg_attr(miri, ignore)]
fn with_big_struct() {
#[allow(unused_attributes)]
#[path = "../examples/mutex.rs"]
mod mutex;
use mutex::*;
let buf = Arc::pin_init(CMutex::new(RingBuffer::<BigStruct, 64>::new())).unwrap();
let mut buf = buf.lock();
for _ in 0..63 {
assert_eq!(
buf.as_mut().try_push(init!(BigStruct{
buf <- init_zeroed(),
oth <- uninit::<_, Infallible>(),
})),
Ok(true)
);
}
assert_eq!(
buf.as_mut().try_push(init!(BigStruct{
buf <- init_zeroed(),
oth <- uninit::<_, Infallible>(),
})),
Ok(false)
);
for _ in 0..63 {
assert!(buf.as_mut().pop_no_stack().is_some());
}
}
#[test]
#[cfg(feature = "alloc")]
#[cfg_attr(any(miri, NO_ALLOC_FAIL_TESTS, target_os = "macos"), ignore)]
fn too_big_pinned() {
use core::alloc::AllocError;
// should be too big with current hardware.
assert!(matches!(
Box::pin_init(RingBuffer::<u8, { 1024 * 1024 * 1024 * 1024 }>::new()),
Err(AllocError)
));
// should be too big with current hardware.
assert!(matches!(
Arc::pin_init(RingBuffer::<u8, { 1024 * 1024 * 1024 * 1024 }>::new()),
Err(AllocError)
));
}