hft_channel/
lib.rs

1//! # SPMC broadcast channel for HFT and real-time systems
2//!
3//! A lightweight, ultra-low-latency **single-producer / multi-consumer**
4//! broadcast channel designed for **high-frequency trading (HFT)** and other
5//! real-time systems.
6//!
7//! Provides predictable performance, minimal contention, and carefully
8//! controlled memory access patterns. Supports **thread-to-thread broadcasting**
9//! via local memory, or **inter-process communication** using shared memory.
10//!
11//! # Features
12//!
13//! * **Lock-free** single-producer / multi-consumer broadcast channel  
14//! * **Seq_no protocol** for overwrite detection  
15//! * **Spin-wait receivers** for ultra-low latency  
16//! * **Cache-friendly** layout (CachePadded)  
17//! * Works **between threads** or **between processes** via shared memory  
18//! * Zero allocations after initialization  
19//! * `no_std`-friendly design  
20//!
21//! # Spin-Wait Behavior
22//!
23//! Receivers use **busy-waiting** (spin loops) to wait for the producer to
24//! complete publishing the next message.
25//!
26//! **Implications:**
27//!
28//! * **Lowest possible latency** (no OS scheduling)  
29//! * A receiver consumes **one logical CPU core** while waiting  
30//! * Best when producer and receivers are on the **same NUMA node**  
31//! * Not ideal when power efficiency is important  
32//! * No OS blocking (by design)  
33//!
34//! This design is intended for **HFT**, **trading engines**, **matching
35//! engines**, **real-time telemetry**, and other performance-critical
36//! workloads.
37//!
38//! # Quick Example
39//!
40//! ```ignore
41//! use hft_channel::spmc_broadcast::channel;
42//!
43//! let (tx, rx) = channel::<u64>("/test", 512);
44//!
45//! let (_, payload) = tx.reserve();
46//! *payload = 42;
47//! tx.commit();
48//!
49//! let (_, payload) = rx.recv();
50//! ```
51//!
52//! # Design Overview
53//!
54//! Each slot’s state is encoded as:
55//!
56//! ```text
57//! [ dirty (1 bit, MSB) | seq_no (63 bits) ]
58//! ```
59//!
60//! Guarantees:
61//!
62//! * At least **one slot is always dirty**  
63//! * Dirty slot = currently being written  
64//! * Clean slot = readable and stable  
65//! * If a receiver observes a changed `seq_no`, the slot was overwritten  
66//!
67//! Typical protocol:
68//!
69//! 1. Sender marks the **next reserved** slot dirty  
70//! 2. Sender writes the payload into the **current reserved** slot  
71//! 3. Sender clears the dirty flag (commit)  
72//! 4. Receiver waits for `dirty == false`, then reads or copies the payload  
73
74#[cfg(not(unix))]
75compile_error!("This crate only supports Unix-like operating systems.");
76
77mod mmap;
78pub mod spmc_broadcast;
79mod utils;
80
81pub(crate) use mmap::{map_shared_memory, unmap_shared_memory};
82pub use utils::{Trials, mono_time_ns};