Debian Codegraph @

third_party/rust/triple_buffer/src/lib.rs

raw
1 //! Triple buffering in Rust
2 //!
3 //! In this crate, we propose a Rust implementation of triple buffering. This is
4 //! a non-blocking thread synchronization mechanism that can be used when a
5 //! single producer thread is frequently updating a shared data block, and a
6 //! single consumer thread wants to be able to read the latest available version
7 //! of the shared data whenever it feels like it.
8 //!
9 //! # Examples
10 //!
11 //! For many use cases, you can use the ergonomic write/read interface, where
12 //! the producer moves values into the buffer and the consumer accesses the
13 //! latest buffer by shared reference:
14 //!
15 //! ```
16 //! // Create a triple buffer
17 //! use triple_buffer::TripleBuffer;
18 //! let buf = TripleBuffer::new(0);
19 //!
20 //! // Split it into an input and output interface, to be respectively sent to
21 //! // the producer thread and the consumer thread
22 //! let (mut buf_input, mut buf_output) = buf.split();
23 //!
24 //! // The producer can move a value into the buffer at any time
25 //! buf_input.write(42);
26 //!
27 //! // The consumer can access the latest value from the producer at any time
28 //! let latest_value_ref = buf_output.read();
29 //! assert_eq!(*latest_value_ref, 42);
30 //! ```
31 //!
32 //! In situations where moving the original value away and being unable to
33 //! modify it on the consumer's side is too costly, such as if creating a new
34 //! value involves dynamic memory allocation, you can use a lower-level API
35 //! which allows you to access the producer and consumer's buffers in place
36 //! and to precisely control when updates are propagated:
37 //!
38 //! ```
39 //! // Create and split a triple buffer
40 //! use triple_buffer::TripleBuffer;
41 //! let buf = TripleBuffer::new(String::with_capacity(42));
42 //! let (mut buf_input, mut buf_output) = buf.split();
43 //!
44 //! // Mutate the input buffer in place
45 //! {
46 //! // Acquire a reference to the input buffer
47 //! let input = buf_input.input_buffer();
48 //!
49 //! // In general, you don't know what's inside of the buffer, so you should
50 //! // always reset the value before use (this is a type-specific process).
51 //! input.clear();
52 //!
53 //! // Perform an in-place update
54 //! input.push_str("Hello, ");
55 //! }
56 //!
57 //! // Publish the above input buffer update
58 //! buf_input.publish();
59 //!
60 //! // Manually fetch the buffer update from the consumer interface
61 //! buf_output.update();
62 //!
63 //! // Acquire a mutable reference to the output buffer
64 //! let output = buf_output.output_buffer();
65 //!
66 //! // Post-process the output value before use
67 //! output.push_str("world!");
68 //! ```
69
70 #![deny(missing_debug_implementations, missing_docs)]
71
72 use cache_padded::CachePadded;
73
74 use std::{
75 cell::UnsafeCell,
76 sync::{
77 atomic::{AtomicU8, Ordering},
78 Arc,
79 },
80 };
81
82 /// A triple buffer, useful for nonblocking and thread-safe data sharing
83 ///
84 /// A triple buffer is a single-producer single-consumer nonblocking
85 /// communication channel which behaves like a shared variable: the producer
86 /// submits regular updates, and the consumer accesses the latest available
87 /// value whenever it feels like it.
88 ///
89 #[derive(Debug)]
90 pub struct TripleBuffer<T: Send> {
91 /// Input object used by producers to send updates
92 input: Input<T>,
93
94 /// Output object used by consumers to read the current value
95 output: Output<T>,
96 }
97 //
98 impl<T: Clone + Send> TripleBuffer<T> {
99 /// Construct a triple buffer with a certain initial value
100 //
101 // FIXME: After spending some time thinking about this further, I reached
102 // the conclusion that clippy was right after all. But since this is
103 // a breaking change, I'm keeping that for the next major release.
104 //
105 #[allow(clippy::needless_pass_by_value)]
106 pub fn new(initial: T) -> Self {
107 Self::new_impl(|| initial.clone())
108 }
109 }
110 //
111 impl<T: Default + Send> Default for TripleBuffer<T> {
112 /// Construct a triple buffer with a default-constructed value
113 fn default() -> Self {
114 Self::new_impl(T::default)
115 }
116 }
117 //
118 impl<T: Send> TripleBuffer<T> {
119 /// Construct a triple buffer, using a functor to generate initial values
120 fn new_impl(mut generator: impl FnMut() -> T) -> Self {
121 // Start with the shared state...
122 let shared_state = Arc::new(SharedState::new(|_i| generator(), 0));
123
124 // ...then construct the input and output structs
125 TripleBuffer {
126 input: Input {
127 shared: shared_state.clone(),
128 input_idx: 1,
129 },
130 output: Output {
131 shared: shared_state,
132 output_idx: 2,
133 },
134 }
135 }
136
137 /// Extract input and output of the triple buffer
138 //
139 // NOTE: Although it would be nicer to directly return `Input` and `Output`
140 // from `new()`, the `split()` design gives some API evolution
141 // headroom towards future allocation-free modes of operation where
142 // the SharedState is a static variable, or a stack-allocated variable
143 // used through scoped threads or other unsafe thread synchronization.
144 //
145 // See https://github.com/HadrienG2/triple-buffer/issues/8 .
146 //
147 pub fn split(self) -> (Input<T>, Output<T>) {
148 (self.input, self.output)
149 }
150 }
151 //
152 // The Clone and PartialEq traits are used internally for testing and I don't
153 // want to commit to supporting them publicly for now.
154 //
155 #[doc(hidden)]
156 impl<T: Clone + Send> Clone for TripleBuffer<T> {
157 fn clone(&self) -> Self {
158 // Clone the shared state. This is safe because at this layer of the
159 // interface, one needs an Input/Output &mut to mutate the shared state.
160 let shared_state = Arc::new(unsafe { (*self.input.shared).clone() });
161
162 // ...then the input and output structs
163 TripleBuffer {
164 input: Input {
165 shared: shared_state.clone(),
166 input_idx: self.input.input_idx,
167 },
168 output: Output {
169 shared: shared_state,
170 output_idx: self.output.output_idx,
171 },
172 }
173 }
174 }
175 //
176 #[doc(hidden)]
177 impl<T: PartialEq + Send> PartialEq for TripleBuffer<T> {
178 fn eq(&self, other: &Self) -> bool {
179 // Compare the shared states. This is safe because at this layer of the
180 // interface, one needs an Input/Output &mut to mutate the shared state.
181 let shared_states_equal = unsafe { (*self.input.shared).eq(&*other.input.shared) };
182
183 // Compare the rest of the triple buffer states
184 shared_states_equal
185 && (self.input.input_idx == other.input.input_idx)
186 && (self.output.output_idx == other.output.output_idx)
187 }
188 }
189
190 /// Producer interface to the triple buffer
191 ///
192 /// The producer of data can use this struct to submit updates to the triple
193 /// buffer whenever he likes. These updates are nonblocking: a collision between
194 /// the producer and the consumer will result in cache contention, but deadlocks
195 /// and scheduling-induced slowdowns cannot happen.
196 ///
197 #[derive(Debug)]
198 pub struct Input<T: Send> {
199 /// Reference-counted shared state
200 shared: Arc<SharedState<T>>,
201
202 /// Index of the input buffer (which is private to the producer)
203 input_idx: BufferIndex,
204 }
205 //
206 // Public interface
207 impl<T: Send> Input<T> {
208 /// Write a new value into the triple buffer
209 pub fn write(&mut self, value: T) {
210 // Update the input buffer
211 *self.input_buffer() = value;
212
213 // Publish our update to the consumer
214 self.publish();
215 }
216
217 /// Check if the consumer has fetched our last submission yet
218 ///
219 /// This method is only intended for diagnostics purposes. Please do not let
220 /// it inform your decision of sending or not sending a value, as that would
221 /// effectively be building a very poor spinlock-based double buffer
222 /// implementation. If what you truly need is a double buffer, build
223 /// yourself a proper blocking one instead of wasting CPU time.
224 ///
225 pub fn consumed(&self) -> bool {
226 let back_info = self.shared.back_info.load(Ordering::Relaxed);
227 back_info & BACK_DIRTY_BIT == 0
228 }
229
230 /// Access the input buffer directly
231 ///
232 /// This advanced interface allows you to update the input buffer in place,
233 /// so that you can avoid creating values of type T repeatedy just to push
234 /// them into the triple buffer when doing so is expensive.
235 ///
236 /// However, by using it, you force yourself to take into account some
237 /// implementation subtleties that you could normally ignore.
238 ///
239 /// First, the buffer does not contain the last value that you published
240 /// (which is now available to the consumer thread). In fact, what you get
241 /// may not match _any_ value that you sent in the past, but rather be a new
242 /// value that was written in there by the consumer thread. All you can
243 /// safely assume is that the buffer contains a valid value of type T, which
244 /// you may need to "clean up" before use using a type-specific process.
245 ///
246 /// Second, we do not send updates automatically. You need to call
247 /// `publish()` in order to propagate a buffer update to the consumer.
248 /// Alternative designs based on Drop were considered, but considered too
249 /// magical for the target audience of this interface.
250 ///
251 pub fn input_buffer(&mut self) -> &mut T {
252 // This is safe because the synchronization protocol ensures that we
253 // have exclusive access to this buffer.
254 let input_ptr = self.shared.buffers[self.input_idx as usize].get();
255 unsafe { &mut *input_ptr }
256 }
257
258 /// Publish the current input buffer, checking for overwrites
259 ///
260 /// After updating the input buffer using `input_buffer()`, you can use this
261 /// method to publish your updates to the consumer.
262 ///
263 /// This will replace the current input buffer with another one, as you
264 /// cannot continue using the old one while the consumer is accessing it.
265 ///
266 /// It will also tell you whether you overwrote a value which was not read
267 /// by the consumer thread.
268 ///
269 pub fn publish(&mut self) -> bool {
270 // Swap the input buffer and the back buffer, setting the dirty bit
271 //
272 // The ordering must be AcqRel, because...
273 //
274 // - Our accesses to the old buffer must not be reordered after this
275 // operation (which mandates Release ordering), otherwise they could
276 // race with the consumer accessing the freshly published buffer.
277 // - Our accesses from the buffer must not be reordered before this
278 // operation (which mandates Consume ordering, that is best
279 // approximated by Acquire in Rust), otherwise they would race with
280 // the consumer accessing the buffer as well before switching to
281 // another buffer.
282 // * This reordering may seem paradoxical, but could happen if the
283 // compiler or CPU correctly speculated the new buffer's index
284 // before that index is actually read, as well as on weird hardware
285 // with incoherent caches like GPUs or old DEC Alpha where keeping
286 // data in sync across cores requires manual action.
287 //
288 let former_back_info = self
289 .shared
290 .back_info
291 .swap(self.input_idx | BACK_DIRTY_BIT, Ordering::AcqRel);
292
293 // The old back buffer becomes our new input buffer
294 self.input_idx = former_back_info & BACK_INDEX_MASK;
295
296 // Tell whether we have overwritten unread data
297 former_back_info & BACK_DIRTY_BIT != 0
298 }
299
300 /// Deprecated alias to `input_buffer()`, please use that method instead
301 #[cfg(any(feature = "raw", test))]
302 #[deprecated(
303 since = "5.0.5",
304 note = "The \"raw\" feature is deprecated as the performance \
305 optimization that motivated it turned out to be incorrect. \
306 All functionality is now available without using feature flags."
307 )]
308 pub fn raw_input_buffer(&mut self) -> &mut T {
309 self.input_buffer()
310 }
311
312 /// Deprecated alias to `publish()`, please use that method instead
313 #[cfg(any(feature = "raw", test))]
314 #[deprecated(
315 since = "5.0.5",
316 note = "The \"raw\" feature is deprecated as the performance \
317 optimization that motivated it turned out to be incorrect. \
318 All functionality is now available without using feature flags."
319 )]
320 pub fn raw_publish(&mut self) -> bool {
321 self.publish()
322 }
323 }
324
325 /// Consumer interface to the triple buffer
326 ///
327 /// The consumer of data can use this struct to access the latest published
328 /// update from the producer whenever he likes. Readout is nonblocking: a
329 /// collision between the producer and consumer will result in cache contention,
330 /// but deadlocks and scheduling-induced slowdowns cannot happen.
331 ///
332 #[derive(Debug)]
333 pub struct Output<T: Send> {
334 /// Reference-counted shared state
335 shared: Arc<SharedState<T>>,
336
337 /// Index of the output buffer (which is private to the consumer)
338 output_idx: BufferIndex,
339 }
340 //
341 // Public interface
342 impl<T: Send> Output<T> {
343 /// Access the latest value from the triple buffer
344 pub fn read(&mut self) -> &T {
345 // Fetch updates from the producer
346 self.update();
347
348 // Give access to the output buffer
349 self.output_buffer()
350 }
351
352 /// Tell whether a buffer update is incoming from the producer
353 ///
354 /// This method is only intended for diagnostics purposes. Please do not let
355 /// it inform your decision of reading a value or not, as that would
356 /// effectively be building a very poor spinlock-based double buffer
357 /// implementation. If what you truly need is a double buffer, build
358 /// yourself a proper blocking one instead of wasting CPU time.
359 ///
360 pub fn updated(&self) -> bool {
361 let back_info = self.shared.back_info.load(Ordering::Relaxed);
362 back_info & BACK_DIRTY_BIT != 0
363 }
364
365 /// Access the output buffer directly
366 ///
367 /// This advanced interface allows you to modify the contents of the output
368 /// buffer, so that you can avoid copying the output value when this is an
369 /// expensive process. One possible application, for example, is to
370 /// post-process values from the producer before use.
371 ///
372 /// However, by using it, you force yourself to take into account some
373 /// implementation subtleties that you could normally ignore.
374 ///
375 /// First, keep in mind that you can lose access to the current output
376 /// buffer any time `read()` or `update()` is called, as it may be replaced
377 /// by an updated buffer from the producer automatically.
378 ///
379 /// Second, to reduce the potential for the aforementioned usage error, this
380 /// method does not update the output buffer automatically. You need to call
381 /// `update()` in order to fetch buffer updates from the producer.
382 ///
383 pub fn output_buffer(&mut self) -> &mut T {
384 // This is safe because the synchronization protocol ensures that we
385 // have exclusive access to this buffer.
386 let output_ptr = self.shared.buffers[self.output_idx as usize].get();
387 unsafe { &mut *output_ptr }
388 }
389
390 /// Update the output buffer
391 ///
392 /// Check if the producer submitted a new data version, and if one is
393 /// available, update our output buffer to use it. Return a flag that tells
394 /// you whether such an update was carried out.
395 ///
396 /// Bear in mind that when this happens, you will lose any change that you
397 /// performed to the output buffer via the `output_buffer()` interface.
398 ///
399 pub fn update(&mut self) -> bool {
400 // Access the shared state
401 let shared_state = &(*self.shared);
402
403 // Check if an update is present in the back-buffer
404 let updated = self.updated();
405 if updated {
406 // If so, exchange our output buffer with the back-buffer, thusly
407 // acquiring exclusive access to the old back buffer while giving
408 // the producer a new back-buffer to write to.
409 //
410 // The ordering must be AcqRel, because...
411 //
412 // - Our accesses to the previous buffer must not be reordered after
413 // this operation (which mandates Release ordering), otherwise
414 // they could race with the producer accessing the freshly
415 // liberated buffer.
416 // - Our accesses from the buffer must not be reordered before this
417 // operation (which mandates Consume ordering, that is best
418 // approximated by Acquire in Rust), otherwise they would race
419 // with the producer writing into the buffer before publishing it.
420 // * This reordering may seem paradoxical, but could happen if the
421 // compiler or CPU correctly speculated the new buffer's index
422 // before that index is actually read, as well as on weird hardware
423 // like GPUs where CPU caches require manual synchronization.
424 //
425 let former_back_info = shared_state
426 .back_info
427 .swap(self.output_idx, Ordering::AcqRel);
428
429 // Make the old back-buffer our new output buffer
430 self.output_idx = former_back_info & BACK_INDEX_MASK;
431 }
432
433 // Tell whether an update was carried out
434 updated
435 }
436
437 /// Deprecated alias to `output_buffer()`, please use that method instead
438 #[cfg(any(feature = "raw", test))]
439 #[deprecated(
440 since = "5.0.5",
441 note = "The \"raw\" feature is deprecated as the performance \
442 optimization that motivated it turned out to be incorrect. \
443 All functionality is now available without using feature flags."
444 )]
445 pub fn raw_output_buffer(&mut self) -> &mut T {
446 self.output_buffer()
447 }
448 /// Deprecated alias to `update()`, please use that method instead
449 #[cfg(any(feature = "raw", test))]
450 #[deprecated(
451 since = "5.0.5",
452 note = "The \"raw\" feature is deprecated as the performance \
453 optimization that motivated it turned out to be incorrect. \
454 All functionality is now available without using feature flags."
455 )]
456 #[cfg(any(feature = "raw", test))]
457 pub fn raw_update(&mut self) -> bool {
458 self.update()
459 }
460 }
461
462 /// Triple buffer shared state
463 ///
464 /// In a triple buffering communication protocol, the producer and consumer
465 /// share the following storage:
466 ///
467 /// - Three memory buffers suitable for storing the data at hand
468 /// - Information about the back-buffer: which buffer is the current back-buffer
469 /// and whether an update was published since the last readout.
470 ///
471 #[derive(Debug)]
472 struct SharedState<T: Send> {
473 /// Data storage buffers
474 buffers: [CachePadded<UnsafeCell<T>>; 3],
475
476 /// Information about the current back-buffer state
477 back_info: CachePadded<AtomicBackBufferInfo>,
478 }
479 //
480 #[doc(hidden)]
481 impl<T: Send> SharedState<T> {
482 /// Given (a way to generate) buffer contents and the back info, build the shared state
483 fn new(mut gen_buf_data: impl FnMut(usize) -> T, back_info: BackBufferInfo) -> Self {
484 let mut make_buf = |i| -> CachePadded<UnsafeCell<T>> {
485 CachePadded::new(UnsafeCell::new(gen_buf_data(i)))
486 };
487 Self {
488 buffers: [make_buf(0), make_buf(1), make_buf(2)],
489 back_info: CachePadded::new(AtomicBackBufferInfo::new(back_info)),
490 }
491 }
492 }
493 //
494 #[doc(hidden)]
495 impl<T: Clone + Send> SharedState<T> {
496 /// Cloning the shared state is unsafe because you must ensure that no one
497 /// is concurrently accessing it, since &self is enough for writing.
498 unsafe fn clone(&self) -> Self {
499 Self::new(
500 |i| (*self.buffers[i].get()).clone(),
501 self.back_info.load(Ordering::Relaxed),
502 )
503 }
504 }
505 //
506 #[doc(hidden)]
507 impl<T: PartialEq + Send> SharedState<T> {
508 /// Equality is unsafe for the same reason as cloning: you must ensure that
509 /// no one is concurrently accessing the triple buffer to avoid data races.
510 unsafe fn eq(&self, other: &Self) -> bool {
511 // Check whether the contents of all buffers are equal...
512 let buffers_equal = self
513 .buffers
514 .iter()
515 .zip(other.buffers.iter())
516 .all(|tuple| -> bool {
517 let (cell1, cell2) = tuple;
518 *cell1.get() == *cell2.get()
519 });
520
521 // ...then check whether the rest of the shared state is equal
522 buffers_equal
523 && (self.back_info.load(Ordering::Relaxed) == other.back_info.load(Ordering::Relaxed))
524 }
525 }
526 //
527 unsafe impl<T: Send> Sync for SharedState<T> {}
528
529 // Index types used for triple buffering
530 //
531 // These types are used to index into triple buffers. In addition, the
532 // BackBufferInfo type is actually a bitfield, whose third bit (numerical
533 // value: 4) is set to 1 to indicate that the producer published an update into
534 // the back-buffer, and reset to 0 when the consumer fetches the update.
535 //
536 type BufferIndex = u8;
537 type BackBufferInfo = BufferIndex;
538 //
539 type AtomicBackBufferInfo = AtomicU8;
540 const BACK_INDEX_MASK: u8 = 0b11; // Mask used to extract back-buffer index
541 const BACK_DIRTY_BIT: u8 = 0b100; // Bit set by producer to signal updates
542
543 /// Unit tests
544 #[cfg(test)]
545 mod tests {
546 use super::{BufferIndex, SharedState, TripleBuffer, BACK_DIRTY_BIT, BACK_INDEX_MASK};
547
548 use std::{fmt::Debug, ops::Deref, sync::atomic::Ordering, thread, time::Duration};
549
550 use testbench::{
551 self,
552 race_cell::{RaceCell, Racey},
553 };
554
555 /// Check that triple buffers are properly initialized
556 #[test]
557 fn initial_state() {
558 // Let's create a triple buffer
559 let mut buf = TripleBuffer::new(42);
560 check_buf_state(&mut buf, false);
561 assert_eq!(*buf.output.read(), 42);
562 }
563
564 /// Check that the shared state's unsafe equality operator works
565 #[test]
566 fn partial_eq_shared() {
567 // Let's create some dummy shared state
568 let dummy_state = SharedState::<u16>::new(|i| [111, 222, 333][i], 0b10);
569
570 // Check that the dummy state is equal to itself
571 assert!(unsafe { dummy_state.eq(&dummy_state) });
572
573 // Check that it's not equal to a state where buffer contents differ
574 assert!(unsafe { !dummy_state.eq(&SharedState::<u16>::new(|i| [114, 222, 333][i], 0b10)) });
575 assert!(unsafe { !dummy_state.eq(&SharedState::<u16>::new(|i| [111, 225, 333][i], 0b10)) });
576 assert!(unsafe { !dummy_state.eq(&SharedState::<u16>::new(|i| [111, 222, 336][i], 0b10)) });
577
578 // Check that it's not equal to a state where the back info differs
579 assert!(unsafe {
580 !dummy_state.eq(&SharedState::<u16>::new(
581 |i| [111, 222, 333][i],
582 BACK_DIRTY_BIT & 0b10,
583 ))
584 });
585 assert!(unsafe { !dummy_state.eq(&SharedState::<u16>::new(|i| [111, 222, 333][i], 0b01)) });
586 }
587
588 /// Check that TripleBuffer's PartialEq impl works
589 #[test]
590 fn partial_eq() {
591 // Create a triple buffer
592 let buf = TripleBuffer::new("test");
593
594 // Check that it is equal to itself
595 assert_eq!(buf, buf);
596
597 // Make another buffer with different contents. As buffer creation is
598 // deterministic, this should only have an impact on the shared state,
599 // but the buffers should nevertheless be considered different.
600 let buf2 = TripleBuffer::new("taste");
601 assert_eq!(buf.input.input_idx, buf2.input.input_idx);
602 assert_eq!(buf.output.output_idx, buf2.output.output_idx);
603 assert!(buf != buf2);
604
605 // Check that changing either the input or output buffer index will
606 // also lead two TripleBuffers to be considered different (this test
607 // technically creates an invalid TripleBuffer state, but it's the only
608 // way to check that the PartialEq impl is exhaustive)
609 let mut buf3 = TripleBuffer::new("test");
610 assert_eq!(buf, buf3);
611 let old_input_idx = buf3.input.input_idx;
612 buf3.input.input_idx = buf3.output.output_idx;
613 assert!(buf != buf3);
614 buf3.input.input_idx = old_input_idx;
615 buf3.output.output_idx = old_input_idx;
616 assert!(buf != buf3);
617 }
618
619 /// Check that the shared state's unsafe clone operator works
620 #[test]
621 fn clone_shared() {
622 // Let's create some dummy shared state
623 let dummy_state = SharedState::<u8>::new(|i| [123, 231, 132][i], BACK_DIRTY_BIT & 0b01);
624
625 // Now, try to clone it
626 let dummy_state_copy = unsafe { dummy_state.clone() };
627
628 // Check that the contents of the original state did not change
629 assert!(unsafe {
630 dummy_state.eq(&SharedState::<u8>::new(
631 |i| [123, 231, 132][i],
632 BACK_DIRTY_BIT & 0b01,
633 ))
634 });
635
636 // Check that the contents of the original and final state are identical
637 assert!(unsafe { dummy_state.eq(&dummy_state_copy) });
638 }
639
640 /// Check that TripleBuffer's Clone impl works
641 #[test]
642 fn clone() {
643 // Create a triple buffer
644 let mut buf = TripleBuffer::new(4.2);
645
646 // Put it in a nontrivial state
647 unsafe {
648 *buf.input.shared.buffers[0].get() = 1.2;
649 *buf.input.shared.buffers[1].get() = 3.4;
650 *buf.input.shared.buffers[2].get() = 5.6;
651 }
652 buf.input
653 .shared
654 .back_info
655 .store(BACK_DIRTY_BIT & 0b01, Ordering::Relaxed);
656 buf.input.input_idx = 0b10;
657 buf.output.output_idx = 0b00;
658
659 // Now clone it
660 let buf_clone = buf.clone();
661
662 // Check that the clone uses its own, separate shared data storage
663 assert_eq!(
664 as_ptr(&buf_clone.output.shared),
665 as_ptr(&buf_clone.output.shared)
666 );
667 assert!(as_ptr(&buf_clone.input.shared) != as_ptr(&buf.input.shared));
668
669 // Check that it is identical from PartialEq's point of view
670 assert_eq!(buf, buf_clone);
671
672 // Check that the contents of the original buffer did not change
673 unsafe {
674 assert_eq!(*buf.input.shared.buffers[0].get(), 1.2);
675 assert_eq!(*buf.input.shared.buffers[1].get(), 3.4);
676 assert_eq!(*buf.input.shared.buffers[2].get(), 5.6);
677 }
678 assert_eq!(
679 buf.input.shared.back_info.load(Ordering::Relaxed),
680 BACK_DIRTY_BIT & 0b01
681 );
682 assert_eq!(buf.input.input_idx, 0b10);
683 assert_eq!(buf.output.output_idx, 0b00);
684 }
685
686 /// Check that the low-level publish/update primitives work
687 #[test]
688 fn swaps() {
689 // Create a new buffer, and a way to track any changes to it
690 let mut buf = TripleBuffer::new([123, 456]);
691 let old_buf = buf.clone();
692 let old_input_idx = old_buf.input.input_idx;
693 let old_shared = &old_buf.input.shared;
694 let old_back_info = old_shared.back_info.load(Ordering::Relaxed);
695 let old_back_idx = old_back_info & BACK_INDEX_MASK;
696 let old_output_idx = old_buf.output.output_idx;
697
698 // Check that updating from a clean state works
699 assert!(!buf.output.update());
700 assert_eq!(buf, old_buf);
701 check_buf_state(&mut buf, false);
702
703 // Check that publishing from a clean state works
704 assert!(!buf.input.publish());
705 let mut expected_buf = old_buf.clone();
706 expected_buf.input.input_idx = old_back_idx;
707 expected_buf
708 .input
709 .shared
710 .back_info
711 .store(old_input_idx | BACK_DIRTY_BIT, Ordering::Relaxed);
712 assert_eq!(buf, expected_buf);
713 check_buf_state(&mut buf, true);
714
715 // Check that overwriting a dirty state works
716 assert!(buf.input.publish());
717 let mut expected_buf = old_buf.clone();
718 expected_buf.input.input_idx = old_input_idx;
719 expected_buf
720 .input
721 .shared
722 .back_info
723 .store(old_back_idx | BACK_DIRTY_BIT, Ordering::Relaxed);
724 assert_eq!(buf, expected_buf);
725 check_buf_state(&mut buf, true);
726
727 // Check that updating from a dirty state works
728 assert!(buf.output.update());
729 expected_buf.output.output_idx = old_back_idx;
730 expected_buf
731 .output
732 .shared
733 .back_info
734 .store(old_output_idx, Ordering::Relaxed);
735 assert_eq!(buf, expected_buf);
736 check_buf_state(&mut buf, false);
737 }
738
739 /// Check that (sequentially) writing to a triple buffer works
740 #[test]
741 fn sequential_write() {
742 // Let's create a triple buffer
743 let mut buf = TripleBuffer::new(false);
744
745 // Back up the initial buffer state
746 let old_buf = buf.clone();
747
748 // Perform a write
749 buf.input.write(true);
750
751 // Check new implementation state
752 {
753 // Starting from the old buffer state...
754 let mut expected_buf = old_buf.clone();
755
756 // ...write the new value in and swap...
757 *expected_buf.input.input_buffer() = true;
758 expected_buf.input.publish();
759
760 // Nothing else should have changed
761 assert_eq!(buf, expected_buf);
762 check_buf_state(&mut buf, true);
763 }
764 }
765
766 /// Check that (sequentially) reading from a triple buffer works
767 #[test]
768 fn sequential_read() {
769 // Let's create a triple buffer and write into it
770 let mut buf = TripleBuffer::new(1.0);
771 buf.input.write(4.2);
772
773 // Test readout from dirty (freshly written) triple buffer
774 {
775 // Back up the initial buffer state
776 let old_buf = buf.clone();
777
778 // Read from the buffer
779 let result = *buf.output.read();
780
781 // Output value should be correct
782 assert_eq!(result, 4.2);
783
784 // Result should be equivalent to carrying out an update
785 let mut expected_buf = old_buf.clone();
786 assert!(expected_buf.output.update());
787 assert_eq!(buf, expected_buf);
788 check_buf_state(&mut buf, false);
789 }
790
791 // Test readout from clean (unchanged) triple buffer
792 {
793 // Back up the initial buffer state
794 let old_buf = buf.clone();
795
796 // Read from the buffer
797 let result = *buf.output.read();
798
799 // Output value should be correct
800 assert_eq!(result, 4.2);
801
802 // Buffer state should be unchanged
803 assert_eq!(buf, old_buf);
804 check_buf_state(&mut buf, false);
805 }
806 }
807
808 /// Check that contended concurrent reads and writes work
809 #[test]
810 #[ignore]
811 fn contended_concurrent_read_write() {
812 // We will stress the infrastructure by performing this many writes
813 // as a reader continuously reads the latest value
814 const TEST_WRITE_COUNT: usize = 100_000_000;
815
816 // This is the buffer that our reader and writer will share
817 let buf = TripleBuffer::new(RaceCell::new(0));
818 let (mut buf_input, mut buf_output) = buf.split();
819
820 // Concurrently run a writer which increments a shared value in a loop,
821 // and a reader which makes sure that no unexpected value slips in.
822 let mut last_value = 0usize;
823 testbench::concurrent_test_2(
824 move || {
825 for value in 1..=TEST_WRITE_COUNT {
826 buf_input.write(RaceCell::new(value));
827 }
828 },
829 move || {
830 while last_value < TEST_WRITE_COUNT {
831 let new_racey_value = buf_output.read().get();
832 match new_racey_value {
833 Racey::Consistent(new_value) => {
834 assert!((new_value >= last_value) && (new_value <= TEST_WRITE_COUNT));
835 last_value = new_value;
836 }
837 Racey::Inconsistent => {
838 panic!("Inconsistent state exposed by the buffer!");
839 }
840 }
841 }
842 },
843 );
844 }
845
846 /// Check that uncontended concurrent reads and writes work
847 ///
848 /// **WARNING:** This test unfortunately needs to have timing-dependent
849 /// behaviour to do its job. If it fails for you, try the following:
850 ///
851 /// - Close running applications in the background
852 /// - Re-run the tests with only one OS thread (--test-threads=1)
853 /// - Increase the writer sleep period
854 ///
855 #[test]
856 #[ignore]
857 fn uncontended_concurrent_read_write() {
858 // We will stress the infrastructure by performing this many writes
859 // as a reader continuously reads the latest value
860 const TEST_WRITE_COUNT: usize = 625;
861
862 // This is the buffer that our reader and writer will share
863 let buf = TripleBuffer::new(RaceCell::new(0));
864 let (mut buf_input, mut buf_output) = buf.split();
865
866 // Concurrently run a writer which slowly increments a shared value,
867 // and a reader which checks that it can receive every update
868 let mut last_value = 0usize;
869 testbench::concurrent_test_2(
870 move || {
871 for value in 1..=TEST_WRITE_COUNT {
872 buf_input.write(RaceCell::new(value));
873 thread::yield_now();
874 thread::sleep(Duration::from_millis(32));
875 }
876 },
877 move || {
878 while last_value < TEST_WRITE_COUNT {
879 let new_racey_value = buf_output.read().get();
880 match new_racey_value {
881 Racey::Consistent(new_value) => {
882 assert!((new_value >= last_value) && (new_value - last_value <= 1));
883 last_value = new_value;
884 }
885 Racey::Inconsistent => {
886 panic!("Inconsistent state exposed by the buffer!");
887 }
888 }
889 }
890 },
891 );
892 }
893
894 /// Through the low-level API, the consumer is allowed to modify its
895 /// bufffer, which means that it will unknowingly send back data to the
896 /// producer. This creates new correctness requirements for the
897 /// synchronization protocol, which must be checked as well.
898 #[test]
899 #[ignore]
900 fn concurrent_bidirectional_exchange() {
901 // We will stress the infrastructure by performing this many writes
902 // as a reader continuously reads the latest value
903 const TEST_WRITE_COUNT: usize = 100_000_000;
904
905 // This is the buffer that our reader and writer will share
906 let buf = TripleBuffer::new(RaceCell::new(0));
907 let (mut buf_input, mut buf_output) = buf.split();
908
909 // Concurrently run a writer which increments a shared value in a loop,
910 // and a reader which makes sure that no unexpected value slips in.
911 testbench::concurrent_test_2(
912 move || {
913 for new_value in 1..=TEST_WRITE_COUNT {
914 match buf_input.input_buffer().get() {
915 Racey::Consistent(curr_value) => {
916 assert!(curr_value <= new_value);
917 }
918 Racey::Inconsistent => {
919 panic!("Inconsistent state exposed by the buffer!");
920 }
921 }
922 buf_input.write(RaceCell::new(new_value));
923 }
924 },
925 move || {
926 let mut last_value = 0usize;
927 while last_value < TEST_WRITE_COUNT {
928 match buf_output.output_buffer().get() {
929 Racey::Consistent(new_value) => {
930 assert!((new_value >= last_value) && (new_value <= TEST_WRITE_COUNT));
931 last_value = new_value;
932 }
933 Racey::Inconsistent => {
934 panic!("Inconsistent state exposed by the buffer!");
935 }
936 }
937 if buf_output.updated() {
938 buf_output.output_buffer().set(last_value / 2);
939 buf_output.update();
940 }
941 }
942 },
943 );
944 }
945
946 /// Range check for triple buffer indexes
947 #[allow(unused_comparisons)]
948 fn index_in_range(idx: BufferIndex) -> bool {
949 (idx >= 0) & (idx <= 2)
950 }
951
952 /// Get a pointer to the target of some reference (e.g. an &, an Arc...)
953 fn as_ptr<P: Deref>(ref_like: &P) -> *const P::Target {
954 &(**ref_like) as *const _
955 }
956
957 /// Check the state of a buffer, and the effect of queries on it
958 fn check_buf_state<T>(buf: &mut TripleBuffer<T>, expected_dirty_bit: bool)
959 where
960 T: Clone + Debug + PartialEq + Send,
961 {
962 // Make a backup of the buffer's initial state
963 let initial_buf = buf.clone();
964
965 // Check that the input and output point to the same shared state
966 assert_eq!(as_ptr(&buf.input.shared), as_ptr(&buf.output.shared));
967
968 // Access the shared state and decode back-buffer information
969 let back_info = buf.input.shared.back_info.load(Ordering::Relaxed);
970 let back_idx = back_info & BACK_INDEX_MASK;
971 let back_buffer_dirty = back_info & BACK_DIRTY_BIT != 0;
972
973 // Input-/output-/back-buffer indexes must be in range
974 assert!(index_in_range(buf.input.input_idx));
975 assert!(index_in_range(buf.output.output_idx));
976 assert!(index_in_range(back_idx));
977
978 // Input-/output-/back-buffer indexes must be distinct
979 assert!(buf.input.input_idx != buf.output.output_idx);
980 assert!(buf.input.input_idx != back_idx);
981 assert!(buf.output.output_idx != back_idx);
982
983 // Back-buffer must have the expected dirty bit
984 assert_eq!(back_buffer_dirty, expected_dirty_bit);
985
986 // Check that the "input buffer" query behaves as expected
987 assert_eq!(
988 as_ptr(&buf.input.input_buffer()),
989 buf.input.shared.buffers[buf.input.input_idx as usize].get()
990 );
991 assert_eq!(*buf, initial_buf);
992
993 // Check that the "consumed" query behaves as expected
994 assert_eq!(!buf.input.consumed(), expected_dirty_bit);
995 assert_eq!(*buf, initial_buf);
996
997 // Check that the output_buffer query works in the initial state
998 assert_eq!(
999 as_ptr(&buf.output.output_buffer()),
1000 buf.output.shared.buffers[buf.output.output_idx as usize].get()
1001 );
1002 assert_eq!(*buf, initial_buf);
1003
1004 // Check that the output buffer query works in the initial state
1005 assert_eq!(buf.output.updated(), expected_dirty_bit);
1006 assert_eq!(*buf, initial_buf);
1007 }
1008 }