Skip to main content

Crate doublebuf

Crate doublebuf 

Source
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_std usage 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 of portable-atomic’s fallbacks, e.g. its critical-section feature together with a critical-section implementation.
  • 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::read or Accessor::write methods.
DoubleBuf
A thread-safe double buffer with automatic swapping. See module-level documentation for general notes. The usual workflow is as follows:
ReadGuard
A guard that grants read access to the buffer currently associated with the Accessor. Owning it indicates that the Accessor is active. Dropping the guard turns it inactive again and swaps the buffers if a swap is due and the other Accessor is also inactive.
WriteGuard
A guard that grants write access to the buffer currently associated with the Accessor. Owning it indicates that the Accessor is 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 other Accessor is also inactive.