Expand description
This crate implements a zero-copy thread-safe double buffer with automatic swapping.
DoubleBuf is a data structure with two buffers (buffer 1 and buffer 2) and two users,
each having exclusive by-reference access to one of the buffers. The users can request read or write access
to the underlying buffer (we say that a user is active while it keeps this access), such that the following holds:
Whenever both users are inactive with at least one having requested write access since the last swap, the two buffers are atomically swapped.
Note that while we use the term “buffer”, any type T is allowed.
§Example
use doublebuf::*;
let db: DoubleBuf<u8> = DoubleBuf::new();
let (back, front) = db.init();
let mut writer = back.write();
let reader = front.read();
// Both are initialized with the default value
assert_eq!(*reader, 0);
assert_eq!(*writer, 0);
*writer = 5;
drop(writer);
drop(reader);
// the buffers are swapped now!
let reader = front.read();
assert_eq!(*reader, 5);§Notes
no_stdusage is explicitly allowed.- The implementation is lock-free on targets with atomic compare-and-swap on single bytes.
On targets without a native compare-and-swap (e.g.
thumbv6m, AVR), the application must configure one ofportable-atomic’s fallbacks, e.g. itscritical-sectionfeature together with acritical-sectionimplementation. - While double buffers conventionally have a “front” and a “back” buffer (the back buffer being used by the producer and the front buffer by the consumer), our implementation is completely symmetric.
- The buffers are not swapped if there has been no write access since the last swap.
- The semantics allow for a live-lock: If the two accessors are continuously overlapping their accesses (that is, if there is no point in time when neither is inactive), the buffers will never get swapped.
Structs§
- Accessor
- A user of the double buffer. There can only ever be exactly two Accessors associated with one initialized double buffer.
The accessor is exclusively associated to one of the two buffers, and can obtain access using the
Accessor::readorAccessor::writemethods. - Double
Buf - A thread-safe double buffer with automatic swapping. See module-level documentation for general notes. The usual workflow is as follows:
- Read
Guard - A guard that grants read access to the buffer currently associated with the
Accessor. Owning it indicates that theAccessoris active. Dropping the guard turns it inactive again and swaps the buffers if a swap is due and the otherAccessoris also inactive. - Write
Guard - A guard that grants write access to the buffer currently associated with the
Accessor. Owning it indicates that theAccessoris active and the associated buffer is dirty, i.e. due for a swap. Dropping the guard turns it inactive again and swaps the buffers if a swap is due and the otherAccessoris also inactive.